mercredi 24 mai 2023

What is the best way to avoid chained if-else condition to invoke different class function?

I am writing a GraphQL Query API which takes filter as input. Based on the filter I need to invoke different object function.

API function signature

public GrantsConnection fetch(GrantFilter filter)

GrantFilter has following attributes.

public class GrantFilter {
  private Boolean isPrimary;
  private String profileId;
  private String entityId;
}

The filter can be a combination of one or two or all attributes.

My approach

public GrantConnection(GrantFilter filter) {
  if(filter.getIsPrimary() != null
     && filter.getProfileId() == null
     && filter.getEntityId() == null) {
    // invoke a function
  } else if(filter.getIsPrimary() == null
     && filter.getProfileId() != null
     && filter.getEntityId() == null) {
     // invoke different function
  } else if(filter.getIsPrimary() == null
     && filter.getProfileId() == null
     && filter.getEntityId() != null
     // invoke 3rd function
  }
 // other combinations
}

All the function invoked from conditionals are objects which implement same interface. What is the best way to write this in spring?

Aucun commentaire:

Enregistrer un commentaire