Function calculate_attribute does not return a value; it only works through side effects.
Often within that function I have to write these few lines:
print('some message')
set_attribute(value)
return
So I decided to put this into a different function:
def report_and_set(value, message):
print(message)
set_attribute(value)
Is it ok to now do the following:
def calculate_attribute(params):
#...
if something:
return report_and_set(value, message)
#...
if another_condition:
return report_and_set(value, message)
#...
It feels kinda weird to write this since report_and_set has no return value. But if I don’t, I’d have to repeatedly type return after every call to report_and_set.
Many programmers, myself included, prefer a single
returnper function.Occasionally, I may insert a
returnin the first few lines of a function to bail if some sanity check fails.I wouldn’t in this case.
In this case, I would simply do…
But also consider the Single Responsibility Principle (it applies equally to functions and classes). If your function is long and contains lots of conditional function invocations,
it’s probably time to refactor!