Is there a particular naming convention for Java m

2019-06-17 14:03发布

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?

10条回答
Root(大扎)
2楼-- · 2019-06-17 14:28

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

查看更多
淡お忘
3楼-- · 2019-06-17 14:29

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.

查看更多
We Are One
4楼-- · 2019-06-17 14:30

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.

查看更多
Deceive 欺骗
5楼-- · 2019-06-17 14:34

Exceptions are part of the method signature in Java, therefore such a naming convention would be redundant.

查看更多
forever°为你锁心
6楼-- · 2019-06-17 14:37

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.

查看更多
疯言疯语
7楼-- · 2019-06-17 14:41

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.

查看更多
登录 后发表回答