Search code examples
oopchaining

What should I consider when choosing between chainability and language constructs?


I have tough time making this design decision.

I could go with traditional new language construct to initialize objects, and use them through variables, such as:

$o = new Object('arg');
$o->method();
$o->property = 'value';
$o->save();

Or I can choose factory pattern and aggressive chainability like as

Object::new('arg')->method()->setProperty('value')->save();

which would result in

  • less LOC to
    • read,
    • maintain,
    • refactor,
  • no need to name variables.

However, I'm not sure if this is an acceptable approach, and if I forgot to take something into account.

Please express your worries or agreement, and guidance as how I could make my decision.


Solution

  • What's nice about the fluent interface is that the meat of the code isn't lost among extra syntactical plumbing making it easier to read. However it is a less familiar idiom than the line-by-line procedural approach, and not as general; not all code structures will be a good fit for this style, for example

    if (something) $o->method();
    

    won't translate as cleanly. So if such things are typical, it may not be a good fit.

    Also consider the context of the other code that will surround it. If the code is going to mostly be these sort of boilerplate looking segments like

    $o = new Object('arg');
    $o->method();
    $o->property = 'value';
    $o->save();
    

    then making them more succinct would surely be an improvement. But if such code will be lost among much other code in a different style, maybe not.

    If it seem like it's probably a good idea, I'd say go for it. If it doesn't play out well, the small effort of switching back will be worth the learning experience.