Image

Imagetrajano wrote in Imagejava_dev 😵drunk

Introduce Adapter

This is a refactoring I generally do, but I can't seem to find it in www.refactoring.com, it might be an anti-pattern for what I know, what do you think? Also the refactoring link at the note below does not exist yet from what I know since I have to write it still.



objectB.setA(getA(objectA));
objectB.setB(getB(objectA));

|
v

ObjectAdapter adapter = new ObjectAdapter(objectA);
objectB.setA(adapter.getA());
objectB.setB(adapter.getB());


Motivation

Objects that are as simple as Strings or as complex as HttpServletRequest have data that we need to retrieve. However, we need to get specific pieces of data either by using the String.substring() or HttpServletRequest.getAttribute() methods. The direct approach forces an understanding on the how the data is stored in the objects.



The Adapter design pattern is used to wrap an existing object with another object that provides methods that would be named closer to what the client would need and limits the possible inputs to the actual object to what clients would normally need so developers do not have to know which part to get from the data.



Mechanics

  1. Determine the object to be wrapped.

  2. Create a new adapter class that has a constructor with one parameter, the object that needs to be wrapped.

  3. Add a private final field to the adapter class with the type of object that needs to be wrapped.

  4. In the adapter class constructor assign the field with the value from the parameter.

  5. In the client code place the code to create the adapter in. Then test to ensure it is working properly.

  6. Determine a data extraction method used in the client code.

  7. Create a new method that performs the data extraction method into the adapter class.

  8. Replace the client code that used to perform the extraction with the method from the adapter class.

  9. Test.
  10. Add more methods to the adapter for any calculation instance.


Example

Before refactoring.


public class ClassA {
  public void someMethod(String data) {
    Persister.saveData(getId(data), getName(data));    
  }
  private String getId(String data) {
    return data.substring(0,4);
  }
  private String getName(String data) {
    return data.substring(5,10);
  }
}

after refactoring


public class ClassA {
  public void someMethod(String data) {
    DataAdapter adapter = new DataAdapter(data);
    Persister.saveData(adapter.getId(), adapter.getName());    
  }
}

public class DataAdapter {
  private final String data;
  public DataAdapter(String data) {
    this.data = data;
  }
  public String getId() {
    return data.substring(0,4);
  }
  public String getName() {
    return data.substring(5,10);
  }
}


Notes

In some cases all the data is needed by clients so it might be useful to move the code for the getters to be performed during construction rather than on demand. Please see "Move getter logic to constructor" refactoring.