Home > Back-end >  What is good naming convention for validating method?
What is good naming convention for validating method?

Time:12-03

Let's say there is a method validating user's input. This method check if there is any duplication in list, and if exists, throw some kind of exception.

In this situation, which is proper naming for this method?

  1. validateIsDuplicated
  2. validateDuplication
  3. validateNonDuplication
  4. or else..

Since English is not my mother language, I'm not familiar with this. I'd appreciate it if you explain me why.

CodePudding user response:

Technically from convention perspective, all the methods you mentioned are correct. But naming conventions is a subjective topic and may vary from team to team. Finally it is about what as a team sounds more intuitive to all.

Having said that, nonDuplicate version sounds a little better than others to me from the given options but I would like to reword it as validateNonDuplication. The reason it sounds better than others is because your positive flow is to make sure there is no duplication while you are throwing an exception if there is a duplicate. So expectations are more inline of having non duplicates.

Hence in my opinion, I would pick validateNonDuplication in this case.

CodePudding user response:

I’ve not seen any conventions on this.

Accentuate the positive

I would suggest phrasing in the affirmative, stating the valid case. Focus on what what you want to see rather than what you want to avoid. Consistent use of positive logic makes the code easier to read and comprehend without having to to do Boolean logic flipping in your mind.

For example… If you want your list to not have duplication, that means the the list has unique items, also commonly known as distinct. So state the valid case as the name of your validation method: isDistinct.

boolean isDistinct( List< LocalDate > dates ) {
    return ( Set.copyOf( dates ).size() == dates.size() ) ; 
}

Per JavaBeans conventions, the leading is… means an accessor method (getter) for a property of the object. If in your context this might prove confusing, choose another name such as datesListIsDistinct.


By the way, for sophisticated data validation, you may find useful Jakarta Bean Validation. See also specification page.

CodePudding user response:

According to Oracle Oracle naming standard:

  • Methods should be verbs, in mixed case with the first letter lowercase, with the first letter of each internal word capitalized.

As you can see it doesn't specify anything else other than it needs to be descriptive. In your case, your examples can be more descriptive. If you method validades lists, maybe put it in. If it checks for a field in an object, specify it. For example validateIdListDuplicate.

This is a subjective topic so there isn't a right answer.

  • Related