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?
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:
if (providers.length == 0) {
throw new IllegalArgumentException();
}
this.providers = providers;
And in order to make things easier to read, you could even go for:
checkProvidersNotEmpty(providers);
this.providers = providers;
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.
Method Call using Ternary Operator
It's the same thing for Java, you have to return the same type of object.
I don't think you can actually do this because the statement throw new IllegalArgumentException()
cannot be assigned to providers
.
From Java documentation about Equality, Relational, and Conditional Operators :
The Conditional Operators
[...]
Another conditional operator is ?:
, which can be thought of as
shorthand for an if-then-else
statement (discussed in the Control
Flow Statements section of this lesson). This operator is also known
as the ternary operator because it uses three operands. In the
following example, this operator should be read as: "If
someCondition
is true
, assign the value of value1
to result
.
Otherwise, assign the value of value2
to result
."
You could do that too:
this.providers = providers.length > 0 ? providers : null;
if (this.providers == null)
throw new IllegalArgumentException();
But normally You should let Your code in cases like that as it is.
That's in that case much better and less complicated.