Question

I have a bean that has around 10+ fields and it may grow till 30 odd fields. The bean is a contract between applications to share data over an HTTP call. Basically, a downstream application will set exactly one field and will make a rest call.

class Person {
    private PersonalInfo personalInfo;
    private EducationDetails educationDetails;
    private WorkAddressDetails workAddressDetails;    
     ...
    // getters and setters
}

Now in my application, I am finding a null field and calling the respective service to process the data.

if(personalInfo != null) {
    personalInfoHandler.process(personalInfo);
} else if(educationDetails != null) {
    educationDetailsHandler.process(educationDetails)
} else if(workAddressDetails != null) {
    workAddressDetailsHandler.process(workAddressDetails)
}
...

This solution was working fairly well when there were a handful of fields in the bean, now as the bean is growing this solution isn't scaling well. is there a better way to re-design this solution? Initially, I thought about creating a factory of handlers but retrieving the exact type of handler from the factory would be tricky too.

Was it helpful?

Solution

A bean with 30+ fields, only one of which can be set, and none of whom are very related, seems awkward.

Would it be possible to have each of the fields classes know how to process itself? e.g. in Java syntax (with a lot of loose ends)

interface CanProcess {
  void process(some arguments);
}

class PersonalInfo implements CanProcess {
  void process(some arguments) {
     // implementation, e.g.
     personalInfoHandler.process(this);
  }
}

class EducationDetails implements CanProcess {

  void setCanProcessHandler(CanProcess useThisHandler) {
    this.CPHandler = useThisHandler;
  }

  void process(some arguments) {
    this.CPHandler.process(this);
  }
}

Then you can completely eliminate the bean, and just pass around a CanProcess and use polymorphism.

Note that, for separation of concerns, the actual implementation of process() might internally call a separate helper, such as personalInfoHandler, educationDetailsHandler, etc... As illustrated in the code for PersonalInfo.process().

In response to the excellent @candied_orange comment about how to construct the field -> handler linkage:

  1. Have it hard coded in the various CanProcess instances. (simplest but least robust, as shown in PersonalInfo code above)
  2. Dependency Inject it, e.g. (shown in EducationDetails code above) myCanProcess.setCanProcessHandler(CanProcess useThisHandler);
  3. Use some sort of table lookup or factory, e.g. handlerTableLookerUpper.getHanderFor(myCanProcess.class);
Licensed under: CC-BY-SA with attribution
scroll top