Posts
201
Comments
1111
Trackbacks
51
C# 4.0 Named Parameters for better code quality

Sometimes new features are added to a language which fundamentally change how we do things (e.g., when generics was added to .NET 2.0). However, there are other times when features are added to the language that are “syntax sugar” or “nice to have’s”. My outlook on those items has always been that “syntax sugar” is typically a good thing – if there is some feature that allows the code to be more expressive/readable then that is a great thing. Sure, the IL might not be any different behind the scenes but you want your code to be as understandable as possible and developers that come behind you can easily understand what your intent was.

To that end, I believe that named parameters being added to C# 4.0 is a good thing. I’m certainly not advocating that named parameters be used for every method call but there are several instances where this is going to be helpful in terms of code readabilty. Often you see argument passed to a method and you have no idea what the parameters are for.  Brad Abrams has a nice design guidelines post regarding Enums vs bool arguments which talks about this very thing. He discusses that enums are often a better choice than Boolean for method parameters because they express intent more clearly.  So in the case where you can’t control the method you are already calling, you can use named parameters to better express intent.

Consider this line of code:

   1:  File.Copy("source.txt", "destination.txt", true);

Unless you’re a developer that is already familiar with this method, you can only guess as to what the last Boolean parameter is for.  With C# 4.0 named parameters this code can be written like this to more clearly express intent:

   1:  File.Copy("source.txt", "destination.txt", overwrite: true);

Object initializers, while typically used in the context of LINQ, can also be used as a stand-alone language feature to express intent more clearly. For example, this snippet of code:

   1:  Person person = new Person();
   2:  person.FirstName = "John";
   3:  person.LastName = "Smith";
   4:  person.DateOfBirth = new DateTime(1970, 1, 1);

can be re-written with object initializers like this to be more concise and better express intent:

   1:  Person person = new Person() { FirstName = "John", LastName="Smith", DateOfBirth = new DateTime(1970, 1, 1)};

It’s as if you can use constructor like syntax to initialize the object – but it’s *more* readable than a constructor because the object initializer uses the property names so it’s obvious what is happening and what properties are being assigned to.  Of course, you can only use that type of syntax in C# 3.0 IF all three of those properties have publicly accessible setters.  What happens if you actually do have a constructor definition that looks like this:

   1:  public Person(string firstName, string lastName, DateTime dateOfBirth)

In that case, you have no other option in C# 3.0 other than to invoke the constructor like this:

   1:  Person person = new Person("John", "Smith", new DateTime(1970, 1, 1));

So it’s not 100% obvious what is being assigned in the constructor (e.g., that third DateTime parameter might be date of birth, might be date hired, who knows).  In C# 4.0, you can invoke the constructor like this:

   1:  Person person = new Person(firstName: "John", lastName: "Smith", dateOfBirth: new DateTime(1970, 1, 1));

This expresses intent clearly and makes the code more understandable.  Again, named parameters should not be used gratuitously but there are many instances where it can make your code higher quality.

posted on Thursday, January 22, 2009 9:51 PM Print
Comments
Gravatar
# re: C# 4.0 Named Parameters for better code quality
Steve
1/23/2009 7:03 AM
I would even like it for the first method call:
File.Copy(sourceFileName: "", destFileName: "");

It's not obvious for all methods what each parameter is.
Gravatar
# re: C# 4.0 Named Parameters for better code quality
Luke Sandell
1/25/2009 11:48 AM
I think far more useful than named parameters is optional parameters, which I believe is also coming to C# 4.0. E.g. you can leave off the last n arguments to a method call and have them be automatically assumed. The talking point has always been that you can simulate this with overloads, but this forces you to search through huge intellisense lists to get the proper overload and of course maintain all the overloads. Some API developers forgo the overloads altogether and force you to pass a null value in certain casts.

However, I think named parameters can also help in methods with a ridiculous number of parameters and overloads, particularly those dealing with reflection. See for example System.Activator.CreateInstance(). It will be interesting to see if MS will attempt to "retrofit" any of these API calls with named and optional parameters in 4.0, if that is even possible without breaking compatibility.
Gravatar
# re: C# 4.0 Named Parameters for better code quality
Aaron
2/2/2009 8:37 PM
Doesn't intellisense take care of this "need"? Really, this doesn't seem useful to me unless you're programming in Notepad.
Gravatar
# re: C# 4.0 Named Parameters for better code quality
Steve
2/3/2009 8:36 AM
@Aaron - I do see what you're saying. The fact is, the language feature is by no means some transcendent feature that is going to fundamentally change how we code - it's syntax candy. Having said that, I do believe it will help. You'll be able to look at the code that someone wrote and immediately tell what's going on without having to mouse hover over each parameter to get intellisense. Also, it's just in general, in line with the .NET framework guidelines (outlined in the Brad Abrams post).
Gravatar
# re: C# 4.0 Named Parameters for better code quality
Erik
4/20/2009 3:45 PM
Aaron,

It is more about reading the code, than writing the code. The more you can read intent revealing code the better and a bool on the end of a method call does nothing to reveal intent. IMO , relying on intellisense to make your code readable is not optimal.

Erik
Gravatar
# re: C# 4.0 Named Parameters for better code quality
Quantumplation
7/9/2009 9:24 PM
One thing I'm waiting to see (and someone fill me in if they can try it for me), is to see if named parameters can be used to create signature-identical overloads:

// Create an object with a name
public void Initialize(String name)
{}

// Create an object, pulling properties from a file
public void Initialize(String file)
{}

then:

MyObject.Initialize(name: "Foo");
MyObjec2.Initialize(file:"Bar");
Gravatar
# re: C# 4.0 Named Parameters for better code quality
Steve
7/10/2009 12:35 AM
@Quantumplation - The code you posted above will not compile. The C# 4.0 compiler enforces the same rules as previous versions of the compiler. Since named parameters are optional and there'd be no way for the compiler to resolve the method reference without them, it must enforce the same rules with regards to signature-identical overloads.
Gravatar
# re: C# 4.0 Named Parameters for better code quality
Quantumplation
7/10/2009 10:39 AM
*nods* understandable. It would have made my life just a little bit easier though. :)
Gravatar
# re: C# 4.0 Named Parameters for better code quality
Dave
10/3/2009 6:32 PM
Yeap, very good article!
Gravatar
# re: C# 4.0 Named Parameters for better code quality
Maarten
5/11/2010 8:00 AM
Good feature! If you are in a position where you can't move to 4.0 just yet, you can already start writing more readable code using /*... */ inline comments:

File.Copy("source.txt", "destination.txt", /*overwrite:*/ true);

This has been possible since 1.0, but I don't see many people using it, so I thought I'd just point it out.
Gravatar
# re: C# 4.0 Named Parameters for better code quality
Remish
5/17/2010 2:51 AM
Something strange with this feature :
with named parameters, you can change order parameters if you name them, but if you do this, you can't have two methods with same type and same numbers parameters but with differents order :
try this :
public void MaMethod(int p, string u)
{
MyProperty = p;
Console.WriteLine(u);
}
you can call it with :
var c = new MyClass();
c.MaMethod(p: 14, u: "plop");
c.MaMethod(u: "plop", p: 12);

but if you add new method :
public void MaMethod(string u, int p)
{
MyProperty = p;
Console.WriteLine("Second : " + u);
}

You can't call them, and create error compilations.
If you remove named parameters (with old style) it's work again.
Gravatar
# good work
ashu6
10/22/2010 5:39 AM
nice post.
Gravatar
# re: C# 4.0 Named Parameters for better code quality
Ashok
1/17/2012 12:19 AM
Very helpful..

Post Comment

Title *
Name *
Email
Comment *  
 

View Steve Michelotti's profile on LinkedIn

profile for Steve Michelotti at Stack Overflow, Q&A for professional and enthusiast programmers




Google My Blog

Tag Cloud