ruby - How can I refactor these methods and remove the dependency checks on the first lines -


i'm making form pre-calculates of fields. so, have bunch of methods rely on previous methods, or should return nil. @ moment i'm doing series of checks, , i'd remove them.

(ignore calculations, examples)

def age   return unless dob  # not bad...    date.today - dob end  def age_at_start   return unless dob && start_date  # getting worse   start_date - dob end  def compensation   return unless age_at_start && time_worked && salary && staff_rating  # shoot me   some_calculation(age_at_start, time_worked, salary, staff_rating) end 

it partially depends on you're really doing, aside example--without context it's difficult know meaningful under circumstances.

can't better than:

def age   date.today - dob if dob end 

same one--i wouldn't break out guard clause yet:

def age_at_start   dob && start_date ? start_date - dob : nil end 

here i'd break out guard clause, because (a) can, , (b) imo testing easier:

def compensation   some_calculation if can_be_compensated? end  def can_be_compensated?   age_at_start && time_worked && salary && staff_rating end 

if some_calculation 'external' , needs args, might wrap in method has access original , can_be_compensated?.


Comments

Popular posts from this blog

java - Play! framework 2.0: How to display multiple image? -

gmail - Is there any documentation for read-only access to the Google Contacts API? -

php - Controller/JToolBar not working in Joomla 2.5 -