চেইনিং মেথড, যাকেন ক্যাসকেডিং বলা হয়, মানে একটি অবজেক্টের ওপর একের পর এক মেথড কল করা এক লাইনে। চলুন একটি উদাহরণ দেখি যেখানে মেথড চেইনিং আমাদের রিপিটেশন এড়াতে সাহায্য করে।
উদাহরণ
নিচের Car ক্লাসটি নিন উদাহরণস্বরূপ -
class Car { constructor() { this.wheels = 4 this.doors = 4 this.topSpeed = 100 this.feulCapacity = "400 Litres" } setWheels(w) { this.wheels = w } setDoors(d) { this.doors = d } setTopSpeed(t) { this.topSpeed = t } setFeulCapacity(fc) { this.feulCapacity = fc } displayCarProps() { console.log(`Your car has ${this.wheels} wheels,\ ${this.doors} doors with a top speed of ${this.topSpeed}\ and feul capacity of ${this.feulCapacity}`) } } let sportsCar = new Car(); sportsCar.setDoors(2) sportsCar.setTopSpeed(250) sportsCar.setFeulCapacity("600 Litres") sportsCar.displayCarProps()আউটপুট
Your car has 4 wheels,2 doors with a top speed of 250and feul capacity of 600 Litres
দেখুন sportsCar কতবার অপ্রয়োজনিয়ো রিপিট হয়েছে? আমরা মেথড চেইনিং ব্যবহার করে এটিকে দূর করতে পারি। সেটারগুলো শুধু ভ্যালু সেট করার বদলে, শেষে this রিটার্ন করুন। এটি আমাদের অবজেক্টের ওপর অপারেশন চালাতে দেবে। এই পরিবর্তন করার পর আমাদের কোড দেখাবে -
class Car { constructor() { this.wheels = 4 this.doors = 4 this.topSpeed = 100 this.feulCapacity = "400 Litres" } setWheels(w) { this.wheels = w; return this; } setDoors(d) { this.doors = d; return this; } setTopSpeed(t) { this.topSpeed = t; return this; } setFeulCapacity(fc) { this.feulCapacity = fc; return this; } displayCarProps() { console.log(`Your car has ${this.wheels} wheels,\ ${this.doors} doors with a top speed of ${this.topSpeed}\ and feul capacity of ${this.feulCapacity}`) } }এখন আমরা কার অবজেক্ট তৈরি করার অংশটিকে আরও পঠনযোগ্য এবং কম রিপিটিং কোডে পরিবর্তন করতে পারি -
উদাহরণ
let sportsCar = new Car() .setDoors(2) .setTopSpeed(250) .setFeulCapacity("600 Litres") .displayCarProps()আউটপুট
Your car has 4 wheels,2 doors with a top speed of 250and feul capacity of 600 Litres
মেথড চেইনিং কে fluent interface ও বলা হয় কারণ এটি অবজেক্টের ওপর মেথড দিয়ে অপারেশন করতে দেয় বিনা ফ্লো বারবার ভাঙায় অবজেক্ট রিপিট করে।