Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implicit typing and TDD

I just read this post and it makes the case against implicit typing using when starting out with Test driven development/design.

His post says that TDD can be "slowed down" when using implicit typing for the return type when unit testing a method. Also, he seems to want the return type specified by the test in order to drive development (which makes sense to me).

A given unit test with implicit typing might look like this:

public void Test_SomeMethod()
{
    MyClass myClass = new MyClass();

    var result = myClass.MethodUnderTest();
    Assert.AreEqual(someCondition, result);
}

So my questions are:

Does using implicit typing help or hinder writing unit tests for TDD? Is there anyone out there that can share their experience using this technique when writing unit tests?

I ask this because soon I have not done TDD and want to know if there is a way to write generic or semi-generic unit tests that would work a return type might change.

like image 233
cmw Avatar asked Oct 14 '22 10:10

cmw


1 Answers

I see his point but I don't really think it's the right reason to not use var here. Remember, TDD works roughly according to the following:

  1. Write a new test.
  2. If test fails to compile (and it should fail!), write enough code until the test compiles.
  3. Run all tests.
  4. If a test fails, write enough code until all tests pass.
  5. Refactor.

Whether or not we use var the test will fail to compile either way because the method under test won't exist yet!. Once we start coding up NewMethod his points are rather moot.

Rather, the right reason to not use var here is because the code gives no indication what the type of result is. This is a matter of opinion but var is okay here

var dict = new Dictionary<Foo, List<Bar>>();

and for anonymous types but not here

var m = M();

because it's completely unclear without going to the declaration of M (or using IntelliSense) what the return type of M is.

like image 112
jason Avatar answered Oct 18 '22 20:10

jason