Benefits and drawbacks of method chaining and a possibility to replace all void return parameters by the object itself

前端 未结 9 1840
隐瞒了意图╮
隐瞒了意图╮ 2020-11-29 06:58

I am mostly interested in Java, but I think it\'s a general question. Recently I\'ve been working with Arquillian framework (ShrinkWrap) that uses a lot of meth

9条回答
  •  北荒
    北荒 (楼主)
    2020-11-29 07:24

    Personally I think that it is a very useful pattern, but it should not be used everywhere. Consider the situation where you have a copyTo(T other) method. Normally you would expect it to not return anything, but if it were to return an object of the same type, which object would you expect? This sort of issue can be cleared up with documentation, but it is still ambiguous on the method signiature.

    public class MyObject {
    
        // ... my data
    
        public MyObject copyTo(MyObject other) {
    
            //... copy data
    
    
            // what should I return?
            return this;
        }
    }
    

提交回复
热议问题