parameter modifiers

Keep It Simple With Parameter Modifiers

 

Today’s post will be my last on parameters for some time. We’ll have mined this vein to exhaustion.

OK, let’s get this show on the road.

I recently suggested that when programming in C#, we should avoid the ‘out’ parameter modifier. Today I would like to posit that we should do the same with the ‘in’ and ‘ref’ parameter modifiers.

The main reason for shunning ‘in‘, ‘out‘ and ‘ref‘ in your code is that you’re going to confuse your fellow developers. They rarely come across these in their day-to-day programming. When they do, they will need to go to the C# documentation to refresh their memories and review the online code examples. I would expect them to want to step through your code and check how it behaves.

All this effort and for what?

Values types, like int, retain their value when being passed as an argument into a method. Unless the parameter and argument are both modified by ‘ref‘. A better way is to return the changed value from the method. If the function already has a return type, include the value you want in a compound return type. Similarly for ‘out‘. Let’s stay standard and use the return value. That’s why we have it.

On the other hand, the ‘in‘ modifier protects parameters from modification in the function—in a limited way—reference types cannot be reassigned. ‘in‘ was introduced as a performance improvement. Any nanosecond performance gain won’t be worth the effort if developers are confused and need to look up how to use it. I have never seen it applied other than in examples. Hopefully it stays that way.  

Even though I agree that developers should know their programming language, it is inevitable that we will forget rarely used language features. Furthermore, language designers provide us with many different options for writing programs. It’s in their interest to keep evolving their language and livelihood. Unfortunately, that does not mean that all new language features are necessarily warranted and that we should use them. Our objective of writing simple, clean, easy-to-maintain programs is not always aligned with their goal of further evolving the language.

Please keep it simple with parameter modifiers.

0 replies

Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply