Reputation: 307
I need some help refactoring some ruby code. Im not keeping it DRY at all.
if potatoes
if item.type != nil
if item.has_stuff == false && (item.something_else).to_f >= (comparing).to_f
# RUN JOB A
else
# RUN JOB B
end
else
# RUN JOB A
end
else
# RUN JOB B
end
I just created random names for things.
Upvotes: 1
Views: 60
Reputation: 71
If you associate the jobs to external methods (defined elsewhere) you can keep it dry by using ternary operators, and using a different perspective, considering that the conditions are complementary... to keep the code more readable you can write the conditions on different lines, if you wish, or you should use a method to perform the checks (i.e. item.has_stuff == false && (item.something_else).to_f >= (comparing).to_f) if meaningful in your code...
A quick example:
def is_empty_and_something_less_than_something?(comparing)
item.has_stuff == false && (item.something_else).to_f >= (comparing).to_f
end
job_a_conditions= potatoes && (item.type.nil? || item.is_empty_and_something_less_than_comparing?(comparing))
job_a_conditions ? job_a : job_b
The same conditions can be associated to a method, if re-used in your code.
Upvotes: 1
Reputation: 22385
if potatoes && (item.type.nil? || (item.has_stuff == false && (item.something_else).to_f >= (comparing).to_f))
# JOB A
else
# JOB B
end
But for such complicated logic, it might be better to pull part of that into a method
def item.has_some_property?(comparing)
has_stuff == false && something_else.to_f >= comparing.to_f
end
if potatoes && (item.type.nil? || item.has_some_property?(comparing))
# JOB A
else
# JOB B
end
Upvotes: 2
Reputation: 168269
if !potatoes
# Job B
elsif item.type.nil?
# Job A
elsif item.has_stuff != false
# Job B
elsif item.something_else.to_f >= comparing.to_f
# Job A
else
# Job B
end
Upvotes: 1