0
\$\begingroup\$

I have been tinkering with various ways to clean this up and I was wondering if it is more ideal to break this into small methods or way to accomplish this on a single line?

  def run_counters
    @num_attempts ||= 0
    @num_attempts += retry_attempt
    @all_attempts ||= 0
    @all_attempts += retry_limit
  end
\$\endgroup\$
1
  • \$\begingroup\$ Welcome to Code Review – your question has been migrated here. So that we may advise you properly, please add contextual information about what your code does, preferably a substantial part of the controller. Unlike Stack Overflow, which prefers short, abstract questions, Code Review needs full details. (See How to Ask.) \$\endgroup\$ Commented Sep 1, 2016 at 16:59

1 Answer 1

2
\$\begingroup\$

Either initialize the variables in your class's constructor (that's specifically what it's for!) or define accessor methods to isolate the initialization logic for each variable:

# via constructor:

def initialize
  @num_attempts = 0
  @all_attempts = 0
end

def run_counters
  num_attempts += retry_attempt
  all_attempts += retry_limit
end

Or:

# via accessor methods:

def run_counters
  num_attempts += retry_attempt
  all_attempts += retry_limit
end

def num_attempts
  @num_attempts ||= 0
end

def all_attempts
  @all_attempts ||= 0
end

This also means you may safely access num_attempts and all_attempts from any other method, and not have to duplicate the initialization logic.

\$\endgroup\$
1
  • \$\begingroup\$ run_counters can be split into 2 different methods IMO. \$\endgroup\$ Commented Sep 1, 2016 at 17:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.