Writing Conditionals and Practicing TDD
TDD Refresher RED – write the test and watch it fail – Why do we watch it fail? GREEN – write the simplest code that can make it pass REFACTOR – cleanup – comments – variable names – eliminate duplication (pay attention to duplication between the values the test knows and the values the code knows)
Chapter Project This chapter’s project is a tax calculator You will write a series of methods that make a series of tests pass. The goal is to practice writing conditional statements
If Statements Used when we want something to happen only under certain conditions if (potatoNumber != 4) { System.out.print(" potato"); } condition then block
if-then-else Statements Used when we want to choose between two different behaviors long result = oneBack + twoBack; if (result < oneBack) { oneBack = 1; twoBack = 0; result = 1; } else { twoBack = oneBack; oneBack = result; } else block then block condition
Why have the curly brackets? Exactly one statement after the condition is considered to be inside the condition Those brackets make one statement out of a sequence of statements if (potatoNumber != 4) { System.out.print(" potato"); halfway = true; }
Watch the semi-colon What will this code do? if (potatoNumber != 4); { System.out.print(" potato"); } notice the semi-colon That semi-colon ends the one statement in the then block, so the rest of the code is NOT part of the if statement (and will always be executed).
Testing Conditionals Clearly, we cannot test every value that a system might see, so we need to target our tests on values that are likely to cause errors. Border case - A situation where a small change in input causes a fundamentally different behavior. Focus the tests on the values around that situation because those are the values where we are most likely to have a defect
Nested Conditionals if (grade > 90) { System.out.println("Excellent"); } else { if (grade > 80) { System.out.println("Average"); } else { System.out.println("Poor"); } What is the output for 95? 85? 75? 90? 80? What are the border cases?