I have a class (MiddleMan) talks to a system and this talk is initialized by the MiddleMan’s clients.
If a ‘talk’ is successfully completed, MiddleMan will generate a token and return it to its client.
The class design I have at the moment is like below:
class MiddleMan{
private String token = null;
private String param1;
private String param2;
private String amount;
boolean isTalkSuccessful = false;
public MiddleMan(String param1, String param2){
this.amount = amount;
this.param1 = param1;
this.param2 = param2;
}
public String talk() throws ValidationException{
//a private method validates param1 and param2
validateParameters();
//talk to backend system;
isTalkSuccessful = talkToSystem();
}
Private void validateParameters() throws ValidationException {
}
private boolen talkToSystem(){
}
public boolean isTalkSuccessful(){
return isTalkSuccessful;
}
public String getToken() throws Exception{
if(isTalkSuccessful()){
return token;
}else{
throw new Exception("cannot return token because talk is not successful");
}
}
}
Does this look right to you? How would you refactor it?
amountcome into play. It’s not in the list of instance variables, neither it’s there in the constructor argument. You need to fix this in your snippet to avoid confusion.talk()method should not validate, as its name is suggesting.isTalkSuccessful()method in yourgetToken(). I am assuming you want client to check this before callinggetToken()to avoid exception. Isn’t it? And you have your check in place just in case client doesn’t callisTalkSuccessful(). Correct? So, if avoiding the exception is the whole point, why not just don’t throw any exception. Lets get rid of that public methodisTalkSuccessful()and let the client callgetToken(). In yourgetToken()method check the private fieldisTalkSuccessfuland if it’s false returnnull. Why not?setToken()? Who will invoke it?