Even Microsoft Does It
If you create a new MVC 3 application in Visual Studio 2010, and look in the account controller, you’ll see the following line:
FormsAuthentication.SetAuthCookie( model.UserName,
false /* createPersistentCookie */);
Hasn’t anybody noticed C# 4.0 introduced named parameters? This was an incredibly welcome language addition to me. Here’s how I would have written the above, along with some good and bad examples demonstrating why named parameters are a good thing for readability and maintainability:
FormsAuthentication.SetAuthCookie( model.UserName,
createPersistentCookie:false );
// bad:
something.DoIt( true, false, true, 60 );
// good:
something.DoIt( updateDatabase:true, sendNotificationEmails:false,
backupFirst:true, timeoutSeconds: 60 );
// and a lot less clunky (and verbose) than this:
var updateDatabase = true;
var sendNotifcationEmails = false;
var backupFirst = true;
var timeoutSeconds = 60;
something.DoIt( updateDatabase, sendNotificationEmails,
backupFirst, timeoutSeconds );
);
Okay, so “something” is a terrible name for a variable, and “DoIt” is a terrible name for a method, but at least we have some hints as to what those mysterious parameters are for!
This language feature essentially boils down to is documentation. For some parameters, like well-named object instances, or self-explanatory strings, it’s not necessary. But for context-less data types like booleans and integers, it makes a lot of sense.










actually, I had *not* noticed that named parameters had been introduced. My only experience using named parameters was during a short jag into ObjectiveC. It’s difficult to suss out the details of the experience because it was so clunky overall, but I found them confusing. It was tough to have to look up the names of the parameters to make sure you had the casing and spelling right.
Posted on Sep 23, 2011.
Zoiks! I’m a stormtrooper!
Posted on Sep 23, 2011.
Yes, it is much clunkier in ObjectiveC, which is really more the fault of the development environment than the language itself, I suspect. If you’re using Visual Studio, you automatically see all the names of the parameters thanks to intellisense, which makes it very fluid and natural.
Yeah, the stormtrooper thing is weird…I’ve wondered myself why everyone gets that avatar, but I haven’t taken the time to look into it….
Posted on Sep 23, 2011.