> That is, what are you optimizing for?
I'm optimizing for other programmers to easily be able to see how objects fit together and behave, and for them to be able to easily extend the system without touching the behavior of other components (which you cannot do if you bundle behavior together). I've slowly shifted towards this approach throughout the last few years of my programming journey.
> Do you have an example to better explain?
Let me make an attempt to do so. Let's say that you have an HTML form builder in code (this is something I'm currently working on, if you can't tell ;). Your form builder lets you design the form such that you can split the form into sections, rows and columns. You might design a registration form like this, for example (I'm using Python-like pseudocode here):
layout = FormLayout(
Section(
title=_("Account information"),
contents=Column(
Field("username"),
Row(
Column(Field("password")),
Column(Field("password_repeat")),
),
),
),
# etc. you get the idea
)
Now, how would I go about rendering this into a tree? If I were to take the approach that the article suggests, I would have to do something like this: def render_element(element: Element) -> SafeString:
# Let's use Python 3.10's match as an analogue for the Dart switch
match element:
case FormLayout(children):
return "".join(render_element(child) for child in children)
case Column(css_class, children):
return format_html(
'<div class="{css_class}">{children}</div>',
css_class=css_class or "col-md",
children=mark_safe(
"".join(render_element(child) for child in children),
),
)
# case Row, Field, ...
As you can probably tell, this is bound to get super unwieldy over time. And this is just for one property of this HTML form builder; now imagine if we had to do some operation to the tree (like checking all fields in a form are actually rendered)!You might, at this point, suggest that we could just split the behavior into different functions... and that would just make us re-implement the dynamic dispatch system that's found in object programming already ;) You can see how we tend to move the behavior to the object in this case, because it lets each object only worry about its own behavior.
I hope this helped with giving a bit of an idea of why I'm for a more object programming-based approach over the pattern matching described in the article.