Can defaults replace overloads?
- Kotlin:
Prefer declaring functions with default parameter values to declaring overloaded functions.
source
How many results should it give?
- ABAP:
A good method does one thing, and that should be reflected by the method also returning exactly one thing.
source
Where do the checks go?
- ABAP:
Validate and fail as early as possible
source
Why return early?
- Go:
The code reads well if the successful flow of control runs down the page, eliminating error cases as they arise. Since error cases tend to end in return statements, the resulting code needs no else statements.
source
How does a function end?
- PEP 8:
Be consistent in return statements. Either all return statements in a function should return an expression, or none of them should.
source
What does a tangled function look like?
def process(order, send_mail):
if order is not None:
if order.items:
total = 0
for item in order.items:
total = total + item.price * item.qty
db.save(order, total)
if send_mail:
mailer.send(order.email, total)
return total
else:
return
else:
raise ValueError("no order")What does it look like cleaned up?
def order_total(order):
return sum(item.price * item.qty for item in order.items)
def save_order(order):
if order is None:
raise ValueError("no order")
if not order.items:
return None
total = order_total(order)
db.save(order, total)
return total
total = save_order(order)
if total is not None:
mailer.send(order.email, total)Where next?
Each language’s rules: clean code by language.