4 ms·
Just to nitpick, those aren't quite equivalent. The second should be: o = window.FindCanvasForObject(obj); o = o.Color(RED); o = o.MoveTo(10,30);
by Groxx 10y ago
Just to nitpick, those aren't quite equivalent. The second should be:
o = window.FindCanvasForObject(obj);
o = o.Color(RED);
o = o.MoveTo(10,30);
o = o.LineTo(50,20);
Which leaves more room for error in the general case - if the API gives you a new object each time, and you fail to assign it every time (or say you have multiple and get the letters mixed up, or you do this rarely and forget), you lose some of the config. It can be fairly easily missed in code reviews. When it's all chained together, there's only one possible interpretation if it compiles and only has one assignment.
But I can see where you're coming from. Chains can be abused rather horrifically. IMO part of that is because it's hard to make helper functions, e.g.:
window.FindCanvasForObject(obj).Color(RED).MoveTo(10,30).LineTo(50,20)
# plus
def move_line(thing, start, end):
return thing.MoveTo(start).LineTo(end)
# leads to
move_line(window.FindCanvasForObject(obj).Color(RED), (10, 30), (50, 20))
It breaks the straightforward left-to-right interpretation. So instead, people just make the chain longer and longer, forever.
(not as much of a problem with a language with open classes, but modifying existing classes for ad-hoc helpers is usually frowned upon too.)
- beagle3 10y agoYou are correct, of course; the only API I used this with on JavaScript kept returning the original object (and that was documented behaviour) so it didn't matter. I most often use this with C++, where it is { CanvasObject *o = window.FindCanvasForObject(obj); o->Color(RED); o->MoveTo(10,30); o->LineTo(50,20); } Your point about helper functions is spot on. They break the form in C++ (and Python if you don't modify classes), but with this form it is still much better than breaking a fluent style line.