ASP.NET MVC Preview 3 was released today and while browsing through the code I saw something which I have seen before but never really reflected on.

protected internal ViewResult View() {
    return View(null /* viewName */, null /* masterName */, null /* model */);
}

protected internal ViewResult View(object model) {
    return View(null /* viewName */, null /* masterName */, model);
}

See how they have an inline comment with the argument name for the null arguments? This is a really nice practice as it makes function calls where nulls are passed much more readable and understandable. Functions that take in objects that can be null or booleans can often be very cryptic since you don't know what argument they represent. In some languages like ruby you can optionally name arguments:

def View(model)
  return View(viewName: nil, masterName: nil, model: nil)
end

For functions taking in booleans you have the option to instead use an enum, this can in some cases make function calls a lot more understandable. For example:

FileStream stream  = File.Open (“foo.txt”, true, false);
FileStream stream  = File.Open (“foo.txt”, CasingOptions.CaseSenstative, FileMode.Open);

For parameters that can be null you could instead use the null object pattern but this might not be feasible in many scenarios so I think that having a short comment like in the first code snippet is a nice way to handle this.

6 comments:

Γιώργος Κασσελάκης said...

named arguments are possible in VB too and I think for C# also. In VB you write it as:
return View(viewName:= nothing, masterName:= nothing, model:= nothing)

etc. I think it's just a choice on the part of the MVC people.

Torkel Ödegaard said...

No, C# does not support named arguments. I dont't think VB.NET does either, I think it only supports it for optional arguments.

Georgios Kasselakis said...

VB absolutely supports them. It's the syntax that I mentioned. I've been using them since VB9 came out.

Apparently C# 08 does that too http://ub0.cc/7q/17

Torkel Ödegaard said...

Ok, did not know that VB supported named arguments.

C# 3.0 does not, that example is using anonymous methods which is something completely different.

Georgios Kasselakis said...

argh I was hasty, I knew that you could do named args in attributes in C#, and combined with the post I generalized.
It's a tie then :P .

Sasi said...

Cool. MVC 6 has wonderful features.

ASP.Net MVC Training
Online MVC Training
.Net Training in Chennai
MVC Training in Chennai