I could not fit this in a Twitter message, so I'll clutter up this joint instead. And, hey, it could use some content, I know.
I recently came across some PHP code (this happens to me a lot these day), which was along these lines:
$someObj->someMethod()['someKey']->doSomething();
$someObj->someMethod()['someOtherKey']->doSomethingElse();
$someObj->someMethod()['anotherKey']->performAnotherAction();
$someObj->someMethod()['lastKey']->doLastThing();
Obviously I've changed the names to protect the in
If this was my code, I'd see no point in repeating myself all over again, instead just ask the question once, and reuse the answer:
$descriptiveName = $someObj->someMethod();
$descriptiveName['someKey']->doSomething();
$descriptiveName['someOtherKey']->doSomethingElse();
$descriptiveName['anotherKey']->performAnotherAction();
$descriptiveName['lastKey']->doLastThing();
To me calling a method is work, and I'd like to avoid work if possible. Just as my colleagues.
However this is not the only occurrence of the former approach I've seen, so perhaps I am missing something? Is there some benefit to desirable behaviour from calling the same method for the same answer repeatedly?
Note I'm not so fussed about performance in situations like this, although I would have expect calling a method multiple times would have an inconsequential performance hit compared to an intermediary variable. Is this not the case? But like I said... whether or not it might be is not really a consideration here. It just seems like doing work for the sake of it?
Thoughts?
For the sake of conversation and broadening everyone's knowledge... in your own language of choice if it's not PHP: what would your answer to this be?
--
Adam