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

前端 未结 9 1790
隐瞒了意图╮
隐瞒了意图╮ 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:17

    Method chaining is a way to implement fluent interfaces, regardless of the programming language. Main benefit of it (readable code) tells you exactly when to use it. If there is no particular need for the readable code, better avoid using it, unless the API is naturally designed to return the context/object as a result of the method calls.

    Step 1: Fluent Interface vs. Command-Query API

    Fluent interface must be considered against command-query API. To understand it better, let me write a bullet-list definition of the command-query API below. In simple words, this is just a standard object-oriented coding approach:

    • Method that modifies the data is called a Command. Command does not return a value.
    • Method that returns a value is called a Query. Query does not modify the data.

    Following the command-query API will give you the benefits like:

    • Looking at the object-oriented code you understand what's happening.
    • Debugging of the code is easier because each call happens separately.

    Step 2: Fluent Interface on top of Command-Query API

    But the command-query API exists for some reason, and it indeed, reads better. Then how do we have the benefits of both fluent interface and command-query API?

    Answer: fluent interface must be implemented on top of the command-query API (as opposed to replacing the command-query API by the fluent interface). Think of a fluent interface as a facade over the command-query API. And after all, it's called fluent "interface" - a readable or convenience interface over the standard (command-query) API.

    Usually, after the command-query API is ready (written, probably unit-tested, polished to easily debug), you can write a fluent interface software layer on top of it. In other words, fluent interface accomplishes its functions by utilizing the command-query API. Then, use the fluent interface (with method chaining) wherever you want a convenience and readability. However, once you want to understand what's actually happening (e.g. when debugging an exception), you can always dig into the command-query API - good old object-oriented code.

提交回复
热议问题