Reputation: 1
I need help with refactoring my program. I have a function that I am calling in two programs. In one program i just need the overtimeAmount, and in the other program I need all three variables returned. How can I refactor this two only return the variables i need for the program.
def OT2(hours, rate):
if hours > 160.0:
overtimeHours = hours - 160.0
overtimeRate = rate * 1.05
overtimeAmount = overtimeHours * overtimeRate
else:
overtimeAmount = 0.0
overtimeRate = 0.0
overtimeHours = 0.0
return overtimeHours, overtimeRate, overtimeAmount
Upvotes: 0
Views: 174
Reputation: 3877
Instead of having one function that does two things, use two functions. That'll go a long way in terms of maintainability and follows the Unix philosophy of doing one thing well:
def get_overtime_hours(hours):
return max(0, hours - 160)
def get_overtime_info(hours, rate):
overtime_hours = get_overtime_hours(hours)
if overtime_hours > 0:
overtime_rate = rate * 1.05
overtime_amount = overtime_hours * overtime_rate
else:
overtime_amount = 0.0
overtime_rate = 0.0
return overtime_hours, overtime_rate, overtime_amount
Upvotes: 2
Reputation: 18876
It's good advice to never return a variable amount of results because it makes your function unpredictable; instead, either
PEP 8 has some words about this in Be consistent in return statements, but doesn't explicitly cover your case
Be consistent in return statements. Either all return statements in a function should return an expression, or none of them should. If any return statement returns an expression, any return statements where no value is returned should explicitly state this as return None, and an explicit return statement should be present at the end of the function (if reachable) [..]
Upvotes: 1
Reputation: 83577
One possibility is to add a third parameter to indicate what you want returned and then an if statement to decide what to return. That doesn't seem any cleaner than just returning all 3 values and ignoring the ones you don't want.
Upvotes: 0