Java class design - Too many if conditions

My code snippet is as follows:

public void execute(Parameters params) { Long requestType = params.getRequestType(); // Based on the requestType the name of the project would be different getName(requestType); // Same as above getDescription(requestType) // Project here is a collection of different requests Long projectId = createProject(name, description) RequestContents requestContents = params.getRequestContents(); for(RequestContent requestcontent : requestcontents) { Long requestId = createRequest(name, description, projectId); updateRequest(requestId, requestContent1); } // Based on the requestType, mail content would differ String mailContent = getMailContent(requestType, projectId) sendMail(mailContent); } 

The output of the sendMail , createProject , createRequest functions depends on requestType , and therefore these functions will have several if-else . What is the correct way to model this class to avoid this?

+4
source share
4 answers

One way would be to create an abstract class AbstractRequest with abstract methods sendMail , createProject , etc., and then have several specific subclasses of RequestType1 RequestType2 , etc., each of which has a different implementation of sendMail , etc. I suppose they call this a strategy.

+3
source

Use double dispatch :

 public class Sender { public void sendMail(RequestType1 requestType, String mailContent) { // some impl } public void sendMail(RequestType2 requestType, String mailContent) { // some impl } public void sendMail(RequestType3 requestType, String mailContent) { // some impl } } 

then

 sender.sendMail(requestType, mailContent); 

The actual method requestType determined at runtime based on the requestType object requestType . Not an “if” in sight.


You could just implement these methods locally, but it would be strange and hard to read. It is better to separate this problem into a separate class.

+1
source

If requestType is a finite set of String values, you can create the corresponding Enum for it.

 enum RequestType{ type1,type2,...; } 

Then you can convert if-else to a more compact switching register:

 switch (RequestType.valueOf(requestType)){ case type1: .... break; case type2: ... break; ... default: } 

From the requestType code is long, you can directly enable it:

 switch (requestType){ case type1: .... break; case type2: ... break; ... default: } 
0
source

why not put an if-else condition in the execute () method and based on this call other methods and pass the appropriate parameters. This way you will create the general functions of sendmail, createproject, createrequest.

0
source

Source: https://habr.com/ru/post/1443971/


All Articles