📜 ⬆️ ⬇️

What is fluent-setter

image

Today in PhpStorm, I created a private variable and noticed that the IDE suggests that I create two types of setters: the regular setter and the fluent setter.

The term "fluent setter" I have not met before, so I created both options.

/* PHP */ class Foo { private $var; //  setter public function setVar($var) { $this->var = $var; } //  fluent setter public function setVar($var) { $this->var = $var; return $this; } } 

Yeah, so fluent setter, is the setter that the object itself returns .
')
What nonsense. Who may need a view design

 $object = $object->setVar(1); //     ,    $object->setVar(1); //      ,   $sameObject = $object->setVar(1); 

This is at first glance.

A little later, I guessed. This is what is called cheating in jQuery. Thanks to the returned object, we can immediately apply the next setter.

 /* Javascript */ $('#elementId').val(13).css('font-size', '20px').appendTo(element2); //     : $('#elementId') .val(13) .css('font-size', '20px') .appendTo(element2); 

Fluent-setters are invented to make the code clearer and clearer.

Yes, in Javascript it is noticeable. In Java and PHP, too. Moreover, there are already widely used setters, so why not make them in a fluent version.

 /* php */ $car->setColor('#f00')->setWeight('1200')->setPower(55000); $car ->setColor('#f00') ->setWeight('1200') ->setPower(55000); 

In Python, of course, you can write setter functions, but the benefits of them are not obvious. It will be more convenient for me personally to use an ordinary Python setter, which does not look like a function, but as an assignment operator. To do setters like set_var () in Python, in my opinion, contradicts the Python ideas of simplicity.

 # python #  @property car.color = '#f00' car.weight = 1200 car.power = 55000 # fluent-,    .   ?   . car.color('#f00').weight('1200').power(55000) #      ... car.set_color('#f00').set_weight('1200').set_power(55000) #    ,    ,     . car.set_color('#f00') \ .set_weight('1200') \ .set_power(55000) 

Later, I found an article about Fluent Interface, where I came across a more pleasing example in python .

A minute of self-education is over.

Source: https://habr.com/ru/post/429020/


All Articles