WHAT IS METHOD CHAINING
Method chaining is a common syntax in object-oriented programming for invoking multiple method calls. The class methods must return the current object using the
this
keyword.METHOD CHAINING EXAMPLES
- Method chaining in Javascript
function Client() {
this.name = null;
this.phone = null;
}
Client.prototype = {
getName: function () {
return this.name;
},
setName: function (value) {
this.name = value;
return this;
},
setPhone: function (value) {
this.phone = value;
return this;
}
};
alert(new Client().setName('John Smith').setPhone('+1 (555) 123-4567').getName()); // prints John Smith - Method chaining in jQuery
$('ul')
.find('a:eq(1)')
.addClass('active')
.text('Test')
.css('color', 'red')
.show(); - Method chaining in PHP
<?php
class Client {
private $name;
private $phone;
public function setName($value) {
$this->name = $value;
return $this;
}
public function setPhone($value) {
$this->phone = $value;
return $this;
}
public function getName() {
return $this->name;
}
}
$client = new Client();
echo $client->setName('Jane Doe')->setPhone('+1 (546) 854-9551')->getName(); // prints Jane Doe
?>
METHOD CHAINING AND ERROR HANDLING
Throwing errors or returning boolean values from a method could break the chain, so proper error handling is a must.
function Client() {
this.error = null;
this.email = null;
this.birthday = null;
}
Client.prototype = {
getError: function () {
return this.error;
},
hasError: function () {
return this.error !== null;
},
getInfo: function () {
return ['Send a mail to ', this.email, ' at ', this.birthday].join('');
},
setBirthday: function (value) {
if (!/^\d{4}-\d{2}-\d{2}$/.test(value)) {
this.error = 'Invalid ISO date.';
return this;
}
this.birthday = value;
return this;
},
setEmail: function (value) {
if (!/[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}/i.test(value)) {
this.error = 'Invalid email address';
return this;
}
this.email = value;
return this;
}
};
var client = new Client();
if (!client.setEmail('www.domain.com').setBirthday('1987-10-29').hasError()) {
console.log(client.getInfo());
} else {
console.log(client.getError());
}
CONCLUSION
Method chaining could be extremely useful when it comes to execution of multiple consecutive methods over a single object.
No comments:
Post a Comment