How to use ternary operator with new?

余生颓废 提交于 2019-12-14 03:27:39

问题


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?


回答1:


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.




回答2:


Method Call using Ternary Operator

It's the same thing for Java, you have to return the same type of object.




回答3:


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."




回答4:


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.



来源:https://stackoverflow.com/questions/41871767/how-to-use-ternary-operator-with-new

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!