Monday, February 20, 2012

How should I be creating classes when doing TDD


I have started doing TDD and I am unsure if I am doing it correctly. I have made a Question class and a QuestionTest. The Question class has an addAnswer method that takes an instance of the Answer class. Now, should I be creating only the class Answer and use the default constructor. Or should I be making the Answer class and also provide the constructor with parameters?




question.addAnswer(new Answer("Some", "Argument that I know I will use"));



or:




question.addAnswer(new Answer());



It is probably the last one where I write only as much as I need to proceed.

3 comments:

  1. Bob, I find that TDD works best for me if I do all my planning ahead. This includes figuring out what classes, methods and constructors are required.

    That way, ALL of my tests work, but they fail out of the box. As I complete code, however, these tests start to work. This is a bit tricky, but it does force you to really think about your tests, and make sure they actually cover all the events you wish to test for. Part of this exercise is to determine what data will be available at which time, and which constructor should be called at which time.

    Have fun with TDD, there's no laws, only guidelines, and it's probably best to do what makes sense in your situation. As long as TDD helps you to be clearer of your goals and understanding of how the application will work, I think you are on the right track.

    ReplyDelete
  2. I disagree with Ewald - "current wisdom" says do no planning ahead. Just start by writing the tests. The tests define the behaviour of your classes - the implementation is "irrelevant" (performance etc notwithstanding) as long as the tests pass.

    Initially all your tests will fail. First make them pass (any way you can). Then refactor. This work flow may be summarised with this mantra:


    Red
    Green
    Refactor


    Repeat until you're happy enough to commit your work to the code base.

    Regarding constructors, unless you have final fields, non-default constructors are a convenience, so don't use them in tests - they may not survive refactoring/review.

    ReplyDelete
  3. What I am reading is that you are test driving the creation of the Question class and during that you decide you need to create the Answer class. You want to write as little as possible and defer creating the full constructor.

    You could instead put writing QuestionTest on hold and start writing AnswerTest. Test that you can construct an Answer in the way that is required (do not make a default constructor if an Answer requires those parameters). Test that after construction your Answer behaves as you expect. You could assert that the getters return the right values if it's a dumb data class.

    Then you could return to testing Question and use the full constructor.

    ReplyDelete