Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- Area of difficulty: coding a class constructor, initially anticipating two constructor arguments, then realising that an extra argument is needed.
- Example: TDD of a class to encapsulate forename and surname.
- Prior vision: an immutable class with two constructor arguments: forename and surname, public read-only property for each of these.
- Up to the point where I realised I wanted another constructor argument, I found TDD of this straightforward:
- Iteration 1: test that, after construction, the read-only Forename property returns the correct value. By the end of this iteration, the class constructor with both arguments has been coded, but the surname argument is not yet used. I got the test to initially fail by not assigning the Forename value.
- ```
- public class Name
- {
- public Name(string forename, string surname)
- {
- Forename = forename;
- }
- public string Forename { get; private set; }
- }
- ```
- Iteration 2: test that, after construction, the read-only Surname property returns the correct value. By the end of this iteration, the Surname property has been added and assigned to in the constructor:
- ```
- public class Name
- {
- public Name(string forename, string surname)
- {
- Forename = forename;
- Surname = surname;
- }
- public string Forename { get; private set; }
- public string Surname { get; private set; }
- }
- ```
- My difficulty arises when I now realise that I would like my class to have an additional ‘Title’ string property (Mr/Miss/Mrs), so needs an extra constructor argument. So, I want the final version of the class to have a single constructor Name(string title, string forename, string surname).
- My 3rd test is ‘Check that after construction the title property has been stored correctly.’
- After writing this test, I get it to compile by adding in the 3rd constructor parameter and the read-only property. Like the previous 2 tests, I don’t assign to it in the constructor so as to get the test to initially fail. But... I have to update the constructors in the previous 2 tests to get everything to compile. Does this undermine their integrity? Is the above the correct approach?
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement