Dear reader of Juri's TechBlog,
I moved my blog to a new domain and a new hosting solution as well. I'm now blogging on juristr.com.

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

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);
   ...
}

Posts you might also be interested in..

Credits: Hoctro | Jack Book

0 Comments:

Post a Comment