Reputation: 187
I have many private validate functions in the code that use the same naming convention validateSomething(). Some of them throw an exception if validate is failed. I going to re-named it throwExceptionIfSomethingInvalid() to make the code more readable. But someone argue that the new name is too strange and cause them confusing. Could you help to give me some advices about that?
Upvotes: 2
Views: 1308
Reputation: 140603
There are no "exact" answers here; only conventions. And which one you choose doesn't matter so much. The more important point is: whatever naming policy you choose:
In other words: you want to follow POLA (principle of least astonishment). Readers of your code should always find that the name of a method (in your context) does exactly say what the method will do.
Besides, "my policy" is typically that a void method that starts like checkSomething
or validateSomethingElse
will always throw an exception if the check fails (and well: what is could a void-method do besides throwing an exception).
In contrast to a boolean returning isSomethingValid()
or so.
Upvotes: 1
Reputation: 15212
But someone argue that the new name is too strange
I agree. The right way to specify that your method can throw a checked exception is to declare it as part of the method signature. Examples :
validateName()throws InvalidInputException
validateAge()throws InvalidInputException
When you do this, the caller will always be forced to either handle the exception or propagate it to a higher module.
Another way to look at this would be to ask your self this : would you name a method that does not return any value void doSomethingWithoutReturn
? No because you can know that the method does not return anything when you see that it's signature has void
in it.
Upvotes: 1