Useful to ensure non-breaking code when calling against generated methods
In an application where a method has parameter values that are tied to fields in a database (e.g. a constructor for a test objects that has properties in the database), it's possible that, based on a change to the database, the order of the parameters might change. If the data types of the method parameters remain the same, and hand-rolled code (e.g. a unit test) calls the generated method, it can be very difficult to see that the hand-rolled code no longer matches the generated code. Named parameters can help prevent this.
For example:
A database has a table MyCreation
with columns IsBig
and IsColoured
. Using an ORM, a test method to create sample data exists to populate such data:
/* Generated Code from an ORM */
public IMyCreation CreateTestObject(bool isBig, bool isColoured)
{
IMyCreation _myCreation = new MyCreation();
_myCreation.IsBig = isBig;
_myCreation.IsColoured = isColoured;
return _myCreation;
}
A method in a hand-rolled test class makes use of this:
var myCreation = mcTest.CreateTestObject(false, true);
Now, if the DB were to change, e.g. a parameter were renamed (IsBig
becomes IsGrande
), then the order of the parameters might change, and the generated function now becomes:
/* Generated Code from an ORM */
public IMyCreation CreateTestObject(bool isColoured, bool isGrande)
{
IMyCreation _myCreation = new MyCreation();
_myCreation.IsColoured = isColoured;
_myCreation.IsGrande = isGrande;
return _myCreation;
}
However, everything will still compile. The calling code is still valid, but no longer correct, as the value for each parameter is different.
var myCreation = mcTest.CreateTestObject(false, true);
If named parameters are used, protection against generated parameter changes is achieved:
var myCreation = mcTest.CreateTestObject(isBig: false, isColoured: true);
... this code would then break (in the case of a param rename) - which is desirable!
Or, in the case of a simple parameter swap without a rename, would continue to work without needing a fix:
var myCreation = mcTest.CreateTestObject(isBig: false, isColoured: true);
would be correct, regardless of whether the function signature is
public IMyCreation CreateTestObject(bool isBig, bool isColoured)
or
public IMyCreation CreateTestObject(bool isColoured, bool isBig)
For generated code, where ugly code is more tolerable, an approach like this might be useful to force named parameters to be used.