Example-guided design

This can make a good follow up after Design in the red step.

Learning Objectives

Session Outline

Connect - Spec vs Example

Write these items on notes or cards. Ask people to sort them into two sections - is it a specification or is it an example?

Concept exercise: Convert Example to Test Case

Show the description of the Shopping Basket Kata. The description includes an example. This example can be turned into a test case. You can do that without implementing the code that will make the test pass. Split into pairs and ask people to turn that specific example into code in a test case. Ask them not to implement the code - just leave everything red and not compiling.

Give people about 10 minutes for this part, or until you can see that they’ve created a test case. Ask them to take a screenshot and share their test with the group via a shared online document or whiteboard.

Review all the code and comment on any differences. Hopefully you’ll have got a wide variety of designs from the different pairs. Learning point - there is more than one way to design code, given the same example!

If they use a float to represent money then don’t stress too much. You could just show them how to do an approximate comparison with an assertEquals that has a tolerance. You could also explain that floats are not a good way to model money and suggest they use an integer and have all the prices in cents instead of dollars.

Concept explanation: Example-guided design

Working from a concrete example can help you to come up with a better design. Use the thing before you implement it. It helps you focus on the interface and making it easy to use, rather than how you’ll write the detailed code inside.

You will probably need several examples to show all the various situations the new code might need to be used in. Start with simpler examples.

Concrete: Shopping Basket

Practice using examples to build up functionality. Go back and write some more code on the Shopping Basket Kata. However, don’t start with implementing the test you just came up with. Comment it out for the moment.

Before you split into pairs to work on the kata, spend a few minutes in the whole group coming up with a test list with simple examples to do first. Something like:

When they are doing the kata, try to stop them from creating a ShoppingBasket class or Product class or calculatePrice function without first creating a test case. Have them practice using things in the test before they exist in the production code.

Conclusions: How does it work and why would you?

How do you use examples to guide design? Are there advantages to doing it this way? Discuss in pairs.