Java alternative to if statement

альтернатива оператору if в java

так что, как вы видите, все операторы if являются отдельными, а не другими условиями. Обратите внимание, что XYZ — это совершенно разные условия, поэтому переключатель не подходит.

Хотя любопытство может быть забавным . зачем мне альтернатива if, особенно когда условие состоит в том, что переключатель не подходит? Как будто Java еще недостаточно раздулась. — ty812

либо то, что вы пытаетесь сделать, глупо (если это здорово!), либо вам нужно предоставить больше информации. Я могу представить себе ситуацию, когда подобный код можно было бы обработать с помощью шаблона обмена сообщениями или чего-то еще интересного (при условии, что ваша ситуация не так проста, как вы ее объяснили). — twolfe18

Что вы ожидаете от этой альтернативы, чего не может предоставить представленный код? (меньше символов, больше читаемости?) — Zed

@Hellnar: Есть дополнительные знания, которые имеют ценность, и есть неясный код для гольфа. — S.Lott

11 ответы

Одним из «истинно объектно-ориентированных» ответов было бы определить интерфейс для «Правила» (с методами condition() и action()), создать 3 реализации, поместить их в коллекцию, а затем просто выполнить итерацию по ним в общем, как в:

Список правила = . ; // ваши 3 правила каким-то образом инициализированы здесь for(Rule r : rules) < if(r.condition()) < r.action(); >>

Это имеет гораздо больше смысла, если у вас есть 300 правил/условий, а не только 3. В Java8 вы можете сделать это вместо этого, если правила интенсивно используют ЦП:

rules.parallelStream().filter(Rule::condition).forEach(Rule::action); 

Карта здесь не сработает, потому что условие уникально для каждой реализации правила. Map требует фактического ключа, а не какого-то кода, скрытого в вызываемом методе. — Alex R

  1. Полиморфизм, когда поведение зависит от начальных значений
  2. Ссылочное присвоение, когда вы знаете возможные начальные значения, и они имеют корреляцию 1 к 1 с возвращаемыми значениями. Списки для этого лучше, чем массивы, но.
// Example: if (a==1) < b=2; >if (a==2) < b=17; >// Becomes int fx(2); // our array of answers fx[0] = 2; fx[1] = 17; b = fx[ a - 1 ]; 
// Example: if (a==1) < doSomething1(); >if (a==2) < doSomething2(); >// Becomes function * fx(2); // our array or better still, list of functions fx[0] = &doSomething1; fx[1] = &doSomething2; `fx[ a - 1 ](); ` 
if (thisCondition == true) < b = true; >else

Альтернативы if-else в Java — оператор switch и оператор условно троичный (?:), ни один из которых не делает именно то, что вы просите (обрабатывает только if без else ). Код, который вы разместили, — лучший способ сделать это, на мой взгляд.

interface SomethingDoer < public void doSomething(); >class ADoer implements SomethingDoer < . >class BDoer implements SomethingDoer < . >class CDoer implements SomethingDoer < . >public class Main < public static void main (String[] args) < SomethingDoer doer = new SomethingDoerFactory(args).getDoer(); doer.doSomething(); >> 

Оператор if не устранен полностью, но перемещен в SomethingDoerFactory. Это решение применимо не во всех случаях, но в некоторых из них является очень хорошей альтернативой множественным «если».

Любые комментарии о том, почему вы минусуете? Разве это не альтернатива? Или это недостаточно хорошо, чтобы быть упомянутым? — Артемб

Я бы рассматривал полиморфное решение только в том случае, если бы мое условное выражение уже было основано на напишите. Я бы не стал создавать целую иерархию классов только для того, чтобы заменить if(x) do a; — Билл Ящерица

во многих случаях это имеет смысл. видеть youtube.com/watch?v=4F72VULWFvc — говорит технический специалист Google. (Разговоры о чистом коде — наследование, полиморфизм и тестирование) я считаю, что отрицательный голос неправильный. — Андреас Петерссон

Прямо со слайдов Мисько: «иногда if — это просто if «. Если вы не будете повторно использовать эти операторы if во многих местах, это сделает вещи излишне сложными. Также: ваше решение неполное. Что, если выполняются оба условия x и y? Вы пропустили AAndBDoer, AAndCDoer, BAndCDoer, AAndBAndCDoer; они хорошо покрыты исходным кодом. — Зак Томпсон

Очевидно, это зависит от того, что именно означает «делать». Полиморфизм вполне может быть отличным решением, но пример слишком общий, чтобы иметь единственное решение для всех случаев. AAndBDoer и т. д. обычно решаются с помощью шаблонов Decorator/Composition для решения типа полиморфизма. — Eek

это самое простое, читабельно, но эффективно решение. Я был бы удивлен, увидев здесь эффективные альтернативы.

можно попробовать применить метод извлечения несколько раз:

Я делаю это в прошивке для устройства, в котором может быть включено или отключено множество различных опций. Я бы предпочел, чтобы мой main() вызывал такие вещи, как doFooIfEnabled(), чем загромождал его множеством ifs и #ifdefs. — Жанна Пиндар

Как и любой шаблон, есть моменты, когда его следует использовать, и моменты, когда его не следует использовать. — бдонлан

Сделайте что-то вроде этого: внедрите Enum на основе условия и вызовите метод переопределения.

public enum Rule < a()< @Override public void do()< // do something. >>, b() < @Override public void do()< // do something. >>, c() < @Override public void do()< // do something. >public abstract void do(); > > public class Test < public static void main(String[] args)< Rule r = Rule.valueOf("a"); r.do(); >> 

Источник

alternative to if statement in java

One «truely object oriented» answer would be to define an interface for «Rule» (with condition() and action() methods), create 3 implementations, stuff them into a collection, and then just iterate through them generically as in:

List rules = . ; // your 3 rules initialized here somehow for(Rule r : rules) < if(r.condition()) < r.action(); >>

This makes a lot more sense if you have 300 rules/conditions rather than just 3.

In Java8, you may want to do this instead, if the rules are CPU-intensive:

rules.parallelStream().filter(Rule::condition).forEach(Rule::action); 

Solution 2

There are a few time you can avoid using if for conditional evluation and branching all together. And they have moments of appropriateness.

  1. Polymorphism, when behavior is dependent on the initial values
  2. Referrenced Assignment, when you know the possible initial values and they have 1 to 1 correlation with the return values. Lists are better than arrays for this, but.
// Example: if (a==1) < b=2; >if (a==2) < b=17; >// Becomes int fx(2); // our array of answers fx[0] = 2; fx[1] = 17; b = fx[ a - 1 ]; 
// Example: if (a==1) < doSomething1(); >if (a==2) < doSomething2(); >// Becomes function * fx(2); // our array or better still, list of functions fx[0] = &doSomething1; fx[1] = &doSomething2; `fx[ a - 1 ](); ` 
if (thisCondition == true) < b = true; >else

Solution 3

The alternatives to if-else in Java are the switch statement and the conditional ternary (?:) operator, neither of which do exactly what you’re asking (handle just an if with no else ). The code you posted is the best way to do it, in my opinion.

Solution 4

this is the most simple, readable yet effective solution. I would be surprised to see effective alternatives here.

you can try to apply extract method several times:

where methods are defined by:

Solution 5

interface SomethingDoer < public void doSomething(); >class ADoer implements SomethingDoer < . >class BDoer implements SomethingDoer < . >class CDoer implements SomethingDoer < . >public class Main < public static void main (String[] args) < SomethingDoer doer = new SomethingDoerFactory(args).getDoer(); doer.doSomething(); >> 

The if is not completely eliminated, but it is moved to SomethingDoerFactory. This solution is not applicable in all cases, but in some of them it is a very good alternative to multiple ifs.

Источник

Java if-else statement

In Java, the «if-else» statement plays a crucial role in controlling the flow of program execution based on specific conditions. This statement allows developers to determine whether a particular block of code should be executed or not, depending on the evaluation of a condition.

The fundamental concept behind the «if-else» statement is to execute a specific block of code if a given condition evaluates to true. If the condition is false, an alternative block of code specified by the «else» clause is executed instead. This construct provides a way to make decisions and perform different actions based on the outcome of a condition.

Java if statement

The «if» statement in Java is a control flow statement that allows you to execute a block of code conditionally based on the result of a Boolean expression.

The expression is a boolean expression that returns either true or false. If the expression evaluates to true, the code inside the set of curly braces will be executed, and if it evaluates to false, the code inside the curly braces will be skipped.

How to java if else statements

Example:

Java if-else statement

The «if-else» statement in Java is an extension of the «if» statement that allows you to specify an alternate block of code to be executed if the expression is false.

The expression is a boolean expression that returns either true or false. If the expression evaluates to true, the code inside the first set of curly braces will be executed, and if it evaluates to false, the code inside the second set of curly braces <. >will be executed.

Multiple if-else statements in Java

You can also chain multiple if-else statements together to handle multiple conditions:

In the above case, only the first expression that evaluates to true will have its corresponding code block executed, and all subsequent expressions and code blocks will be skipped.

Nested if-else statement in Java

A «nested if» statement in Java is an » if» statement that is contained within another «if» statement. The basic idea behind a nested «if» statement is to test multiple conditions in a single control flow statement.

In the above example, the first «if» statement tests the condition represented by expression1. If expression1 evaluates to true, the code inside the first set of curly braces will be executed. Within this code block, there is another «if» statement that tests the condition represented by expression2. If expression2 also evaluates to true, the code inside the second set of curly braces will be executed.

Nested «if» statements can be useful when you need to test multiple conditions in a single control flow statement. For example, you might use a nested «if» statement to check if a variable is within a certain range and take different actions based on whether the variable is greater than, less than, or equal to a certain value.

Common uses of the «if-else» statement in Java

  1. Conditional execution: The most common use of the «if-else» statement is to conditionally execute a block of code based on the result of a Boolean expression. For example, you might want to execute a block of code that performs a calculation only if a certain variable has a specific value.
  2. Decision making: The «if-else» statement can also be used to make decisions in your code based on different conditions. For example, you might use an «if-else» statement to determine which of two different actions to take based on the value of a variable.
  3. Error checking: The «if-else» statement can also be used to check for errors or invalid inputs in your code. For example, you might use an «if-else» statement to validate user input and display an error message if the input is not valid.
  4. Multiple branches: The «if-else» statement can also be used to handle multiple branches of execution based on different conditions. For example, you might use multiple «if-else» statements to handle different cases in a switch statement.

Alternative of if statement in Java

There are alternatives to the «if» statement in Java that can be used to control the flow of execution of a program based on certain conditions. Following are some of the most common alternatives:

Switch statement:

The «switch» statement is an alternative to the «if-else» statement that allows you to execute different blocks of code based on the value of a single expression. The «switch» statement is often used when you need to handle multiple cases for the same expression. For example, you might use a «switch» statement to handle different menu options in a program.

Ternary operator:

The ternary operator is a compact alternative to the «if-else» statement that allows you to write simple conditional expressions in a single line of code. The ternary operator takes the form expression1 ? expression2 : expression3, where expression1 is the condition, expression2 is the value to be returned if the condition is true, and expression3 is the value to be returned if the condition is false.

Conditional operator:

The conditional operator is another alternative to the «if-else» statement that allows you to write simple conditional expressions in a single line of code. The conditional operator takes the form expression1 ?: expression2, where expression1 is the condition and expression2 is the value to be returned if the condition is false.

These alternatives can provide a more concise, efficient, and readable way to control the flow of execution in your program, depending on the specific requirements of your code. It’s important to choose the right alternative for your use case based on the desired behavior, performance, and readability of your code.

Summary:

The correct syntax and indentation when using nested «if» statements, as well as to choose appropriate expressions that evaluate to true or false in order to produce the desired behavior in your code. Additionally, it’s a good idea to be mindful of the complexity and readability of your code, as nested «if» statements can quickly become difficult to understand if they are not well organized and properly indented.

Источник

Читайте также:  Javascript interop calls cannot be issued at this time
Оцените статью