I have 2 implementation of the interface:
public interface MyInterface{ void getCollectedData(MyData mydata); } public class MyImpl implements MyInterface{ public void getCollectedData(MyData mydata){ ServiceResult result = new ServiceResult(); ..... result.setName(myData.getServiceName()); } } public class MyImpl2 implements MyInterface{ public void getCollectedData(MyData mydata){ ServiceResult result = new ServiceResult(); ..... result.setName(myData.getTargetName()); } }
As you can see, the getCollectedData
method in both implementations is almost the same. The only thing that differs in the implementation of the method, is that each implementation sets different name.
However, the method is very large (lot of setting parameters that are the same) and if is very mucb redundant to have the same method body in both implementation when only one line differs.
What is reasonable way to solve this? What first came to my mind is to create a base method to set all parameters and then set other params in the method itself:
public interface MyInterface{ void getCollectedData(MyData mydata); default ServiceResult fillData(MyData mydata){ ServiceResult result = new ServiceResult(); // set data return result; } } public class MyImpl implements MyInterface{ public void getCollectedData(MyData mydata){ ServiceResult result = fillData(mydata); result.setName(myData.getServiceName()); } } public class MyImpl2 implements MyInterface{ public void getCollectedData(MyData mydata){ ServiceResult result = fillData(mydata); result.setName(myData.getTargetName()); } }
However by this i have to return new object and then modify its state. In my particular case, the object's properties are set with setters and are not immutable, but what if the objects will have to became immutable in the near future, or the same problems appears with immutable object?
What is the most reasonable way to handle this and not being redundant?
Thanks for help!
MyInterface.getCollectedData
method to accept two parameters,MyData mydata
andSupplier<String> nameSupplier
? You could then pass in a lambda when calling itgetCollectedData(data, () -> data.getServiceName())
. Or perhaps use aFunction<MyData, String>
and dogetCollectedData(data, (d) -> d.getServiceName())
. Then you only need a single implementation. Sometimes code duplication is only apparent; only DRY out the code if you don't expect the two methods to evolve in significantly different directions over time (i.e. the code repetition isn't circumstantial).