Exercises


  1. Concatenating a new line character to the end of a string has created repetitive code. Extract this functionality to a new utility method on the class util.StringUtil. Mark StringUtil as a utility class by changing its constructor's access privilege to private. You will need to move the class constant NEWLINE to this class. Use your compiler to help you determine impacts on other code. Ensure that you have tests for the utility method.

  2. Transform your Pawn class into a more generic class named Piece. A Piece is a color plus a name (pawn, knight, rook, bishop, queen, or king). A Piece should be a value object: It should have a private constructor and no way to change anything on the object after construction. Create factory methods to return Piece objects based on the color and name. Eliminate the ability to create a default piece.

  3. Change BoardTest to reflect the complete board:

     package chess; import junit.framework.TestCase; import util.StringUtil; public class BoardTest extends TestCase {    private Board board;    protected void setUp() {       board = new Board();    }    public void testCreate() {       board.initialize();       assertEquals(32, board.pieceCount());       String blankRank = StringUtil.appendNewLine("........");       assertEquals(             StringUtil.appendNewLine("RNBQKBNR") +             StringUtil.appendNewLine("PPPPPPPP") +             blankRank + blankRank + blankRank + blankRank +             StringUtil.appendNewLine("pppppppp") +             StringUtil.appendNewLine("rnbqkbnr"),          board.print());    } } 

  4. Ensure that a new Board creates sixteen black pieces and sixteen white pieces. Use a class counter on the Piece object to track the counts. Make sure you can run your tests twice without problems (uncheck the "Reload Classes Every Run" box on JUnit and click Run a second time).

  5. Create methods isBlack and isWhite on the Piece class (test first, of course).

  6. Gather the names of each of your test methods. Put the class name in front of each test name. Show the list to a friend and ask what the methods say about each class.

  7. Read over the section on Simple Design again. Does your current chess design follow the patterns of simple design?



Agile Java. Crafting Code with Test-Driven Development
Agile Javaв„ў: Crafting Code with Test-Driven Development
ISBN: 0131482394
EAN: 2147483647
Year: 2003
Pages: 391
Authors: Jeff Langr

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net