Last active
January 3, 2016 12:09
-
-
Save tarynsauer/8461024 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // Original functions | |
| public void returnBoardSize() { | |
| ui.requestBoardSize(); | |
| String size = ui.returnBoardSize(); | |
| if (tryParse(size)) { | |
| validateBoardSize(size); | |
| Integer intSize = Integer.parseInt(size); | |
| setBoardSize(intSize); | |
| } else { | |
| ui.invalidBoardSizeMessage(size); | |
| returnBoardSize(); | |
| } | |
| } | |
| // Handles NumberFormatException | |
| private static boolean tryParse(String size) { | |
| try { | |
| new Integer(size); | |
| return true; | |
| } catch (NumberFormatException e) { | |
| return false; | |
| } | |
| } | |
| // Refactored methods | |
| // Sets board size to GameSettings object when valid. | |
| public void setUpBoardSize() { | |
| String size = getBoardSizeFromUser(); | |
| if (tryParse(size)) { | |
| validateBoardSize(size); | |
| setBoardSize(Integer.parseInt(size)); | |
| } else { | |
| ui.invalidBoardSizeMessage(size); | |
| setUpBoardSize(); | |
| } | |
| } | |
| // Shows bad input message and recursively calls setup method again if bad value. | |
| private void validateBoardSize(String size) { | |
| if ((Integer.parseInt(size) < MIN_BOARD_SIZE) || (Integer.parseInt(size) > MAX_BOARD_SIZE)) { | |
| ui.invalidBoardSizeMessage(size); | |
| setUpBoardSize(); | |
| } | |
| } | |
| // Gets board size string from user | |
| private String getBoardSizeFromUser() { | |
| ui.requestBoardSize(); | |
| return ui.returnBoardSize(); | |
| } | |
| // Handles NumberFormatException | |
| private static boolean tryParse(String size) { | |
| try { | |
| new Integer(size); | |
| return true; | |
| } catch (NumberFormatException e) { | |
| return false; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment