Contact Me

Replace Attribute With Object

Create a class, place the old field and its behavior in the class, and store the object of the class in the original class.

 This refactoring technique is used to replace an object's individual attributes with a single object, in order to improve the readability and maintainability of the codebase. This can be useful when an object has a large number of attributes, making it difficult to understand or maintain.

 For example, consider the following class, which has several attributes:

class Order {

constructor(id, customerName, customerAddress, items, total) {

  this.id = id;

  this.customerName = customerName;

  this.customerAddress = customerAddress;

  this.items = items;

  this.total = total;

  }

}

 To improve the readability and maintainability of this class, we can replace the individual attributes with a single object called customer:

class Order {

constructor(id, customer, items, total) {

  this.id = id;

  this.customer = customer;

  this.items = items;

  this.total = total;

}

}

const customer = {

 name: 'John Doe',

 address: '123 Main St'

}

const order = new Order(1, customer, [], 0);

 In this example, we have replaced the individual attributes customerName and customerAddress with a single object called customer. This improves the readability of the Order class by reducing the number of attributes it contains and making it clear that it's representing an order, with a customer name and address.


 Another benefit is that it allows for reusing the extracted object in other parts of the codebase. For example, in the above example, if we have another class that also needs to use the customer object, we can simply pass the customer object, instead of duplicating the code.

 An additional example of this technique could be to replace the individual attributes of an Address object with a single 'location' object, which could contain attributes such as the street, city, state, and zip code. This would make the Address class more readable and easier to understand, as well as making the location data more reusable.

 It's also worth noting that when implementing this technique, it's important to consider the implications of the extracted object and how it will be used in the codebase. For example, if the extracted object will be used in multiple classes or methods, it may be beneficial to create a new class for the object to encapsulate its behavior and make it more reusable.