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

1

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!

🐧

Image of Datadog

The Future of AI, LLMs, and Observability on Google Cloud

Datadog sat down with Google’s Director of AI to discuss the current and future states of AI, ML, and LLMs on Google Cloud. Discover 7 key insights for technical leaders, covering everything from upskilling teams to observability best practices

Learn More

Top comments (0)

AWS Security LIVE!

Tune in for AWS Security LIVE!

Join AWS Security LIVE! for expert insights and actionable tips to protect your organization and keep security teams prepared.

Learn More