DEV Community

Cover image for Clean Code Tip: Keep the parameters in a consistent order
Davide Bellone
Davide Bellone

Posted on • Originally published at code4it.dev

Clean Code Tip: Keep the parameters in a consistent order

If you have a set of related functions, use always a coherent order of parameters.

Take this bad example:

IEnumerable<Section> GetSections(Context context);

void AddSectionToContext(Context context, Section newSection);

void AddSectionsToContext(IEnumerable<Section> newSections, Context context);
Enter fullscreen mode Exit fullscreen mode

Notice the order of the parameters passed to AddSectionToContext and AddSectionsToContext: they are swapped!

Quite confusing, isn't it?

Confusion intensifies

For sure, the code is harder to understand, since the order of the parameters is not what the reader expects it to be.

But, even worse, this issue may lead to hard-to-find bugs, especially when parameters are of the same type.

Think of this example:

IEnumerable<Item> GetPhotos(string type, string country);

IEnumerable<Item> GetVideos(string country, string type);
Enter fullscreen mode Exit fullscreen mode

Well, what could possibly go wrong?!?

We have two ways to prevent possible issues:

  1. use coherent order: for instance, type is always the first parameter
  2. pass objects instead: you'll add a bit more code, but you'll prevent those issues

To read more about this code smell, check out this article by Maxi Contieri!

This article first appeared on Code4IT

Conclusion

To recap, always pay attention to the order of the parameters!

  • keep them always in the same order
  • use easy-to-understand order (remember the Principle of Least Surprise?)
  • use objects instead, if necessary.

πŸ‘‰ Let's discuss it on Twitter or in the comment section below!

🐧

Top comments (0)