Chained method calls (also called "fluent interface") are becoming more commonplace in Tuleap codebase. They appear a lot when using Results (Ok|Err
), Options, but also Builders and Mocks.
However, there are several styles for writing them:
// Aligning on the first arrow
$very_long_result_name->map()
->andThen()
->match();
$this->very_long_result_name
->map()
->andThen()
->match();
The problem with the style above is that the number of spaces to indent the arrows depends on the length of the first variable (either $very_long_result_name
or $this
here).
// Arrow is at the end of the line
$very_long_result_name->map()->
andThen()->
match();
$this->very_long_result_name->
map()->
andThen()->
match();
Writing the arrow at the end of the line seems more confusing, I have to read the previous line to know that this is a method call, and not a plain function.
// Indent arrows twice
$very_long_result_name->map()
->andThen()
->match();
$this->very_long_result_name
->map()
->andThen()
->match();
The style above ignores the length of the variable, but is counter-intuitive. Why indent twice here and once everywhere else ?
// Indent arrows once
$very_long_result_name->map()
->andThen()
->match();
$this->very_long_result_name
->map()
->andThen()
->match();
I propose to adopt the last style (indent arrows once, arrows at the beginning of the line), because it matches what is enforced by Prettier, so it is more consistent with the frontend codebase. It is also eligible to be enforced automatically by the PEAR.WhiteSpace.ObjectOperatorIndent PHPCS sniff, which can also automatically fix bad instances.
It should be noted that at the time of writing, there is a bug when choosing the multilevel = false
option for this rule. We must set it to true
.