Szkolenie dla NaviExpert, 22.02.2011
Ćwiczenie z refaktoryzacji
(na podstawie Refactoring Workbook)
Agenda
Refactoring exercises
simple game example (by W. Wake)
dining philosphers
A simple game
Rules
the game implements a simplistic example of a tic-tac-toe
family
there is a board divided into squares, which are occupied by
different markers; every player has different marker ('X' or 'O')
it this case the board is linear and is 9 squares long
given a set and a player marker, the program answers with a
move
the winner is the party that lines up a sequence of three
markers in a row
the program is to be extended in future
A simple game
public class Game {
public StringBuffer board;
public Game(String s) {board = new StringBuffer(s);}
public Game(StringBuffer s, int position, char player) {
board = new StringBuffer();
board.append(s);
board.setCharAt(position, player);
}
public int move(char player) {
for (int i = 0; i < 9; i++) {
if (board.charAt(i) == '-') {
Game game = play(i, player);
if (game.winner() == player)
return i;
}
}
for (int i = 0; i < 9; i++) {
if (board.charAt(i) == '-')
return i;
}
return -1;
}
A simple game
public Game play(int i, char player) {
return new Game(this.board, i, player);
}
public char winner() {
if (board.charAt(0) != '-'
&& board.charAt(0) == board.charAt(1)
&& board.charAt(1) == board.charAt(2))
return board.charAt(0);
if (board.charAt(3) != '-'
&& board.charAt(3) == board.charAt(4)
&& board.charAt(4) == board.charAt(5))
return board.charAt(3);
if (board.charAt(6) != '-'
&& board.charAt(6) == board.charAt(7)
&& board.charAt(7) == board.charAt(8))
return board.charAt(6);
return '-';
}
}
A simple game
int pos = new Game("XOXOX-OXO").move('X');
position
gameboard
player
char winner = new Game("XOXXX-OXO").winner();
winner's marker
A simple game
Tasks
Identify smells
Suggest refactorings to remove the smells
merge loops
simplify subsequent ifs
name constants appropriately
rework duplicates in winner() method
mark '–' as empty square
replace for loops with iterator
provide extension points for scoring
Q&A
© Copyright 2026 Paperzz