5

I'm looking for a reference to clean coding styles that I can pass to a team member.

In particular, the rule that a method should not change its return type based on an input parameter. If you need different output, use a different method.

Example:

$invoice_items = getInvoiceItems();
$total         = getInvoiceItems( TRUE );

To me, this is bad coding style (and I'm not even talking about a parameter whose meaning can't be determined from the calling code).

The above example should actually be:

$total = totalInvoiceItems();

... where totalInvoiceItems() might call getInvoiceItems() to get the items it needs to total.

Where would I find a reference to this (and possibly other important coding style rules)?

14

As Eric said, the boolean flag as a behavior selector is a tell-tale sign that something's wrong with the function's contract.

Reasons, why this is a problem

  • The function contract is unnecessarily complicated. It's easy to explain the contract of a function that simply returns all invoice items, just as well as it is easy to explain a function that takes a list of invoice items and returns the sum of their payment amounts. It's much more involved to explain the optional boolean parameter version.

  • The function name is not telling you what the function does anymore. getInvoiceItems sounds like it should give me some items, not a sum value. Analogously, splitting it into two functions gives you something like sumOfInvoiceItems($items), which is self-explanatory again.

  • The function implementation itself is unnecessarily complicated. The simpler a function, the easier it is to understand, explain, verify, ... More complex functions are better at attracting bugs, so simple is better.

References

  • The main reference about clean code is of course the book of the same name by Uncle Bob. You will find more detailled reasoning there for keeping your functions short and simple with clean contracts and to name them well.

  • Albeit it is usually applied to classes, instead of functions, the Single Responsibility Principle can also be applied to a function. But anyways, the SRP also stems from Uncle Bob, so I guess the real reference is just Uncle Bob himself.

5

Functions should behave consistently. There is a second function hidden in functions with a boolean parameter anyway.

If there is a branch inside the function with two mostly different behaviors, why not make it two function and maybe factor the common code into a third? Is there a shortage of function declarators?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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