Search code examples
javadesign-patternsconstructorbuilder

Different methods need different attributes in one object


I have a given web service. (This is only an example, the real one is more complex, but it has the same problem.) The service has three methods and all three methods have a person as parameter and need other things from it. (I can't change the entity or methods.)

Entity (Person) (It has only a default constructor):

private String name;
private int age;
private Address address;
private List<String> hobbies;
private List<Person> friends;
  • Method1 needs name and age.
  • Method2 needs address name and age.
  • Method3 needs all.

I need to fill the object from my own objects. I need to write a "converter". What is the best practice for it?

My solutions:

  • Builder Pattern with builds for three methods.
  • Set all attributes and send unhandled overhead (bad solution in my eyes).

Solution

    1. Creating a builder that sets only required fields sounds good.

    2. You can inherit from this class for each of your needs and implement your own constructors

      public class Target {
          // fields
      }
      
      public class Purpose1 extends Target {
          public Purpose1(String name, int age) {
              // set fields or do whatever you wish
          }
      }
      
      public class Purpose2 extends Target {
          public Purpose2(String address, String name, int age) {
              // set fields or do whatever you wish
          }
      }
      
      public class Purpose3 extends Target {
          public Purpose3(...) {
              // set fields or do whatever you wish
          }
      }
      

    And then you may use instances of subclasses where class Target is required.