This is not the first time that I’ve found myself in a situation in which I have to adapt two objects with almost the same data, for example:
User.java (Object returned from another library)
private String name;
private String surname;
private String email;
private String telephone;
...
getters and setters();
constructor();
MyUser.java
private String name;
private String surname;
private String email;
private String telephone;
...
getters and setters();
constructor();
I usually create a method to convert one object into another one, like this:
User m1 = new User();
MyUser m2 = new MyUser();
m2.setName(m1.getName());
m2.setsurmame(m1.getsurname());
…and so on…
Does anybody know a different way to do this kind of stuff?
Use Object Composition For objects that you create using the other library, create an instance of
ExternalUser. But if you want to create them locally, create aBrandNewUser. Then you can just treat them the same way, with one version using the pass-through composition methods, and the ones created by your code using your own internal implementation.You can create your object like this: