Assuming the following code:
requiredIssue.get().isDone()
where requiredIssue is an Optional and it has been verified that requiredIssue.isPresent(). Does this code break the Law of Demeter? Technically there is a tight coupling here between my class and Optional now, because isDone() now relies on get() working properly.
But is it not reasonable to assume for the standard library to work consistently?
First,
does violate the Law of Demeter, which clearly enumerates the objects you can call methods on. Whatever object
get()returns is not in that list. For more detail on the Law itself, see this article.Second, the concrete example with
Optional. Callingget()of anOptionalhas many problems and should be avoided. The Law of Demeter (which is a sort-of canary in a coalmine for bad code) correctly indicates that this construct is flawed. Problems range from temporal coupling with theisPresent()call, technical leak of having to callisPresent()in the first place, to copying the "isPresent()" logic allover the place. Most of the time if you feel the need to useget()you are already doing it wrong.Third, the more general question of whether standard classes should be basically exempt from the Law of Demeter. They should not be exempt, if you are trying to do object-oriented programming. You have to keep in mind that some of the JDK, and most of the JEE are not actually meant to be used in an object-oriented environment. Sure, they use Java, which is a semi-object-oriented language, but they are expected to be used in a "mixed-paradigm" context, in which procedural designs are allowed. Just think of "Service" classes, pure "Data" objects (like Beans), layering, etc. These come from our procedural past, which some argue is still relevant and useful today.
Regardless where you stand on that debate, some of the standard classes/libraries/specifications are just not compatible with the Law of Demeter, or object-orientation in general. If you are willing to compromise on object-oriented principles (like most projects) that is not a problem. If you are actually not willing to compromise on a good design, but are forced to do so by libraries or standard classes, the solution is not to discuss the Law of Demeter away, but to recognize (and accept) that you are making an conscious decision to violate it.
So, is it reasonable to assume the standard library works? Sure! That does not mean they are exempt from good design principles, like the Law of Demeter, if you really want to stick with object-orientation.