On Github willdurand / object-calisthenics-slides
class Board { public String board() { StringBuilder buf = new StringBuilder(); // 0 for (int i = 0; i < 10; i++) { // 1 for (int j = 0; j < 10; j++) { // 2 buf.append(data[i][j]); } buf.append("\n"); } return buf.toString(); } }
public String board() { StringBuilder buf = new StringBuilder(); collectRows(buf); return buf.toString(); }
private void collectRows(StringBuilder buf) { for (int i = 0; i < 10; i++) { collectRow(buf, i); } } private void collectRow(StringBuilder buf, int row) { for (int i = 0; i < 10; i++) { buf.append(data[row][i]); } buf.append("\n"); }http://refactoring.com/catalog/extractMethod.html
public void login(String username, String password) { if (userRepository.isValid(username, password)) { redirect('homepage'); } else { addFlash('error', 'Bad credentials'); redirect('login'); } }
public void login(String username, String password) { if (!userRepository.isValid(username, password)) { addFlash('error', 'Bad credentials'); return redirect('login'); } redirect('homepage'); }
public void login(String username, String password) { String redirectRoute = 'homepage'; if (!userRepository.isValid(username, password)) { addFlash('error', 'Bad credentials'); redirectRoute = 'login'; } redirect(redirectRoute); }
class Location { class Piece { public Piece current; public String representation; } } class Board { public String boardRepresentation() { StringBuilder buf = new StringBuilder(); for (Location loc : squares()) { buf.append(loc.current.representation.substring(0, 1)); } return buf.toString(); } }
class Location { private Piece current; public void addTo(StringBuilder buf) { current.addTo(buf); } } class Piece { private String representation; public String character() { return representation.substring(0, 1); } public void addTo(StringBuilder buf) { buf.append(character()); } }
// Before: // buf.append(loc.current.representation.substring(0, 1)); // After: class Board { public String boardRepresentation() { StringBuilder buf = new StringBuilder(); for (Location location : squares()) { location.addTo(buf); } return buf.toString(); } }
Then, your method is reused multiple times.
Looks like code duplication.
Maybe your class has multiple responsabilities.
Violation of the Single Responsibility Principle.