Method chain with object values

Is it acceptable / good practice to use a method chain template for value objects (for example, return a new object instead)? Are there cases where this solution is implemented?

I cannot come up with any flaws, but I would like to hear your thought.

+4
source share
3 answers

Conclusion: this practice is quite acceptable.

I believe this generally happens when you have an immutable object. Instead of mutating the original object, a new one is created with the given value and returned. The arguments for and against this using a chain of methods are about the same as using mutable and immutable objects.

The only thing I would like to say is that it becomes understandable for callers of the class - they cannot depend on the equality of identity with the hooked object, and it should be clear that the call does not change the original object. Although, if they do connect calls, they will not assign intermediate objects, so there will be no risk. The important thing is that they use only the last object in the method chain.

To use java.lang.String as an example, the String client does this:

myString.trim().replace("a", "b").substring(3, 9); 

... means nothing, and, as a rule, indicates a misunderstanding of the programmer. What they should do is:

 String myNewString = myString.trim().replace("a", "b").substring(3, 9); 

... and then using myNewString in subsequent operations. Interestingly, the static analysis tool for Java, Findbugs, can detect cases of this misunderstanding and report it as a likely error.

The main business is customer understanding. Other disadvantages include if the value object is very expensive to create and the new one for each chain. You should be able to tell in your scenario if this could be a problem. In this case, instead of creating a new object in each method chain, you may need to implement the Builder template.

In addition, I cannot think of any other problems.

+5
source

Many Java classes provide immutable objects. java.lang.String, java.math.BigInteger and java.math.BigDecimal are immutable value objects, their methods return a new object. The biggest drawback of this is that people new to him do not understand it unchanged and think that they are changing the original.

Some languages ​​emphasize immutability more than others. In Ruby, strings change, and collections often provide a version that returns a copy, and another that mutates an existing copy (for example, Array # sort and Array # sort!). In Clojure, immutability is the norm.

+2
source

Yes it is very good. Examples:

  • String in Java and .NET
  • DateTime and TimeSpan in .NET
  • Many types in Joda Time and Noda Time
  • Lists in functional languages ​​like F #

For reference types that are implemented as immutable value objects, the downside may be that you end up generating a lot of garbage. In any case, you can complete a lot of copying - it depends on the specific situation.

+2
source

All Articles