How to achieve backward compatibility with a changed java class structure

Viewed 38

We have a class structure like below and

public class Partner {
   Long id;
   String name;
   PartnerDetails details;
}

public class PartnerDetails {
   String address;
   Long share;
   PartnerGroup group;
}

public class PartnerGroup {
   Long id;
   String groupName;
}

We are using partner.getDetails().getGroup().getGroupName(); to fetch group name of a partner currently.

But due to further enhancements, now we are moving PartnerGroup group property to Partner class and we are not deleting PartnerDetails.group property to avoid issues with the old records. Now the structure will be like below:

public class Partner {
   Long id;
   String name;
   PartnerDetails details;
   PartnerGroup group;
}

public class PartnerDetails {
   String address;
   Long share;
   PartnerGroup group;
}

public class PartnerGroup {
   Long id;
   String groupName;
}

For new records we are going to use partner.getGroup().getGroupName();

Please advise what is the best approach to work with new structure for new records and old structure for older records to fetch groupname.

1 Answers
  1. Replace all usages of partner.getDetails().getGroup().getGroupName(); with partner.getPartnerGroupName()

  2. Create method Partner#getPartnerGroupName that handles implementation details internally:

public class Partner {
   Long id;
   String name;
   PartnerDetails details;
   PartnerGroup group;
   
   public String getPartnerGroupName() {
       if (group != null) {
           return group.getGroupName();
       }
       return getDetails().getGroup().getGroupName(); 
   }
}

https://en.wikipedia.org/wiki/Law_of_Demeter

Related