jeudi 17 décembre 2015

Simplifying an if (do some operation) then return

This probably a common occurrence and might be a stupid question, but i just really want to know how others handle this.

say i have:

private void actionPerformed(ActionEvent evt){
     if(isValid(textfield.getText()){
         // do something
     }
}

private boolean isValid(String text){
    if(text.isEmpty()){
      displayErrorMessage("empty string!");
      return false;
    }
    if(hasInvalidChars(text)){
      displayErrorMessage("Invalid chars");
      return false;
    }
    ....
    return true;
}

the isValid(String) method feels weird, I think a method should only do one simple thing, but isValid() certainly violates it, it displays an error message then returns a boolean.

Is that alright? or are there other ways to get around it?

Aucun commentaire:

Enregistrer un commentaire