What is the conventional Java exception for "Too Many Results" - java

I am writing a generic API that takes parameters and returns results. I expect that if the data is consistent, only one result will be returned for an ID. If I get 1 result, I return it. If I get 0 results, I can throw "MissingResourceException" or "NoSuchElementException" etc. However, if I get multiple results, what should I throw? I have looked at the obvious places (Oracle/Java API documentation, Googling it, and of course, StackOverflow), but didn't find one.
Please note that I may not control the data, so the "the data should have been good/police your data" advice, while valid, will not help me.
Any help is appreciated.

Joshua Bloch's Effective Java says in Item 60 (Favor to use standard exceptions):
Also, feel free to subclass an existing exception if you want to add a bit more failure-capture information (Item 63).
So, I vote for one of IllegalStateException or YourOwnException (with additional failure-related info).

Related

Custom exceptions or empty list

I am working on a project to parse the text. I am parsing for specific text and store them in the array. I have written a class for it. If I get improper text so that I cannot find what I want in the given input, What is the best practice, should I return the empty array and let the calling class handle it or should I raise a custom exception to the calling class.
If I were using your class as a library and received an empty array as a return value, I would assume -- barring documentation otherwise -- nothing had been read (and be very confused if my input had text to read!)
Similarly, I would hope that when and if a piece of library code threw an exception, it would throw something useful so that I could debug the problem. That might come in the form of a custom exception, or it might come in the form of an existing library exception; for example, ParseException, which supplies the offset into the text where the exception occurred. However, if there is some other piece of information that's relevant to your particular exceptional case, then a custom Exception subclass may be warranted.
If caller's view of empty-list is error i.e. caller always except some value in list and handling empty list is not usual in his case that's a signal that a custom exception is better.
For example: If caller has a category input and contract is your API will have its product, emptiness is error according to contract.
Now, if there is no use-case of above tight contract between caller and API, it's perfectly valid to send empty list.
For example: Caller asks for a list of XYZ articles and you don't have, an empty article list is fine.
It's purely subjective and use-case driven, Java doesn't provide any specific guidelines on this.
It's hard to have "best practices" since every design case is different. As a rule of thumb, consider what API would be easiest for your consumer to use and would be least surprising. I also highly suggest picking up a copy of Effective Java by Joshua Bloch if you haven't seen it already. Specifically applicable are sections on "Use Exceptions for Exceptional Conditions", and "Favor use of the Built in Exceptions" (and the book contains lots of other good style and correctness suggestions).
Now to your particular case:
Is it expected that your user should provide proper text or improper text as input? If the former, then an Exception is more likely the correct solution. Furthermore, If you returned an empty array, What would the difference be between proper text that happens to be empty, and improper text? Could you tell the difference in your calling code? Does such a distinction matter?
Now what exception to throw? You could throw a subclass of IOException (as you're dealing with input), the (arguably) potential downside is that IOException is not a RuntimeException so anyone calling your code would be forced to either handle the exception or rethrow it. (Checked versus Unchecked exceptions is another debate).
It depends on what you are doing. If improper text is a common and expected thing, simply ignoring it and returning an empty array (or null) may be completely reasonable. But if improper text should never happen and calls into question the validity of previously or subsequently processed input (that may already have been added to the array) you should probably throw an exception.

How should I return a value from function?

Three ways I see here:
1) make function return that value explicitly
2) add additional argument to the function's argument list and pass string holder as that parameter. After the function completes its execution, that string holder will contain the result of the function.
3) throw an exception from that function that will contain the result.
I for myself see first choice more preferable because it's simple, intuitive and straight.
On the other hand, when execution of the function goes in a wrong way there may be additional choices like throw an exception or use a variable passed through parameter to save errors if any happen.
Intuitively, I see that ideal choice is to have explicit return value and throws declaration. So return value is used for normal execution and caught exception will signal about abnormal situation. But I myself don't like exceptions too much if only it is not the completely unpredictable error, so I'd use explicit return value and additional parameter to hold some extra-situation logs or errors.
Please advise books or articles on the subject (it shouldn't necessary talk about Java, any other languages with similar mechanisms are also suitable).
You absolutely want option #1. Exceptions are not unpredictable; if you use them correctly, they are in fact entirely predictable. You can throw different exception types based on the error (FileNotFoundException, IllegalArgumentException, SomeConditionSpecificToMyAppException, etc), and those exceptions can contain any error or diagnostic information you need to convey.
Here's a good section in the Java SE tutorial on exceptions: http://docs.oracle.com/javase/tutorial/essential/exceptions/
Java methods have return values for a reason: to return their results. In the vast majority of cases #1 should be your only choice. Even if you want to return a wrapper object e.g. because you need to return multiple values, you should probably just return the thing...
Exceptions are just that: they are thrown in exceptional (i.e. abnormal) circumstances. Since traditionally throwing an exception also implies a performance impact, exceptions should not be thrown during normal operation.
Why are you trying to confuse yourself?
EDIT:
On the other hand, exceptions are quite suitable for rare/abnormal conditions:
They have built-in support for the generation of debugging information. Getting a stack trace is half the battle in dealing with most bugs.
All decent debuggers allow for thrown exceptions to be used as a break point, which can be invaluable.
Exceptions allow for error conditions to be passed up the method call chain relatively transparently, allowing for the error handling code to be placed with as much granularity as desired.
Exceptions are the standard way to deal with error conditions in Java. This should be enough for most programmers. Please respect the people that will have to work with your code and don't break such basic conventions by reinventing the wheel...
I would use choice 1 almost every time. There is nothing stopping you throwing a Exception as required.
Please read Code Complete by Steve McConnell. It's all there.

Where to catch and process null arguments?

When I code, I often ask myself the same question :
Do I have to verify all arguments are not null ? So, in each method, I will have something like that :
if (arg1 == null)
{
throw FooException("...");
}
if (arg2 == null)
{
throw FooException("...");
}
If not, in which case is preferable ?
What's the best practices ?
As always, it depends.
If you're writing an API to be used by other teams / organizations, such defensive programming with precondition checks on public functions can really help your users; when using an external library, a meaningful error message like 'argument passed to foo() should not be null' is way better than NullPointerException thrown from some inner class.
Outside of API, though, I think such checks clutter the code too much. Thrown NullPointerExceptions are usually pretty easy to trace with debugger anyway. In languages that support them, you can consider using assertions - their syntax is usually less cumbersome, and you can turn them off on production so the checks won't degrade performance.
Unfortunetly, yes. you should check all arguments. Now ideally, if you code with good design practices one function should not have more than 4 or 5 arguments, at the most.
Having said that, one should always check for null values in function entry and throw appropriate exception or IllegalArgumentException (my fav).
Furhter, one should never pass NULL to a function and should never return a NULL. Sounds simple but it will save lots of code and bugs. Have a look at the NULL Design Pattern too.
Depends, if you want different exceptions i guess you would have to do that for all occasions where you might get a null value. Another way would be to user DATATYP.TryParse(). Look that up.
Hope it helps.
Since you're throwing an exception anyway, not verifying them would probably just lead to a nullpointerexception or something similar. I'm not entirely sure what the best practices are myself.
You should ideally always verify any arguments before you perform any action that might modify any state or data associated with said arguments. It's better to fail early and in a manageable way (by throwing a exception) than to end up with an inconsistent state / data which then also has to be resolved.
Your methods are expecting certain data to be there, there are some cases when it should be safe to assume that it is actually there (say inside a private method, which is called from other methods which validate input). However in general I would recommend validating arguments whenever they are:
Supplied by a user.
Supplied as part of an API.
Passed between modules of a system .
It's might be worth taking a look at this previous StackOverflow question.
I feel it's mostly down to common sense, and a little down to personal preference.
As others have mentioned, if it's a public API then you want to provide clear error messages wherever possible, so it's best to check parameters before they are used and throw exceptions with messages as per your example.
If it's internal code then there are two other options to think about: use assertions, or don't bother with the validation and rely on debugging. As a rule of thumb, I'll put assertions in if it's code that I expect other developers will be calling or if the condition is subtle enough that debugging it might be a pain. Otherwise, I'll just allow it to fail.
Sometimes you can avoid the issue by using the Null Object pattern. If it's a public API I'd still be inclined to include the checks though.

Should the JUnit message state the condition of success or failure?

I can write an assertion message one of two ways. Stating success:
assertEquals( "objects should be identical", expected, actual );
Or stating the condition of being broken:
assertEquals( "objects aren't identical", expected, actual );
Is there a standard for this in JUnit specifically? If not, what are the arguments for each side?
P.S. I've seen articles on the web demonstrating both of these without explanation, so just saying "search Google" is not an answer!
[UPDATE]
Everyone is getting hung up on the fact that I used assertEquals and therefore the message is probably useless. But of course that's just because I wanted to illustrate the question simply.
So imagine instead it's:
assertTrue( ... big long multi-line expression ... );
Where a message is useful.
I rarely even bother with a message, at least for assertEquals. Any sensible test runner will explain that you were using assertEquals and the two things which were meant to be equal. Neither of your messages give more information than that.
I usually find that unit test failures are transient things - I'll rapidly find out what's wrong and fix it. The "finding out what's wrong" usually involves enough detail that a single message isn't going to make much difference. Consider "time saved by having a message" vs "time spent thinking of messages" :)
EDIT: Okay, one case where I might use a message: when there's a compact description in text which isn't obvious from the string representation of the object.
For example: "Expected date to be December 1st" when comparing dates stored as milliseconds.
I wouldn't worry about how you express it exactly though: just make sure it's obvious from the message which way you mean. Either "should be" or "wasn't" is fine - just "December 1st" wouldn't be obvious.
According to the junit API the message is the "the identifying message for the AssertionError" so its not a message describing the condition that should be met but a message describing what's wrong if the condition isn't met. So in your example "objects aren't identical" seems to be more conformant.
Unlike many others I feel that using a message is extremely helpful for many reasons:
The person looking at the logs of a failed test may not be the person who wrote the test. It can take time to read through the code and understand what case the assertion is meant to address. A helpful message will save time.
Even in the event it is the developer of the test who is looking at the logs it may have been days or months since the test was written and, again, a message can save time.
My advice would be to write the message with a statement of the expected behavior. For example:
assertEquals("The method should be invoked 3 times", 3, invocationCount);
I don't think it matters at all - You already know that a failure happened, and therefore it doesn't matter if the message states what should have happened, or what shouldn't happen.
The goal of the message is to help you when it can, not to obtain some completeness.
Obviously, in the case of assertEquals this is less important, but the message is important in the case of general asserts. The message should help you obtain enough context to understand right away what exactly failed.
However, the amount of needed context (and thus the details in the message) should depend on how you get the report. For example, if you get it in Eclipse, you can easily go and interact and see what happened, so the message is less imporrtant. However, if you get your reports emailed to you (e.g., from a continuous build server) then you want the message to provide enough information so that you will have an idea of what is going on before you even go to the corresponding source code.
I would like to answer the question without considering, if a message in generel is useful.
If a test fails, something is wrong. I know this. I want to know why it is broken. That's very easy to find out because I just have to open the test case and the SUT.
Like Jon said, it's very easy to fix it (hopefully ;-) ).
But what about the message? The message is for me an advice, what could be done to turn it into a green test case. So I would appreciate if there's an advice given in the message text, how to fix this problem or where to search for the problem.
Another interesting aspect would be the usage of positive expressions. It's worth a consideration to use positive text messages. In your example, I would use Objects should be identical. But that's a small reason.
I see this question from two perspectives,
First and the most common perspective, which is already being discussed by most of us here: From the perspective of someone who is seeing the logs and trying to fix the error:
I believe that both the messages provides equal information.
Second perspective is that of someone who is reading/ maintaining/ reviewing the code: As we have been talking since ages about the readability and simplicity of code. So, it is also equally important as well.
We have been made to believe that my code should be simple and self explanatory so that no explicit comments are needed and I strongly agree with it.
From this perspective:
These messages make it a lot easier to read and go through the code as they serve the dual purpose of documentation as well as error reporting:
assertEquals( "objects should be identical", expected, actual );
assertTrue( "flag should have been set", flag );
assertNotNull( "object must not be null", object );
These messages are not so reader friendly as they talk about the unexpected condition:
assertEquals( "objects aren't identical", expected, actual );
assertTrue( "flag is not set", flag );
assertNotNull( "object is null", object );
According to specs, the message is to describe the error when it occurs.
And is useful when you build your application in a CI environment, like Jenkins, and using plugins to analyze error results.
http://junit.sourceforge.net/javadoc/org/junit/Assert.html#assertTrue(java.lang.String,%20boolean)
message - the identifying message for the AssertionError (null okay)
Vote me down too (like Jon), but the only time I've ever use a message like this (on assert equals) is when building a single test with a matrix of values and one of the test elements fails: I use the message to indicate which test case failed. Otherwise, the text is totally redundant.
From the javadocs of JUnit:
Asserts that two objects are equal. If
they are not an AssertionFailedError
is thrown with the given message.
According to the API, the message can be whatever you want. I would argue that the two options you have are both the same and both superfluous. The success or failure of the assert already provides all the information you are providing in the message.
It follows for me that you should have either nothing (there is an assert that doesn't take a string on purpose) OR include a message with meaning beyond what is already there.
So I guess this is a reiteration of Jon's answer, but too verbose to be a comment.
Those messages are particularly important when a test fails. And when it fails, you don't only want to know that the objects should be equal, you want to know why they should be equal.
So instead of
assertEquals( "objects should be identical", expected, actual );
use
assertEquals( "Status code should be 403 (forbidden), because a user "
+ "with role customer must not be allowed to access the admin console.",
403, statusCode );
And yes, messages are allowed to be very long, as long as they help the developer to identify the issue fast and fix it the right way.
I don't put a message for the case you cite, unless I'm running a test where I have an array of similar test values that I'm running in a loop and I want to pinpoint exactly which one failed. Then I add a message to tell me which one.
I agree that providing a message is helpful and I always provide one.
To me, the useful thing to include is a clear statement of what went wrong - usually involving the words 'should' or 'should not'.
E.g., "objects are equal" is ambiguous - does it mean the objects are equal and that's why the test failed? Or that objects should be equal but they aren't? But if you say "Objects should be equal" or "Objects should not be equal" it's obvious why the assertion failed.
I particularly like how the Spock test framework encourages tests that read like a story and have come to structure tests under different frameworks similarly. I'm not particularly concerned about the individual error message making a lot of sense, I aim for quickly wrapping my head around the entire test once I open it:
assertEquals("Cloned and persisted items", mockedTiCount, clonedTis.size());
assertTrue("Belong to new transaction", clonedTis.stream().allMatch(ti -> ti.getTransaction().getId().equals(cloned.getId())));
assertNotEquals("Which has a different ID", t.getId(), cloned.getId());
assertEquals("While the originals are left intact", mockedTiCount, transactionItemRepository.findByTransactionId(t.getId()).size());
Opting for many small tests instead of few large ones helps here as well, as does a neatly structured, hopefully reusable, test setup code.

Is defining a "ProbableBugException" code smell, paranoia or good practice?

In my Java code, I occasionally run into situations where I have to catch a checked exception from a library function that I'm pretty sure can't occur in my use case.
Also, when coding, I sometimes notice that I'm relying on certain inputs from other modules (my own) to have or not have particular features. For example, I might expect a string to be in a certain format etc. In these situations, I would often put in a verification step, although I control the code that send the input myself.
At the moment, I'm working on a quite complex product that I want to be very reliable. Among other things, I want it to collect information from caught exceptions and automatically file bug reports. For the above two scenarios, I therefore defined an (unchecked) "ProbableBugException", that tells me I made a mistake in the code delivering the input data.
Is that a) stupid, b) paranoid or c) good practice? This is going to be subjective, I'll put up three wiki answers so we can vote away without rep warping.
ETA:
Thanks to Svend for pointing out that Java has assertions, I didn't realize that. Assertions are actuall pretty much what my question was about, but I only knew them from C and have never used them there.
I'm thinking that using an assert is what you really want there ("probably bug").
It's stupid, because:
the exception should be much more specific, like InvalidInputException
you should think harder about the input side, it's likely that it's shaky if you feel you need that kind of exception
It's good practice, because:
you might have a coworker coding on the input side and the two of you might have misunderstood each other
if you make a mistake, fixing it becomes trivial
in situations where the input side is a plugin of some sort, it helps the plugin developers (who might be external) to deliver correct input.
I always expect the unexecpected.
I often have code like this : ( $div will never be 0 into my code )
if( $div != 0 ) {
$var = $var2 / $div;
} else {
/*
* It should never happen
*/
throw Exception( 'relevant message' );
}
I always protect myself from me and the others

Categories