I have this code:
if (providers.length > 0)
this.providers = providers;
else
throw new IllegalArgumentException();
And i want to simplify it. I went for:
(providers.length > 0) ? this.providers = providers : throw new IllegalArgumentException();
But that gives me a compiler error. Why?
You could do that too:
But normally You should let Your code in cases like that as it is. That's in that case much better and less complicated.
Method Call using Ternary Operator
It's the same thing for Java, you have to return the same type of object.
The reason why the ternary operator doesn't work is because that is for assigning values. Meaning: the "else" part after ":" needs to return a value of the same type as the "then" case after "?".
And
throw new
doesn't return a providers object ...But in the end, that doesn't matter anyway; as the really simple version of that code looks more like:
And in order to make things easier to read, you could even go for:
In other words: you move the exception throwing into a separate method. The implicit convention here would be that a method named
checkSomething()
throws an exception when the check it does fails. And beyond that: give a reasonable message when creating that exception. It will help debugging later on.You do not strive for the shortest program possible, but for the shortest version that comes with the best reading experience.
Using the ternary operator here would not result in an "easy to read" experience. Thus: forget about it.
I don't think you can actually do this because the statement
throw new IllegalArgumentException()
cannot be assigned toproviders
.From Java documentation about Equality, Relational, and Conditional Operators :