Hi Jesse,

On 10 July 2016 at 14:31, Jesse Schalken <m...@jesseschalken.com> wrote:

> On Sun, Jul 10, 2016 at 8:34 PM, Rasmus Schultz <ras...@mindplay.dk>
> wrote:
>
> >
> > What you're really trying to accomplish is something like the ".."
> > operator found in some other languages - this is known as the "cascade
> > operator" in Dart, for example:
> >
> >
> >
> http://news.dartlang.org/2012/02/method-cascades-in-dart-posted-by-gilad.html
> >
> >
>
> While I was writing about an operator to set object properties in-line
> here: http://news.php.net/php.internals/93662 , I considered it would be
> easy to add method calls to the same syntax:
>
>
> return Blah::create(5) {
>     prop1 = 'hello',
>     prop2 = a_func(),
>     setThing(9),
>     setOtherThing(1),
> };
>
>
> which is in principle just an alternative syntax to as the cascade operator
> in Dart.
>
> I agree entirely that method chaining is just a verbose workaround for the
> lack of such a language feature. I've found a few problems with method
> chaining which this would resolve:
>
>    1. The verbosity of adding "return $this;" to all your mutator methods
>    (Daniel Ciochiu's issue).
>

`return $this;` is a fairly common anti-pattern. It can be useful in few
edge-cases, like immutable APIs (CoW) and DSL builders, but it's usually a
bad idea. I ranted extensively about this at
https://ocramius.github.io/blog/fluent-interfaces-are-evil/


>    2. You can't return a value from a mutator method while also supporting
>    method chaining. In theory mutator methods shouldn't need a return value
>    (command-query separation) but in many cases they do, such as a setter
>    which returns the previous value, a pop() method on a stack, or a
>    delete($where) method returning the number of deleted records.
>    3. It is often unclear whether a method being chained is returning the
>    same object it was called on, a copy of the object, or an instance of a
>    different class altogether. You can work around this with careful method
>    naming and documentation ("with.." for new instance, "set.." for same
>    instance etc), but language-level support eliminates this issue
> entirely.
>

Are you actually talking about a `$this` return-hint? That would indeed
solve some issues, by enforcing identity as part of the return type. Don't
think that there are scenarios where identity is required though, as it
would be useless (the hint would not serve any actual
behavioral/expressiveness improvement).

@Daniel: the fact that an implicit return is added to the opcodes for a
method that has a `self` hint seems useless/magic to me. It would basically
allow automatic fluent interfaces, enforcing something useless though,
since a fluent interface does not provide any actual usefulness per-se
(besides code-style preferences).


Marco Pivetta

http://twitter.com/Ocramius

http://ocramius.github.com/

Reply via email to