Juri Strumpflohner
Juri Strumpflohner Juri is a full stack developer and tech lead with a special passion for the web and frontend development. He creates online videos for Egghead.io, writes articles on his blog and for tech magazines, speaks at conferences and holds training workshops. Juri is also a recognized Google Developer Expert in Web Technologies

Use The "var" Keyword to Have More Maintainable Tests!?

2 min read

I have to admit that initially when the "var" keyword has been introduced in C# I was quite precautious in using it. It does reduce code readability, I thought. In the end I'd say it's pretty much a matter of style and preferences, but not only, it even might help you in avoiding to break your code when you make changes, thus leading to a more maintainable code base.

I recently had the following scenario in a lot of tests where I verified the correct validation of my entities
public void TestSomething()
{
//Arrange
...

//Act
IList<ValidationError> result = validationProvider.Validate(entity);

//Assert
Assert.AreEqual(3, result.Count(), "There should be 3 validation errors");
}
However, with the new changes to our architecture I'm currently working on, I try to adapt the validation to the one proposed by ASP.net MVC and Entity Framework, still allowing to write validation rules in the same way we were accustomed so far. This led to a couple of breaking changes however, as I took the opportunity to make some improvements. As a result the return type of the validation adapter wasn't an IList any more, but instead IEnumerable<ValidationResult>. Note the generic type of the list changed as well. As a consequence the tests didn't compile any more and I had to manually fix them all (although it was just a matter of search&replace ;)).

Instead, if I had written those tests by not explicitly defining the collection type but rather to just declare them using the var keyword, my tests would have continued to work without any problems.
public void TestSomething()
{
//Arrange
...

//Act
var result = validationProvider.Validate(entity);
...
}

Questions? Thoughts? Hit me up on Twitter
comments powered by Disqus