问题
I'm tempted to add a suffix like "Ex" to differentiate methods (with similar signatures) that throw Exceptions from those that don't.
Is there such a convention?
回答1:
Yes, you name them the same as methods that don't.
Isn't the exception specification enough?
Edit: If you have similar methods that throw/not throw, I recommend the Parse
/TryParse
pattern (Parse
being replaced by the operation). .NET Framework uses it frequently (Dictionary<T,K>.TryGetValue
, Monitor.TryEnter
, int.TryParse
, etc. etc.).
Edit: Coding Horror: TryParse and the Exception Tax
回答2:
Don't do that.
This is like asking "is there a naming convention for methods that take two Strings as parameters".
Java has checked exceptions, which means that you need to declare them anyway. So you can easily see if an exception will be thrown, and what type of exception. You cannot even compile code that calls the method without adding exception handling code.
Update: It seems your intention is to have methods that check if a certain condition is true, but you do not want to return just false, but throw an Exception if the condition is not met, so that you can also convey an explanation message (in the Exception). I think a prefix of "assert" or "ensure" makes sense:
// instead of
if (! isAuthenticated())
throw new NotAuthenticatedException("not sure why at this point...");
// you do
assertAuthentication();
// which will throw NotAuthenticatedException("proper explanation") inside
回答3:
Why would you do such a thing in Java? It already has exception specifiers built into the language. The compiler will prevent you from calling a method which explicitly throws an exception without some action being taken on your part to handle or allow the exception to propagate?
回答4:
If you need these methods differentiated, I'm sure you can do it in the naming without using a suffix or anything, which is (as others have pointed out) pretty ghastly.
Why have:
boolean authenticate(String username, String password);
and (say)
void authenticateEx(String username, String password) throws WhateverException;
when you could actually make it a meaningful part of the name by conveying the actual intent:
void ensureCanAuthenticate(String username, String password);
// or
void assertValidCredentials(...);
// or
void authenticateOrDie(...);
... or any number of other (probably better) names which actually convey the intent rather than relying on a confusing suffix.
回答5:
Exceptions are part of the method signature in Java, therefore such a naming convention would be redundant.
回答6:
Hungarian notation for methods that throw exceptions? Quel horror!
Do you mean checked or unchecked exceptions? Why on earth would you want to do that?
When you think about it, you'd have to add your convention to every method, because there's always the potential of an error or NPE or some other thing that could go wrong.
The "throws" clause is enough when you have checked exceptions, and there's no good purpose on God's green earth for unchecked exceptions.
Don't do it. Please.
回答7:
There is no convention and adding an ex will make the name harder to read and ugly looking for the average java programmer.
But at sometimes I could imagine that it would make your code faster understandable to add a try to methods that are likely to throw an exception. Especially if they are unchecked.
It doesn't have to be something ugly like it could be found in many c/c++ programs where you use _name or mName for members or iValue for integers. But in java there are some conventions too. If a method will return an integer it is prefixed with is... set, get and test are the most used examples for this. All of this things are documented in the method header, through return type annotations etc... But adding one word to the function name makes it easier and faster to read and understand.
Why not use try to give programmers reading your code a subconscious hint that this method is likely to throw an exception. Like tryCopyFile instead of tryWriteFile.
回答8:
There is none that I'm aware of.
In my opinion, the only time something like that makes sense is in unit test cases (e.g., testFooExpectingException()). But that's not really what you're talking about.
回答9:
There is no such convention because every method can throw exceptions, regardless of whether you declare them or not. It's also somewhat redundant in this day and age of IDE tooltips (unless you're not using an IDE of course).
I'm curious to know why you are tempted to use such a naming convention though.
回答10:
Every once in a while you'll run into a case where it might make sense to have a method name like getSafely()
(returns a default value in the case where the actual value is invalid, for code that doesn't care too much about real values vs placeholders) or its converse getOrBlowUp()
(for fail-fast code where a missing value is technically possible but indicates a bug in the code that's supposed to set the value).
But the point here isn't "method 2 throws an exception, method 1 doesn't" -- because, as mentioned above, any code could throw a RuntimeException
. The point is that the two methods have different error-handling semantics, specific to different use cases, and that's what the method names try to capture.
Even then, the code would usually be cleaner if you could just get away with one behavior or the other, and call the method get()
.
A useful parallel here might be the distinction between Systems Hungarian and Apps Hungarian in Hungarian Notation. (See also this piece on coding conventions from Joel on Software.)
- Systems Hungarian just tells you the type of the variable, so integer
count
becomesiCount
. This is the most common form of Hungarian notation and IMHO it's (1) pretty pointless with a modern IDE and (2) potentially deceptive, if someone changes the type declaration without renaming the variable. - Apps Hungarian tells you the purpose of the variable, so integer (or short, or ordinal ID object, or whatever, who cares?)
index
representing a data row becomesdrIndex
, andindex
representing an annotation column becomesacIndex
. This is much more useful and much less likely to cause trouble.
Calling your method getEx()
is Systems Hungarian.
来源:https://stackoverflow.com/questions/1169158/is-there-a-particular-naming-convention-for-java-methods-that-throw-exceptions