Code4IT

The place for .NET enthusiasts, Azure lovers, and backend developers

Clean Code Tip: Keep the parameters in a consistent order

2021-11-30 1 min read Clean Code Tips
Just a second!
If you are here, it means that you are a software developer. So, you know that storage, networking, and domain management have a cost .

If you want to support this blog, please ensure that you have disabled the adblocker for this site. I configured Google AdSense to show as few ADS as possible - I don't want to bother you with lots of ads, but I still need to add some to pay for the resources for my site.

Thank you for your understanding.
- Davide

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);

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);

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!

🐧