Reinstalling a refactoring conditional variable

I'm working on the project. I currently have a rather large conditional statement that assigns a value to a variable based on some input parameters. So, I have something like this.

if some condition
  x = some value
elsif another condition
  x = a different value
  ...

What is the best way to reorganize this? I hope that I can get something like

x = some value if some condition || another value if another condition

Is there a sample for this kind of thing?

+5
source share
5 answers

Just set the destination outside the if.

x = if some condition
  some value
elsif another condition
  a different value

Or you can use a hash.

x = dict[some condition]
+9
source

The conditional operator is also an expression, so one of the first things you can do if the variable is the same in each condition:

x = if cond1
  expr1
elsif cond2
  expr2
....
end

- , , case.

, , , .

.

# Where conditional is currently, and x assigned, assuming the conditionals
# need a couple of variables . . .
x = foo param1, param2

# Elsewhere
private

def foo p1, p2
  if cond1
    expr1
  elsif cond2
    expr2
  ....
  end
end
+1

, . , , :

If Condition is true ? Then value X : Otherwise value Y

:

speed = 90
speed > 55 ? puts("I can't drive 55!") : puts("I'm a careful driver")

, .

0
x = some condition ? some value : 
    another condition ? a different value : ...
0

, refactor.

There is not enough detail in your question to go further with recommendations, but this refactor will make your code base much more resistant to changes. If you get a new requirement, this is a bad form to break down the conditional and change it (more prone to introducing errors, more difficult to fulfill); It is advisable to create a new object that can be connected to an existing code base. This flexibility is what the Open / Closed Principle describes (“O” in SOLID).

0
source

All Articles