第 14 章 Successive Refinement

    This chapter is a case study in successive refinement. You will see a module that started well but did not scale. Then you will see how the module was refactored and cleaned.

    Most of us have had to parse command-line arguments from time to time. If we don’t have a convenient utility, then we simply walk the array of strings that is passed into the main function. There are several good utilities available from various sources, but none of them do exactly what I want. So, of course, I decided to write my own. I call it: Args.

    Args is very simple to use. You simply construct the Args class with the input arguments and a format string, and then query the Args instance for the values of the arguments. Consider the following simple example:

    Listing 14-1 Simple use of Args

    You can see how simple this is. We just create an instance of the Args class with two parameters. The first parameter is the format, or schema, string: “l,p#,d*.” It defines three command-line arguments. The first, -l, is a boolean argument. The second, -p, is an integer argument. The third, -d, is a string argument. The second parameter to the Args constructor is simply the array of command-line argument passed into main.

    If the constructor returns without throwing an ArgsException, then the incoming command-line was parsed, and the Args instance is ready to be queried. Methods like getBoolean, getInteger, and getString allow us to access the values of the arguments by their names.

    If there is a problem, either in the format string or in the command-line arguments themselves, an ArgsException will be thrown. A convenient description of what went wrong can be retrieved from the errorMessage method of the exception.

    ARGS IMPLEMENTATION Listing 14-2 is the implementation of the Args class. Please read it very carefully. I worked hard on the style and structure and hope it is worth emulating.

    Listing 14-2 Args.java

    1. import static com.objectmentor.utilities.args.ArgsException.ErrorCode.*;
    2. import java.util.*;
    3. public class Args {
    4. private Map<Character, ArgumentMarshaler> marshalers;
    5. private Set<Character> argsFound;
    6. private ListIterator<String> currentArgument;
    7. public Args(String schema, String[] args) throws ArgsException {
    8. marshalers = new HashMap<Character, ArgumentMarshaler>();
    9. argsFound = new HashSet<Character>();
    10. parseSchema(schema);
    11. parseArgumentStrings(Arrays.asList(args));
    12. }
    13. private void parseSchema(String schema) throws ArgsException {
    14. for (String element : schema.split(","))
    15. if (element.length() > 0)
    16. parseSchemaElement(element.trim());
    17. }
    18. private void parseSchemaElement(String element) throws ArgsException {
    19. char elementId = element.charAt(0);
    20. String elementTail = element.substring(1);
    21. validateSchemaElementId(elementId);
    22. if (elementTail.length() == 0)
    23. marshalers.put(elementId, new BooleanArgumentMarshaler());
    24. else if (elementTail.equals("*"))
    25. marshalers.put(elementId, new StringArgumentMarshaler());
    26. else if (elementTail.equals("#"))
    27. marshalers.put(elementId, new IntegerArgumentMarshaler());
    28. else if (elementTail.equals("##"))
    29. marshalers.put(elementId, new DoubleArgumentMarshaler());
    30. else if (elementTail.equals("[*]"))
    31. marshalers.put(elementId, new StringArrayArgumentMarshaler());
    32. else
    33. throw new ArgsException(INVALID_ARGUMENT_FORMAT, elementId, elementTail);
    34. }
    35. private void validateSchemaElementId(char elementId) throws ArgsException {
    36. if (!Character.isLetter(elementId))
    37. throw new ArgsException(INVALID_ARGUMENT_NAME, elementId, null);
    38. }
    39. private void parseArgumentStrings(List<String> argsList) throws ArgsException {
    40. for (currentArgument = argsList.listIterator(); currentArgument.hasNext(); ) {
    41. String argString = currentArgument.next();
    42. if (argString.startsWith("-")) {
    43. parseArgumentCharacters(argString.substring(1));
    44. } else {
    45. currentArgument.previous();
    46. break;
    47. }
    48. }
    49. }
    50. private void parseArgumentCharacters(String argChars) throws ArgsException {
    51. for (int i = 0; i < argChars.length(); i++)
    52. parseArgumentCharacter(argChars.charAt(i));
    53. }
    54. private void parseArgumentCharacter(char argChar) throws ArgsException {
    55. ArgumentMarshaler m = marshalers.get(argChar);
    56. if (m == null) {
    57. throw new ArgsException(UNEXPECTED_ARGUMENT, argChar, null);
    58. } else {
    59. argsFound.add(argChar);
    60. try {
    61. m.set(currentArgument);
    62. } catch (ArgsException e) {
    63. e.setErrorArgumentId(argChar);
    64. throw e;
    65. }
    66. }
    67. }
    68. public boolean has(char arg) {
    69. return argsFound.contains(arg);
    70. }
    71. public int nextArgument() {
    72. return currentArgument.nextIndex();
    73. }
    74. public boolean getBoolean(char arg) {
    75. return BooleanArgumentMarshaler.getValue(marshalers.get(arg));
    76. }
    77. public String getString(char arg) {
    78. return StringArgumentMarshaler.getValue(marshalers.get(arg));
    79. }
    80. public int getInt(char arg) {
    81. return IntegerArgumentMarshaler.getValue(marshalers.get(arg));
    82. }
    83. public double getDouble(char arg) {
    84. return DoubleArgumentMarshaler.getValue(marshalers.get(arg));
    85. }
    86. public String[] getStringArray(char arg) {
    87. return StringArrayArgumentMarshaler.getValue(marshalers.get(arg));
    88. }
    89. }

    Notice that you can read this code from the top to the bottom without a lot of jumping around or looking ahead. The one thing you may have had to look ahead for is the definition of ArgumentMarshaler, which I left out intentionally. Having read this code carefully, you should understand what the ArgumentMarshaler interface is and what its derivatives do. I’ll show a few of them to you now (Listing 14-3 through Listing 14-6).

    Listing 14-3 ArgumentMarshaler.java

    1. public interface ArgumentMarshaler {
    2. void set(Iterator<String> currentArgument) throws ArgsException;
    3. }

    Listing 14-4 BooleanArgumentMarshaler.java

    1. public class BooleanArgumentMarshaler implements ArgumentMarshaler {
    2. private boolean booleanValue = false;
    3. public void set(Iterator<String> currentArgument) throws ArgsException {
    4. booleanValue = true;
    5. }
    6. public static boolean getValue(ArgumentMarshaler am) {
    7. if (am != null && am instanceof BooleanArgumentMarshaler)
    8. return ((BooleanArgumentMarshaler) am).booleanValue;
    9. else
    10. return false;
    11. }
    12. }

    Listing 14-5 StringArgumentMarshaler.java

    1. import static com.objectmentor.utilities.args.ArgsException.ErrorCode.*;
    2. public class StringArgumentMarshaler implements ArgumentMarshaler {
    3. private String stringValue =
    4. public void set(Iterator<String> currentArgument) throws ArgsException {
    5. try {
    6. stringValue = currentArgument.next();
    7. } catch (NoSuchElementException e) {
    8. throw new ArgsException(MISSING_STRING);
    9. }
    10. }
    11. public static String getValue(ArgumentMarshaler am) {
    12. if (am != null && am instanceof StringArgumentMarshaler)
    13. return ((StringArgumentMarshaler) am).stringValue;
    14. else
    15. return "";
    16. }
    17. }

    The other ArgumentMarshaler derivatives simply replicate this pattern for doubles and String arrays and would serve to clutter this chapter. I’ll leave them to you as an exercise.

    One other bit of information might be troubling you: the definition of the error code constants. They are in the ArgsException class (Listing 14-7).

    Listing 14-6 IntegerArgumentMarshaler.java

    1. import static com.objectmentor.utilities.args.ArgsException.ErrorCode.*;
    2. public class IntegerArgumentMarshaler implements ArgumentMarshaler {
    3. private int intValue = 0;
    4. public void set(Iterator<String> currentArgument) throws ArgsException {
    5. String parameter = null;
    6. try {
    7. parameter = currentArgument.next();
    8. intValue = Integer.parseInt(parameter);
    9. } catch (NoSuchElementException e) {
    10. throw new ArgsException(MISSING_INTEGER);
    11. } catch (NumberFormatException e) {
    12. throw new ArgsException(INVALID_INTEGER, parameter);
    13. }
    14. }
    15. public static int getValue(ArgumentMarshaler am) {
    16. if (am != null && am instanceof IntegerArgumentMarshaler)
    17. return ((IntegerArgumentMarshaler) am).intValue;
    18. else
    19. return 0;
    20. }
    21. }

    Listing 14-7 ArgsException.java

    1. import static com.objectmentor.utilities.args.ArgsException.ErrorCode.*;
    2. public class ArgsException extends Exception {
    3. private char errorArgumentId = '\0';
    4. private String errorParameter = null;
    5. private ErrorCode errorCode = OK;
    6. public ArgsException() {
    7. }
    8. public ArgsException(String message) {
    9. super(message);
    10. }
    11. public ArgsException(ErrorCode errorCode) {
    12. this.errorCode = errorCode;
    13. }
    14. public ArgsException(ErrorCode errorCode, String errorParameter) {
    15. this.errorCode = errorCode;
    16. this.errorParameter = errorParameter;
    17. }
    18. public ArgsException(ErrorCode errorCode,
    19. char errorArgumentId, String errorParameter) {
    20. this.errorCode = errorCode;
    21. this.errorParameter = errorParameter;
    22. this.errorArgumentId = errorArgumentId;
    23. }
    24. public char getErrorArgumentId() {
    25. return errorArgumentId;
    26. }
    27. public void setErrorArgumentId(char errorArgumentId) {
    28. this.errorArgumentId = errorArgumentId;
    29. }
    30. public String getErrorParameter() {
    31. return errorParameter;
    32. }
    33. public void setErrorParameter(String errorParameter) {
    34. this.errorParameter = errorParameter;
    35. }
    36. public ErrorCode getErrorCode() {
    37. return errorCode;
    38. }
    39. public void setErrorCode(ErrorCode errorCode) {
    40. this.errorCode = errorCode;
    41. }
    42. public String errorMessage() {
    43. switch (errorCode) {
    44. case OK:
    45. return "TILT: Should not get here.";
    46. case UNEXPECTED_ARGUMENT:
    47. return String.format("Argument -%c unexpected.", errorArgumentId);
    48. case MISSING_STRING:
    49. return String.format("Could not find string parameter for -%c.",
    50. errorArgumentId);
    51. case INVALID_INTEGER:
    52. return String.format("Argument -%c expects an integer but was '%s'.",
    53. errorArgumentId, errorParameter);
    54. case MISSING_INTEGER:
    55. return String.format("Could not find integer parameter for -%c.",
    56. errorArgumentId);
    57. case INVALID_DOUBLE:
    58. return String.format("Argument -%c expects a double but was '%s'.",
    59. errorArgumentId, errorParameter);
    60. case MISSING_DOUBLE:
    61. return String.format("Could not find double parameter for -%c.",
    62. errorArgumentId);
    63. case INVALID_ARGUMENT_NAME:
    64. return String.format("'%c' is not a valid argument name.",
    65. errorArgumentId);
    66. case INVALID_ARGUMENT_FORMAT:
    67. return String.format("'%s' is not a valid argument format.",
    68. errorParameter);
    69. }
    70. return "";
    71. }
    72. public enum ErrorCode {
    73. OK, INVALID_ARGUMENT_FORMAT, UNEXPECTED_ARGUMENT, INVALID_ARGUMENT_NAME,
    74. MISSING_STRING,
    75. MISSING_INTEGER, INVALID_INTEGER,
    76. MISSING_DOUBLE, INVALID_DOUBLE
    77. }
    78. }

    It’s remarkable how much code is required to flesh out the details of this simple concept. One of the reasons for this is that we are using a particularly wordy language. Java, being a statically typed language, requires a lot of words in order to satisfy the type system. In a language like Ruby, Python, or Smalltalk, this program is much smaller.1

    Please read the code over one more time. Pay special attention to the way things are named, the size of the functions, and the formatting of the code. If you are an experienced programmer, you may have some quibbles here and there with various parts of the style or structure. Overall, however, I hope you conclude that this program is nicely written and has a clean structure.

    For example, it should be obvious how you would add a new argument type, such as a date argument or a complex number argument, and that such an addition would require a trivial amount of effort. In short, it would simply require a new derivative of Argument-Marshaler, a new getXXX function, and a new case statement in the parseSchemaElement function. There would also probably be a new ArgsException.ErrorCode and a new error message.

    How Did I Do This? Let me set your mind at rest. I did not simply write this program from beginning to end in its current form. More importantly, I am not expecting you to be able to write clean and elegant programs in one pass. If we have learned anything over the last couple of decades, it is that programming is a craft more than it is a science. To write clean code, you must first write dirty code and then clean it.

    This should not be a surprise to you. We learned this truth in grade school when our teachers tried (usually in vain) to get us to write rough drafts of our compositions. The process, they told us, was that we should write a rough draft, then a second draft, then several subsequent drafts until we had our final version. Writing clean compositions, they tried to tell us, is a matter of successive refinement.

    Most freshman programmers (like most grade-schoolers) don’t follow this advice particularly well. They believe that the primary goal is to get the program working. Once it’s “working,” they move on to the next task, leaving the “working” program in whatever state they finally got it to “work.” Most seasoned programmers know that this is professional suicide.

    ARGS: THE ROUGH DRAFT Listing 14-8 shows an earlier version of the Args class. It “works.” And it’s messy.

    Listing 14-8 Args.java (first draft)

    1. import java.text.ParseException;
    2. import java.util.*;
    3. public class Args {
    4. private String schema;
    5. private String[] args;
    6. private boolean valid = true;
    7. private Set<Character> unexpectedArguments = new TreeSet<Character>();
    8. private Map<Character, Boolean> booleanArgs =
    9. new HashMap
    10. <Character, Boolean>();
    11. private Map<Character, String> stringArgs = new HashMap
    12. <Character, String>();
    13. private Map<Character, Integer> intArgs = new HashMap<Character, Integer>();
    14. private Set<Character> argsFound = new HashSet<Character>();
    15. private int currentArgument;
    16. private char errorArgumentId = '\0';
    17. private String errorParameter = "TILT";
    18. private ErrorCode errorCode = ErrorCode.OK;
    19. private enum ErrorCode {
    20. OK, MISSING_STRING, MISSING_INTEGER, INVALID_INTEGER, UNEXPECTED_ARGUMENT
    21. }
    22. public Args(String schema, String[] args) throws ParseException {
    23. this.schema = schema;
    24. this.args = args;
    25. valid = parse();
    26. }
    27. private boolean parse() throws ParseException {
    28. if (schema.length() == 0 && args.length == 0)
    29. return true;
    30. parseSchema();
    31. try {
    32. parseArguments();
    33. } catch (ArgsException e) {
    34. }
    35. return valid;
    36. }
    37. private boolean parseSchema() throws ParseException {
    38. for (String element : schema.split(",")) {
    39. if (element.length() > 0) {
    40. String trimmedElement = element.trim();
    41. parseSchemaElement(trimmedElement);
    42. }
    43. }
    44. return true;
    45. }
    46. private void parseSchemaElement(String element) throws ParseException {
    47. char elementId = element.charAt(0);
    48. String elementTail = element.substring(1);
    49. validateSchemaElementId(elementId);
    50. if (isBooleanSchemaElement(elementTail))
    51. parseBooleanSchemaElement(elementId);
    52. else if (isStringSchemaElement(elementTail))
    53. parseStringSchemaElement(elementId);
    54. else if (isIntegerSchemaElement(elementTail)) {
    55. parseIntegerSchemaElement(elementId);
    56. } else {
    57. throw new ParseException(
    58. String.format("Argument: %c has invalid format: %s.",
    59. elementId, elementTail), 0);
    60. }
    61. }
    62. private void validateSchemaElementId(char elementId) throws ParseException {
    63. if (!Character.isLetter(elementId)) {
    64. throw new ParseException(
    65. "Bad character:" + elementId + "in Args format: " + schema, 0);
    66. }
    67. }
    68. private void parseBooleanSchemaElement(char elementId) {
    69. booleanArgs.put(elementId, false);
    70. }
    71. private void parseIntegerSchemaElement(char elementId) {
    72. intArgs.put(elementId, 0);
    73. }
    74. private void parseStringSchemaElement(char elementId) {
    75. stringArgs.put(elementId, "");
    76. }
    77. private boolean isStringSchemaElement(String elementTail) {
    78. return elementTail.equals("*");
    79. }
    80. private boolean isBooleanSchemaElement(String elementTail) {
    81. return elementTail.length() == 0;
    82. }
    83. private boolean isIntegerSchemaElement(String elementTail) {
    84. return elementTail.equals("#");
    85. }
    86. private boolean parseArguments() throws ArgsException {
    87. for (currentArgument = 0; currentArgument < args.length; currentArgument++) {
    88. String arg = args[currentArgument];
    89. parseArgument(arg);
    90. }
    91. return true;
    92. }
    93. private void parseArgument(String arg) throws ArgsException {
    94. if (arg.startsWith("-"))
    95. parseElements(arg);
    96. }
    97. private void parseElements(String arg) throws ArgsException {
    98. for (int i = 1; i < arg.length(); i++)
    99. parseElement(arg.charAt(i));
    100. }
    101. private void parseElement(char argChar) throws ArgsException {
    102. if (setArgument(argChar))
    103. argsFound.add(argChar);
    104. else {
    105. unexpectedArguments.add(argChar);
    106. errorCode = ErrorCode.UNEXPECTED_ARGUMENT;
    107. valid = false;
    108. }
    109. }
    110. private boolean setArgument(char argChar) throws ArgsException {
    111. if (isBooleanArg(argChar))
    112. setBooleanArg(argChar, true);
    113. else if (isStringArg(argChar))
    114. setStringArg(argChar);
    115. else if (isIntArg(argChar))
    116. setIntArg(argChar);
    117. else
    118. return false;
    119. return true;
    120. }
    121. private boolean isIntArg(char argChar) {
    122. return intArgs.containsKey(argChar);
    123. }
    124. private void setIntArg(char argChar) throws ArgsException {
    125. currentArgument++;
    126. String parameter = null;
    127. try {
    128. parameter = args[currentArgument];
    129. intArgs.put(argChar, new Integer(parameter));
    130. } catch (ArrayIndexOutOfBoundsException e) {
    131. valid = false;
    132. errorArgumentId = argChar;
    133. errorCode = ErrorCode.MISSING_INTEGER;
    134. throw new ArgsException();
    135. } catch (NumberFormatException e) {
    136. valid = false;
    137. errorArgumentId = argChar;
    138. errorParameter = parameter;
    139. errorCode = ErrorCode.INVALID_INTEGER;
    140. throw new ArgsException();
    141. }
    142. }
    143. private void setStringArg(char argChar) throws ArgsException {
    144. currentArgument++;
    145. try {
    146. stringArgs.put(argChar, args[currentArgument]);
    147. } catch (ArrayIndexOutOfBoundsException e) {
    148. valid = false;
    149. errorArgumentId = argChar;
    150. errorCode = ErrorCode.MISSING_STRING;
    151. throw new ArgsException();
    152. }
    153. }
    154. private boolean isStringArg(char argChar) {
    155. return stringArgs.containsKey(argChar);
    156. }
    157. private void setBooleanArg(char argChar, boolean value) {
    158. booleanArgs.put(argChar, value);
    159. }
    160. private boolean isBooleanArg(char argChar) {
    161. return booleanArgs.containsKey(argChar);
    162. }
    163. public int cardinality() {
    164. return argsFound.size();
    165. }
    166. public String usage() {
    167. if (schema.length() > 0)
    168. return "-[" + schema + "]";
    169. else
    170. return "";
    171. }
    172. public String errorMessage() throws Exception {
    173. switch (errorCode) {
    174. case OK:
    175. throw new Exception("TILT: Should not get here.");
    176. case UNEXPECTED_ARGUMENT:
    177. return unexpectedArgumentMessage();
    178. case MISSING_STRING:
    179. return String.format("Could not find string parameter for -%c.",
    180. errorArgumentId);
    181. case INVALID_INTEGER:
    182. return String.format("Argument -%c expects an integer but was '%s'.",
    183. errorArgumentId, errorParameter);
    184. case MISSING_INTEGER:
    185. return String.format("Could not find integer parameter for -%c.",
    186. errorArgumentId);
    187. }
    188. return "";
    189. }
    190. private String unexpectedArgumentMessage() {
    191. StringBuffer message = new StringBuffer("Argument(s) -");
    192. for (char c : unexpectedArguments) {
    193. message.append(c);
    194. }
    195. message.append(" unexpected.");
    196. return message.toString();
    197. }
    198. private boolean falseIfNull(Boolean b) {
    199. return b != null && b;
    200. }
    201. private int zeroIfNull(Integer i) {
    202. return i == null ? 0 : i;
    203. }
    204. private String blankIfNull(String s) {
    205. return s == null ? "" : s;
    206. }
    207. public String getString(char arg) {
    208. return blankIfNull(stringArgs.get(arg));
    209. }
    210. public int getInt(char arg) {
    211. return zeroIfNull(intArgs.get(arg));
    212. }
    213. public boolean getBoolean(char arg) {
    214. return falseIfNull(booleanArgs.get(arg));
    215. }
    216. public boolean has(char arg) {
    217. return argsFound.contains(arg);
    218. }
    219. public boolean isValid() {
    220. return valid;
    221. }
    222. private class ArgsException extends Exception {
    223. }
    224. }

    I hope your initial reaction to this mass of code is “I’m certainly glad he didn’t leave it like that!” If you feel like this, then remember that’s how other people are going to feel about code that you leave in rough-draft form.

    Actually “rough draft” is probably the kindest thing you can say about this code. It’s clearly a work in progress. The sheer number of instance variables is daunting. The odd strings like “TILT,” the HashSets and TreeSets, and the try-catch-catch blocks all add up to a festering pile.

    I had not wanted to write a festering pile. Indeed, I was trying to keep things reasonably well organized. You can probably tell that from my choice of function and variable names and the fact that there is a crude structure to the program. But, clearly, I had let the problem get away from me.

    The mess built gradually. Earlier versions had not been nearly so nasty. For example, Listing 14-9 shows an earlier version in which only Boolean arguments were working.

    Listing 14-9 Args.java (Boolean only)

    1. package com.objectmentor.utilities.getopts;
    2. import java.util.*;
    3. public class Args {
    4. private String schema;
    5. private String[] args;
    6. private boolean valid;
    7. private Set<Character> unexpectedArguments = new TreeSet<Character>();
    8. private Map<Character, Boolean> booleanArgs =
    9. new HashMap<Character, Boolean>();
    10. private int numberOfArguments = 0;
    11. public Args(String schema, String[] args) {
    12. this.schema = schema;
    13. this.args = args;
    14. valid = parse();
    15. }
    16. public boolean isValid() {
    17. return valid;
    18. }
    19. private boolean parse() {
    20. if (schema.length() == 0 && args.length == 0)
    21. return true;
    22. parseSchema();
    23. parseArguments();
    24. return unexpectedArguments.size() == 0;
    25. }
    26. private boolean parseSchema() {
    27. for (String element : schema.split(",")) {
    28. parseSchemaElement(element);
    29. }
    30. return true;
    31. }
    32. private void parseSchemaElement(String element) {
    33. if (element.length() == 1) {
    34. parseBooleanSchemaElement(element);
    35. }
    36. }
    37. private void parseBooleanSchemaElement(String element) {
    38. char c = element.charAt(0);
    39. if (Character.isLetter(c)) {
    40. booleanArgs.put(c, false);
    41. }
    42. }
    43. private boolean parseArguments() {
    44. for (String arg : args)
    45. parseArgument(arg);
    46. return true;
    47. }
    48. private void parseArgument(String arg) {
    49. if (arg.startsWith("-"))
    50. parseElements(arg);
    51. }
    52. private void parseElements(String arg) {
    53. for (int i = 1; i < arg.length(); i++)
    54. parseElement(arg.charAt(i));
    55. }
    56. private void parseElement(char argChar) {
    57. if (isBoolean(argChar)) {
    58. numberOfArguments++;
    59. setBooleanArg(argChar, true);
    60. } else
    61. unexpectedArguments.add(argChar);
    62. }
    63. private void setBooleanArg(char argChar, boolean value) {
    64. booleanArgs.put(argChar, value);
    65. }
    66. private boolean isBoolean(char argChar) {
    67. return booleanArgs.containsKey(argChar);
    68. }
    69. public int cardinality() {
    70. return numberOfArguments;
    71. }
    72. public String usage() {
    73. if (schema.length() > 0)
    74. return "-[" + schema + "]";
    75. else
    76. return "";
    77. }
    78. public String errorMessage() {
    79. if (unexpectedArguments.size() > 0) {
    80. return unexpectedArgumentMessage();
    81. } else
    82. return "";
    83. }
    84. private String unexpectedArgumentMessage() {
    85. StringBuffer message = new StringBuffer("Argument(s) -");
    86. for (char c : unexpectedArguments) {
    87. message.append(c);
    88. }
    89. message.append(" unexpected.");
    90. return message.toString();
    91. }
    92. public boolean getBoolean(char arg) {
    93. return booleanArgs.get(arg);
    94. }
    95. }

    Although you can find plenty to complain about in this code, it’s really not that bad. It’s compact and simple and easy to understand. However, within this code it is easy to see the seeds of the later festering pile. It’s quite clear how this grew into the latter mess.

    Notice that the latter mess has only two more argument types than this: String and integer. The addition of just two more argument types had a massively negative impact on the code. It converted it from something that would have been reasonably maintainable into something that I would expect to become riddled with bugs and warts.

    I added the two argument types incrementally. First, I added the String argument, which yielded this:

    Listing 14-10 Args.java (Boolean and String)

    1. package com.objectmentor.utilities.getopts;
    2. import java.text.ParseException;
    3. import java.util.*;
    4. public class Args {
    5. private String schema;
    6. private String[] args;
    7. private boolean valid = true;
    8. private Set<Character> unexpectedArguments = new TreeSet<Character>();
    9. private Map<Character, Boolean> booleanArgs =
    10. new HashMap<Character, Boolean>();
    11. private Map<Character, String> stringArgs =
    12. new HashMap<Character, String>();
    13. private Set<Character> argsFound = new HashSet<Character>();
    14. private int currentArgument;
    15. private char errorArgument = '\0';
    16. enum ErrorCode {
    17. OK, MISSING_STRING
    18. }
    19. private ErrorCode errorCode = ErrorCode.OK;
    20. public Args(String schema, String[] args) throws ParseException {
    21. this.schema = schema;
    22. this.args = args;
    23. valid = parse();
    24. }
    25. private boolean parse() throws ParseException {
    26. if (schema.length() == 0 && args.length == 0)
    27. return true;
    28. parseSchema();
    29. parseArguments();
    30. return valid;
    31. }
    32. private boolean parseSchema() throws ParseException {
    33. for (String element : schema.split(",")) {
    34. if (element.length() > 0) {
    35. String trimmedElement = element.trim();
    36. parseSchemaElement(trimmedElement);
    37. }
    38. }
    39. return true;
    40. }
    41. private void parseSchemaElement(String element) throws ParseException {
    42. char elementId = element.charAt(0);
    43. String elementTail = element.substring(1);
    44. validateSchemaElementId(elementId);
    45. if (isBooleanSchemaElement(elementTail))
    46. parseBooleanSchemaElement(elementId);
    47. else if (isStringSchemaElement(elementTail))
    48. parseStringSchemaElement(elementId);
    49. }
    50. private void validateSchemaElementId(char elementId) throws ParseException {
    51. if (!Character.isLetter(elementId)) {
    52. throw new ParseException(
    53. "Bad character:" + elementId + "in Args format: " + schema, 0);
    54. }
    55. }
    56. private void parseStringSchemaElement(char elementId) {
    57. stringArgs.put(elementId, " ");
    58. }
    59. private boolean isStringSchemaElement(String elementTail) {
    60. return elementTail.equals("*");
    61. }
    62. private boolean isBooleanSchemaElement(String elementTail) {
    63. return elementTail.length() == 0;
    64. }
    65. private void parseBooleanSchemaElement(char elementId) {
    66. booleanArgs.put(elementId, false);
    67. }
    68. private boolean parseArguments() {
    69. for (currentArgument = 0; currentArgument < args.length; currentArgument++) {
    70. String arg = args[currentArgument];
    71. parseArgument(arg);
    72. }
    73. return true;
    74. }
    75. private void parseArgument(String arg) {
    76. if (arg.startsWith("-"))
    77. parseElements(arg);
    78. }
    79. private void parseElements(String arg) {
    80. for (int i = 1; i < arg.length(); i++)
    81. parseElement(arg.charAt(i));
    82. }
    83. private void parseElement(char argChar) {
    84. if (setArgument(argChar))
    85. argsFound.add(argChar);
    86. else {
    87. unexpectedArguments.add(argChar);
    88. valid = false;
    89. }
    90. }
    91. private boolean setArgument(char argChar) {
    92. boolean set = true;
    93. if (isBoolean(argChar))
    94. setBooleanArg(argChar, true);
    95. else if (isString(argChar))
    96. setStringArg(argChar, " ");
    97. else
    98. set = false;
    99. return set;
    100. }
    101. private void setStringArg(char argChar, String s) {
    102. currentArgument++;
    103. try {
    104. stringArgs.put(argChar, args[currentArgument]);
    105. } catch (ArrayIndexOutOfBoundsException e) {
    106. valid = false;
    107. errorArgument = argChar;
    108. errorCode = ErrorCode.MISSING_STRING;
    109. }
    110. }
    111. private boolean isString(char argChar) {
    112. return stringArgs.containsKey(argChar);
    113. }
    114. private void setBooleanArg(char argChar, boolean value) {
    115. booleanArgs.put(argChar, value);
    116. }
    117. private boolean isBoolean(char argChar) {
    118. return booleanArgs.containsKey(argChar);
    119. }
    120. public int cardinality() {
    121. return argsFound.size();
    122. }
    123. public String usage() {
    124. if (schema.length() > 0)
    125. return "-[" + schema + "]";
    126. else
    127. return " ";
    128. }
    129. public String errorMessage() throws Exception {
    130. if (unexpectedArguments.size() > 0) {
    131. return unexpectedArgumentMessage();
    132. } else
    133. switch (errorCode) {
    134. case MISSING_STRING:
    135. return String.format("Could not find string parameter for -%c.", errorArgument);
    136. case OK:
    137. throw new Exception("TILT: Should not get here.");
    138. }
    139. return " ";
    140. }
    141. private String unexpectedArgumentMessage() {
    142. StringBuffer message = new StringBuffer("Argument(s) -");
    143. for (char c : unexpectedArguments) {
    144. message.append(c);
    145. }
    146. message.append(" unexpected.");
    147. return message.toString();
    148. }
    149. public boolean getBoolean(char arg) {
    150. return falseIfNull(booleanArgs.get(arg));
    151. }
    152. private boolean falseIfNull(Boolean b) {
    153. return b == null ? false : b;
    154. }
    155. public String getString(char arg) {
    156. return blankIfNull(stringArgs.get(arg));
    157. }
    158. private String blankIfNull(String s) {
    159. return s == null ? " " : s;
    160. }
    161. public boolean has(char arg) {
    162. return argsFound.contains(arg);
    163. }
    164. public boolean isValid() {
    165. return valid;
    166. }
    167. }

    You can see that this is starting to get out of hand. It’s still not horrible, but the mess is certainly starting to grow. It’s a pile, but it’s not festering quite yet. It took the addition of the integer argument type to get this pile really fermenting and festering.

    So I Stopped I had at least two more argument types to add, and I could tell that they would make things much worse. If I bulldozed my way forward, I could probably get them to work, but I’d leave behind a mess that was too large to fix. If the structure of this code was ever going to be maintainable, now was the time to fix it.

    So I stopped adding features and started refactoring. Having just added the String and integer arguments, I knew that each argument type required new code in three major places. First, each argument type required some way to parse its schema element in order to select the HashMap for that type. Next, each argument type needed to be parsed in the command-line strings and converted to its true type. Finally, each argument type needed a getXXX method so that it could be returned to the caller as its true type.

    Many different types, all with similar methods—that sounds like a class to me. And so the ArgumentMarshaler concept was born.

    ARGS: THE ROUGH DRAFT To avoid this, I use the discipline of Test-Driven Development (TDD). One of the central doctrines of this approach is to keep the system running at all times. In other words, using TDD, I am not allowed to make a change to the system that breaks that system. Every change I make must keep the system working as it worked before.

    To achieve this, I need a suite of automated tests that I can run on a whim and that verifies that the behavior of the system is unchanged. For the Args class I had created a suite of unit and acceptance tests while I was building the festering pile. The unit tests were written in Java and administered by JUnit. The acceptance tests were written as wiki pages in FitNesse. I could run these tests any time I wanted, and if they passed, I was confident that the system was working as I specified.

    So I proceeded to make a large number of very tiny changes. Each change moved the structure of the system toward the ArgumentMarshaler concept. And yet each change kept the system working. The first change I made was to add the skeleton of the ArgumentMarshaller to the end of the festering pile (Listing 14-11).

    Listing 14-11 ArgumentMarshaller appended to Args.java

    1. private class ArgumentMarshaler {
    2. private boolean booleanValue = false;
    3. public void setBoolean(boolean value) {
    4. booleanValue = value;
    5. }
    6. public boolean getBoolean() {
    7. return booleanValue;
    8. }
    9. }
    10. private class BooleanArgumentMarshaler extends ArgumentMarshaler {
    11. }
    12. private class StringArgumentMarshaler extends ArgumentMarshaler {
    13. }
    14. private class IntegerArgumentMarshaler extends ArgumentMarshaler {
    15. }

    Clearly, this wasn’t going to break anything. So then I made the simplest modification I could, one that would break as little as possible. I changed the HashMap for the Boolean arguments to take an ArgumentMarshaler.

    1. private Map<Character, ArgumentMarshaler> booleanArgs = new HashMap<Character, ArgumentMarshaler>();

    This broke a few statements, which I quickly fixed.

    1. private void parseBooleanSchemaElement(char elementId) {
    2. booleanArgs.put(elementId, new BooleanArgumentMarshaler());
    3. }
    4. ..
    5. private void setBooleanArg(char argChar, boolean value) {
    6. booleanArgs.get(argChar).setBoolean(value);
    7. }
    8. public boolean getBoolean(char arg) {
    9. return falseIfNull(booleanArgs.get(arg).getBoolean());
    10. }

    Notice how these changes are in exactly the areas that I mentioned before: the parse, set, and get for the argument type. Unfortunately, small as this change was, some of the tests started failing. If you look carefully at getBoolean, you’ll see that if you call it with ‘y,’ but there is no y argument, then booleanArgs.get(‘y’) will return null, and the function will throw a NullPointerException. The falseIfNull function had been used to protect against this, but the change I made caused that function to become irrelevant.

    Incrementalism demanded that I get this working quickly before making any other changes. Indeed, the fix was not too difficult. I just had to move the check for null. It was no longer the boolean being null that I needed to check; it was the ArgumentMarshaller.

    First, I removed the falseIfNull call in the getBoolean function. It was useless now, so I also eliminated the function itself. The tests still failed in the same way, so I was confident that I hadn’t introduced any new errors.

    1. public boolean getBoolean(char arg) {
    2. return booleanArgs.get(arg).getBoolean();
    3. }

    Next, I split the function into two lines and put the ArgumentMarshaller into its own variable named argumentMarshaller. I didn’t care for the long variable name; it was badly redundant and cluttered up the function. So I shortened it to am [N5].

    1. public boolean getBoolean(char arg) {
    2. Args.ArgumentMarshaler am = booleanArgs.get(arg);

    And then I put in the null detection logic.

    1. public boolean getBoolean(char arg) {
    2. Args.ArgumentMarshaler am = booleanArgs.get(arg);
    3. return am != null && am.getBoolean();
    4. }

    STRING ARGUMENTS Addin_g String arguments was very similar to adding boolean arguments. I had to change the HashMap and get the parse, set, and get functions working. There shouldn’t be any surprises in what follows except, perhaps, that I seem to be putting all the marshalling implementation in the ArgumentMarshaller base class instead of distributing it to the derivatives.

    1. private Map<Character, ArgumentMarshaler> stringArgs =
    2. new HashMap<Character, ArgumentMarshaler>();
    3. private void parseStringSchemaElement(char elementId) {
    4. stringArgs.put(elementId, new StringArgumentMarshaler());
    5. }
    6. private void setStringArg(char argChar) throws ArgsException {
    7. currentArgument++;
    8. try {
    9. stringArgs.get(argChar).setString(args[currentArgument]);
    10. } catch (ArrayIndexOutOfBoundsException e) {
    11. valid = false;
    12. errorArgumentId = argChar;
    13. errorCode = ErrorCode.MISSING_STRING;
    14. throw new ArgsException();
    15. }
    16. }
    17. public String getString(char arg) {
    18. Args.ArgumentMarshaler am = stringArgs.get(arg);
    19. return am == null ? : am.getString();
    20. }
    21. private class ArgumentMarshaler {
    22. private boolean booleanValue = false;
    23. private String stringValue;
    24. public void setBoolean(boolean value) {
    25. booleanValue = value;
    26. }
    27. public boolean getBoolean() {
    28. return booleanValue;
    29. }
    30. public void setString(String s) {
    31. stringValue = s;
    32. }
    33. public String getString() {
    34. return stringValue == null ? : stringValue;
    35. }
    36. }

    Again, these changes were made one at a time and in such a way that the tests kept running, if not passing. When a test broke, I made sure to get it passing again before continuing with the next change.

    By now you should be able to see my intent. Once I get all the current marshalling behavior into the ArgumentMarshaler base class, I’m going to start pushing that behavior down into the derivatives. This will allow me to keep everything running while I gradually change the shape of this program.

    The obvious next step was to move the int argument functionality into the ArgumentMarshaler. Again, there weren’t any surprises.

    1. private Map<Character, ArgumentMarshaler> intArgs =
    2. new HashMap<Character, ArgumentMarshaler>();
    3. private void parseIntegerSchemaElement(char elementId) {
    4. intArgs.put(elementId, new IntegerArgumentMarshaler());
    5. }
    6. private void setIntArg(char argChar) throws ArgsException {
    7. currentArgument++;
    8. String parameter = null;
    9. try {
    10. parameter = args[currentArgument];
    11. intArgs.get(argChar).setInteger(Integer.parseInt(parameter));
    12. } catch (ArrayIndexOutOfBoundsException e) {
    13. valid = false;
    14. errorArgumentId = argChar;
    15. errorCode = ErrorCode.MISSING_INTEGER;
    16. throw new ArgsException();
    17. } catch (NumberFormatException e) {
    18. valid = false;
    19. errorArgumentId = argChar;
    20. errorParameter = parameter;
    21. errorCode = ErrorCode.INVALID_INTEGER;
    22. throw new ArgsException();
    23. }
    24. }
    25. public int getInt(char arg) {
    26. Args.ArgumentMarshaler am = intArgs.get(arg);
    27. return am == null ? 0 : am.getInteger();
    28. }
    29. private class ArgumentMarshaler {
    30. private boolean booleanValue = false;
    31. private String stringValue;
    32. private int integerValue;
    33. public void setBoolean(boolean value) {
    34. booleanValue = value;
    35. }
    36. public boolean getBoolean() {
    37. return booleanValue;
    38. }
    39. public void setString(String s) {
    40. stringValue = s;
    41. }
    42. public String getString() {
    43. return stringValue == null ? ”: stringValue;
    44. }
    45. public void setInteger(int i) {
    46. integerValue = i;
    47. }
    48. public int getInteger() {
    49. return integerValue;
    50. }
    51. }

    With all the marshalling moved to the ArgumentMarshaler, I started pushing functionality into the derivatives. The first step was to move the setBoolean function into the BooleanArgumentMarshaller and make sure it got called correctly. So I created an abstract set method.

    1. private abstract class ArgumentMarshaler {
    2. protected boolean booleanValue = false;
    3. private String stringValue;
    4. private int integerValue;
    5. public void setBoolean(boolean value) {
    6. booleanValue = value;
    7. }
    8. public boolean getBoolean() {
    9. return booleanValue;
    10. }
    11. public void setString(String s) {
    12. stringValue = s;
    13. }
    14. public String getString() {
    15. return stringValue == null ? " " : stringValue;
    16. }
    17. public void setInteger(int i) {
    18. integerValue = i;
    19. }
    20. public int getInteger() {
    21. return integerValue;
    22. }
    23. public abstract void set(String s);
    24. }

    Then I implemented the set method in BooleanArgumentMarshaller.

    1. private class BooleanArgumentMarshaler extends ArgumentMarshaler {
    2. public void set(String s) {
    3. booleanValue = true;
    4. }
    5. }

    And finally I replaced the call to setBoolean with a call to set.

    1. private void setBooleanArg(char argChar, boolean value) {
    2. booleanArgs.get(argChar) .set(“true”);
    3. }

    The tests all still passed. Because this change caused set to be deployed to the Boolean-ArgumentMarshaler, I removed the setBoolean method from the ArgumentMarshaler base class.

    Notice that the abstract set function takes a String argument, but the implementation in the BooleanArgumentMarshaller does not use it. I put that argument in there because I knew that the StringArgumentMarshaller and IntegerArgumentMarshaller would use it.

    Next, I wanted to deploy the get method into BooleanArgumentMarshaler. Deploying get functions is always ugly because the return type has to be Object, and in this case needs to be cast to a Boolean.

    Just to get this to compile, I added the get function to the ArgumentMarshaler.

    1. private abstract class ArgumentMarshaler {
    2. public Object get() {
    3. return null;
    4. }
    5. }

    This compiled and obviously failed the tests. Getting the tests working again was simply a matter of making get abstract and implementing it in BooleanAgumentMarshaler.

    1. private abstract class ArgumentMarshaler {
    2. protected boolean booleanValue = false;
    3. public abstract Object get();
    4. }
    5. private class BooleanArgumentMarshaler extends ArgumentMarshaler {
    6. public void set(String s) {
    7. booleanValue = true;
    8. }
    9. public Object get() {
    10. return booleanValue;
    11. }
    12. }

    Once again the tests passed. So both get and set deploy to the BooleanArgumentMarshaler! This allowed me to remove the old getBoolean function from ArgumentMarshaler, move the protected booleanValue variable down to BooleanArgumentMarshaler, and make it private.

    I did the same pattern of changes for Strings. I deployed both set and get, deleted the unused functions, and moved the variables.

    1. private void setStringArg(char argChar) throws ArgsException {
    2. currentArgument++;
    3. try {
    4. stringArgs.get(argChar).set(args[currentArgument]);
    5. } catch (ArrayIndexOutOfBoundsException e) {
    6. valid = false;
    7. errorArgumentId = argChar;
    8. errorCode = ErrorCode.MISSING_STRING;
    9. throw new ArgsException();
    10. }
    11. }
    12. public String getString(char arg) {
    13. Args.ArgumentMarshaler am = stringArgs.get(arg);
    14. return am == null ? " " : (String) am.get();
    15. }
    16. private abstract class ArgumentMarshaler {
    17. private int integerValue;
    18. public void setInteger(int i) {
    19. integerValue = i;
    20. }
    21. public int getInteger() {
    22. return integerValue;
    23. }
    24. public abstract void set(String s);
    25. public abstract Object get();
    26. }
    27. private class BooleanArgumentMarshaler extends ArgumentMarshaler {
    28. private boolean booleanValue = false;
    29. public void set(String s) {
    30. booleanValue = true;
    31. }
    32. public Object get() {
    33. return booleanValue;
    34. }
    35. }
    36. private class StringArgumentMarshaler extends ArgumentMarshaler {
    37. private String stringValue = " ";
    38. public void set(String s) {
    39. stringValue = s;
    40. }
    41. public Object get() {
    42. return stringValue;
    43. }
    44. }
    45. private class IntegerArgumentMarshaler extends ArgumentMarshaler {
    46. public void set(String s) {
    47. }
    48. public Object get() {
    49. return null;
    50. }
    51. }

    Finally, I repeated the process for integers. This was just a little more complicated because integers needed to be parsed, and the parse operation can throw an exception. But the result is better because the whole concept of NumberFormatException got buried in the IntegerArgumentMarshaler.

    1. private boolean isIntArg(char argChar) {return intArgs.containsKey(argChar);}
    2. private void setIntArg(char argChar) throws ArgsException {
    3. currentArgument++;
    4. String parameter = null;
    5. try {
    6. parameter = args[currentArgument];
    7. intArgs.get(argChar).set(parameter);
    8. } catch (ArrayIndexOutOfBoundsException e) {
    9. valid = false;
    10. errorArgumentId = argChar;
    11. errorCode = ErrorCode.MISSING_INTEGER;
    12. throw new ArgsException();
    13. } catch (ArgsException e) {
    14. valid = false;
    15. errorArgumentId = argChar;
    16. errorParameter = parameter;
    17. errorCode = ErrorCode.INVALID_INTEGER;
    18. throw e;
    19. }
    20. }
    21. private void setBooleanArg(char argChar) {
    22. try {
    23. booleanArgs.get(argChar).set(“true”);
    24. } catch (ArgsException e) {
    25. }
    26. }
    27. public int getInt(char arg) {
    28. Args.ArgumentMarshaler am = intArgs.get(arg);
    29. return am == null ? 0 : (Integer) am.get();
    30. }
    31. private abstract class ArgumentMarshaler {
    32. public abstract void set(String s) throws ArgsException;
    33. public abstract Object get();
    34. }
    35. private class IntegerArgumentMarshaler extends ArgumentMarshaler {
    36. private int intValue = 0;
    37. public void set(String s) throws ArgsException {
    38. try {
    39. intValue = Integer.parseInt(s);
    40. } catch (NumberFormatException e) {
    41. throw new ArgsException();
    42. }
    43. }
    44. public Object get() {
    45. return intValue;
    46. }
    47. }

    Of course, the tests continued to pass. Next, I got rid of the three different maps up at the top of the algorithm. This made the whole system much more generic. However, I couldn’t get rid of them just by deleting them because that would break the system. Instead, I added a new Map for the ArgumentMarshaler and then one by one changed the methods to use it instead of the three original maps.

    1. public class Args {
    2. private Map<Character, ArgumentMarshaler> booleanArgs =
    3. new HashMap<Character, ArgumentMarshaler>();
    4. private Map<Character, ArgumentMarshaler> stringArgs =
    5. new HashMap<Character, ArgumentMarshaler>();
    6. private Map<Character, ArgumentMarshaler> intArgs =
    7. new HashMap<Character, ArgumentMarshaler>();
    8. private Map<Character, ArgumentMarshaler> marshalers =
    9. new HashMap<Character, ArgumentMarshaler>();
    10. private void parseBooleanSchemaElement(char elementId) {
    11. ArgumentMarshaler m = new BooleanArgumentMarshaler();
    12. booleanArgs.put(elementId, m);
    13. marshalers.put(elementId, m);
    14. }
    15. private void parseIntegerSchemaElement(char elementId) {
    16. ArgumentMarshaler m = new IntegerArgumentMarshaler();
    17. intArgs.put(elementId, m);
    18. marshalers.put(elementId, m);
    19. }
    20. private void parseStringSchemaElement(char elementId) {
    21. ArgumentMarshaler m = new StringArgumentMarshaler();
    22. stringArgs.put(elementId, m);
    23. marshalers.put(elementId, m);
    24. }
    25. }

    Of course the tests all still passed. Next, I changed isBooleanArg from this:

    1. private boolean isBooleanArg(char argChar) {
    2. return booleanArgs.containsKey(argChar);
    3. }

    to this:

    1. private boolean isBooleanArg(char argChar) {
    2. ArgumentMarshaler m = marshalers.get(argChar);
    3. return m instanceof BooleanArgumentMarshaler;
    4. }

    The tests still passed. So I made the same change to isIntArg and isStringArg.

    1. private boolean isIntArg(char argChar) {
    2. ArgumentMarshaler m = marshalers.get(argChar);
    3. return m instanceof IntegerArgumentMarshaler;
    4. }
    5. private boolean isStringArg(char argChar) {
    6. ArgumentMarshaler m = marshalers.get(argChar);
    7. return m instanceof StringArgumentMarshaler;
    8. }

    The tests still passed. So I eliminated all the duplicate calls to marshalers.get as follows:

    1. private boolean setArgument(char argChar) throws ArgsException {
    2. ArgumentMarshaler m = marshalers.get(argChar);
    3. if (isBooleanArg(m))
    4. setBooleanArg(argChar);
    5. else if (isStringArg(m))
    6. setStringArg(argChar);
    7. else if (isIntArg(m))
    8. setIntArg(argChar);
    9. else
    10. return false;
    11. return true;
    12. }
    13. private boolean isIntArg(ArgumentMarshaler m) {
    14. return m instanceof IntegerArgumentMarshaler;
    15. }
    16. private boolean isStringArg(ArgumentMarshaler m) {
    17. return m instanceof StringArgumentMarshaler;
    18. }
    19. private boolean isBooleanArg(ArgumentMarshaler m) {
    20. return m instanceof BooleanArgumentMarshaler;
    21. }

    This left no good reason for the three isxxxArg methods. So I inlined them:

    1. private boolean setArgument(char argChar) throws ArgsException {
    2. ArgumentMarshaler m = marshalers.get(argChar);
    3. if (m instanceof BooleanArgumentMarshaler)
    4. setBooleanArg(argChar);
    5. else if (m instanceof StringArgumentMarshaler)
    6. setStringArg(argChar);
    7. else if (m instanceof IntegerArgumentMarshaler)
    8. setIntArg(argChar);
    9. else
    10. return false;
    11. return true;
    12. }

    Next, I started using the marshalers map in the set functions, breaking the use of the other three maps. I started with the booleans.

    1. public class Args {
    2. private boolean setArgument(char argChar) throws ArgsException {
    3. ArgumentMarshaler m = marshalers.get(argChar);
    4. if (m instanceof BooleanArgumentMarshaler)
    5. setBooleanArg(m);
    6. else if (m instanceof StringArgumentMarshaler)
    7. setStringArg(argChar);
    8. else if (m instanceof IntegerArgumentMarshaler)
    9. setIntArg(argChar);
    10. else
    11. return false;
    12. return true;
    13. }
    14. private void setBooleanArg(ArgumentMarshaler m) {
    15. try {
    16. m.set("true"); // was: booleanArgs.get(argChar).set("true");
    17. } catch (ArgsException e) {
    18. }
    19. }
    20. }

    The tests still passed, so I did the same with Strings and Integers. This allowed me to integrate some of the ugly exception management code into the setArgument function.

    1. private boolean setArgument(char argChar) throws ArgsException {
    2. ArgumentMarshaler m = marshalers.get(argChar);
    3. try {
    4. if (m instanceof BooleanArgumentMarshaler)
    5. setBooleanArg(m);
    6. else if (m instanceof StringArgumentMarshaler)
    7. setStringArg(m);
    8. else if (m instanceof IntegerArgumentMarshaler)
    9. setIntArg(m);
    10. else
    11. return false;
    12. } catch (ArgsException e) {
    13. valid = false;
    14. errorArgumentId = argChar;
    15. throw e;
    16. }
    17. return true;
    18. }
    19. private void setIntArg(ArgumentMarshaler m) throws ArgsException {
    20. currentArgument++;
    21. String parameter = null;
    22. try {
    23. parameter = args[currentArgument];
    24. m.set(parameter);
    25. } catch (ArrayIndexOutOfBoundsException e) {
    26. errorCode = ErrorCode.MISSING_INTEGER;
    27. throw new ArgsException();
    28. } catch (ArgsException e) {
    29. errorParameter = parameter;
    30. errorCode = ErrorCode.INVALID_INTEGER;
    31. throw e;
    32. }
    33. }
    34. private void setStringArg(ArgumentMarshaler m) throws ArgsException {
    35. currentArgument++;
    36. try {
    37. m.set(args[currentArgument]);
    38. } catch (ArrayIndexOutOfBoundsException e) {
    39. errorCode = ErrorCode.MISSING_STRING;
    40. throw new ArgsException();
    41. }
    42. }

    I was close to being able to remove the three old maps. First, I needed to change the getBoolean function from this:

    1. public boolean getBoolean(char arg) {
    2. Args.ArgumentMarshaler am = booleanArgs.get(arg);
    3. return am != null && (Boolean) am.get();
    4. }

    to this:

    1. public boolean getBoolean(char arg) {
    2. Args.ArgumentMarshaler am = marshalers.get(arg);
    3. boolean b = false;
    4. try {
    5. b = am != null && (Boolean) am.get();
    6. } catch (ClassCastException e) {
    7. b = false;
    8. }
    9. return b;
    10. }

    This last change might have been a surprise. Why did I suddenly decide to deal with the ClassCastException? The reason is that I have a set of unit tests and a separate set of acceptance tests written in FitNesse. It turns out that the FitNesse tests made sure that if you called getBoolean on a nonboolean argument, you got a false. The unit tests did not. Up to this point I had only been running the unit tests.2

    This last change allowed me to pull out another use of the boolean map:

    1. private void parseBooleanSchemaElement(char elementId) {
    2. ArgumentMarshaler m = new BooleanArgumentMarshaler();
    3. booleanArgs.put(elementId, m);
    4. marshalers.put(elementId, m);
    5. }

    And now we can delete the boolean map.

    1. public class Args {
    2. private Map<Character, ArgumentMarshaler> booleanArgs
    3. = new HashMap<Character, ArgumentMarshaler>();
    4. private Map<Character, ArgumentMarshaler> stringArgs =
    5. new HashMap<Character, ArgumentMarshaler>();
    6. private Map<Character, ArgumentMarshaler> intArgs =
    7. new HashMap<Character, ArgumentMarshaler>();
    8. private Map<Character, ArgumentMarshaler> marshalers =
    9. new HashMap<Character, ArgumentMarshaler>();
    10. }
    1. private void parseBooleanSchemaElement(char elementId) {
    2. marshalers.put(elementId, new BooleanArgumentMarshaler());
    3. }
    4. private void parseIntegerSchemaElement(char elementId) {
    5. marshalers.put(elementId, new IntegerArgumentMarshaler());
    6. }
    7. private void parseStringSchemaElement(char elementId) {
    8. marshalers.put(elementId, new StringArgumentMarshaler());
    9. }
    10. public String getString(char arg) {
    11. Args.ArgumentMarshaler am = marshalers.get(arg);
    12. try {
    13. return am == null ? : (String) am.get();
    14. } catch (ClassCastException e) {
    15. return ”;
    16. }
    17. }
    18. public int getInt(char arg) {
    19. Args.ArgumentMarshaler am = marshalers.get(arg);
    20. try {
    21. return am == null ? 0 : (Integer) am.get();
    22. } catch (Exception e) {
    23. return 0;
    24. }
    25. }
    26. public class Args {
    27. private Map<Character, ArgumentMarshaler> stringArgs =
    28. new HashMap<Character, ArgumentMarshaler>();
    29. private Map<Character, ArgumentMarshaler> intArgs =
    30. new HashMap<Character, ArgumentMarshaler>();
    31. private Map<Character, ArgumentMarshaler> marshalers =
    32. new HashMap<Character, ArgumentMarshaler>();

    Next, I inlined the three parse methods because they didn’t do much anymore:

    1. private void parseSchemaElement(String element) throws ParseException {
    2. char elementId = element.charAt(0);
    3. String elementTail = element.substring(1);
    4. validateSchemaElementId(elementId);
    5. if (isBooleanSchemaElement(elementTail))
    6. marshalers.put(elementId, new BooleanArgumentMarshaler());
    7. else if (isStringSchemaElement(elementTail))
    8. marshalers.put(elementId, new StringArgumentMarshaler());
    9. else if (isIntegerSchemaElement(elementTail)) {
    10. marshalers.put(elementId, new IntegerArgumentMarshaler());
    11. } else {
    12. throw new ParseException(String.format(
    13. "Argument: %c has invalid format: %s.", elementId, elementTail), 0);
    14. }
    15. }

    Okay, so now let’s look at the whole picture again. Listing 14-12 shows the current form of the Args class.

    Listing 14-12 Args.java (After first refactoring)

    1. package com.objectmentor.utilities.getopts;
    2. import java.text.ParseException;
    3. import java.util.*;
    4. public class Args {
    5. private String schema;
    6. private String[] args;
    7. private boolean valid = true;
    8. private Set<Character> unexpectedArguments = new TreeSet<Character>();
    9. private Map<Character, ArgumentMarshaler> marshalers =
    10. new HashMap<Character, ArgumentMarshaler>();
    11. private Set<Character> argsFound = new HashSet<Character>();
    12. private int currentArgument;
    13. private char errorArgumentId = '\0';
    14. private String errorParameter = "TILT";
    15. private ErrorCode errorCode = ErrorCode.OK;
    16. private enum ErrorCode {
    17. OK, MISSING_STRING, MISSING_INTEGER, INVALID_INTEGER,
    18. UNEXPECTED_ARGUMENT
    19. }
    20. public Args(String schema, String[] args) throws ParseException {
    21. this.schema = schema;
    22. this.args = args;
    23. valid = parse();
    24. }
    25. private boolean parse() throws ParseException {
    26. if (schema.length() == 0 && args.length == 0)
    27. return true;
    28. parseSchema();
    29. try {
    30. parseArguments();
    31. } catch (ArgsException e) {
    32. }
    33. return valid;
    34. }
    35. private boolean parseSchema() throws ParseException {
    36. for (String element : schema.split(",")) {
    37. if (element.length() > 0) {
    38. String trimmedElement = element.trim();
    39. parseSchemaElement(trimmedElement);
    40. }
    41. }
    42. return true;
    43. }
    44. private void parseSchemaElement(String element) throws ParseException {
    45. char elementId = element.charAt(0);
    46. String elementTail = element.substring(1);
    47. validateSchemaElementId(elementId);
    48. if (isBooleanSchemaElement(elementTail))
    49. marshalers.put(elementId, new BooleanArgumentMarshaler());
    50. else if (isStringSchemaElement(elementTail))
    51. marshalers.put(elementId, new StringArgumentMarshaler());
    52. else if (isIntegerSchemaElement(elementTail)) {
    53. marshalers.put(elementId, new IntegerArgumentMarshaler());
    54. } else {
    55. throw new ParseException(String.format(
    56. "Argument: %c has invalid format: %s.", elementId, elementTail), 0);
    57. }
    58. }
    59. private void validateSchemaElementId(char elementId) throws ParseException {
    60. if (!Character.isLetter(elementId)) {
    61. throw new ParseException(
    62. "Bad character:" + elementId + "in Args format: " + schema, 0);
    63. }
    64. }
    65. private boolean isStringSchemaElement(String elementTail) {
    66. return elementTail.equals("*");
    67. }
    68. private boolean isBooleanSchemaElement(String elementTail) {
    69. return elementTail.length() == 0;
    70. }
    71. private boolean isIntegerSchemaElement(String elementTail) {
    72. return elementTail.equals("-");
    73. }
    74. private boolean parseArguments() throws ArgsException {
    75. for (currentArgument = 0; currentArgument < args.length; currentArgument++) {
    76. String arg = args[currentArgument];
    77. parseArgument(arg);
    78. }
    79. return true;
    80. }
    81. private void parseArgument(String arg) throws ArgsException {
    82. if (arg.startsWith("-"))
    83. parseElements(arg);
    84. }
    85. private void parseElements(String arg) throws ArgsException {
    86. for (int i = 1; i < arg.length(); i++)
    87. parseElement(arg.charAt(i));
    88. }
    89. private void parseElement(char argChar) throws ArgsException {
    90. if (setArgument(argChar))
    91. argsFound.add(argChar);
    92. else {
    93. unexpectedArguments.add(argChar);
    94. errorCode = ErrorCode.UNEXPECTED_ARGUMENT;
    95. valid = false;
    96. }
    97. }
    98. private boolean setArgument(char argChar) throws ArgsException {
    99. ArgumentMarshaler m = marshalers.get(argChar);
    100. try {
    101. if (m instanceof BooleanArgumentMarshaler)
    102. setBooleanArg(m);
    103. else if (m instanceof StringArgumentMarshaler)
    104. setStringArg(m);
    105. else if (m instanceof IntegerArgumentMarshaler)
    106. setIntArg(m);
    107. else
    108. return false;
    109. } catch (ArgsException e) {
    110. valid = false;
    111. errorArgumentId = argChar;
    112. throw e;
    113. }
    114. return true;
    115. }
    116. private void setIntArg(ArgumentMarshaler m) throws ArgsException {
    117. currentArgument++;
    118. String parameter = null;
    119. try {
    120. parameter = args[currentArgument];
    121. m.set(parameter);
    122. } catch (ArrayIndexOutOfBoundsException e) {
    123. errorCode = ErrorCode.MISSING_INTEGER;
    124. throw new ArgsException();
    125. } catch (ArgsException e) {
    126. errorParameter = parameter;
    127. errorCode = ErrorCode.INVALID_INTEGER;
    128. throw e;
    129. }
    130. }
    131. private void setStringArg(ArgumentMarshaler m) throws ArgsException {
    132. currentArgument++;
    133. try {
    134. m.set(args[currentArgument]);
    135. } catch (ArrayIndexOutOfBoundsException e) {
    136. errorCode = ErrorCode.MISSING_STRING;
    137. throw new ArgsException();
    138. }
    139. }
    140. private void setBooleanArg(ArgumentMarshaler m) {
    141. try {
    142. m.set("true");
    143. } catch (ArgsException e) {
    144. }
    145. }
    146. public int cardinality() {
    147. return argsFound.size();
    148. }
    149. public String usage() {
    150. if (schema.length() > 0)
    151. return "-[" + schema + "]";
    152. else
    153. return " ";
    154. }
    155. public String errorMessage() throws Exception {
    156. switch (errorCode) {
    157. case OK:
    158. throw new Exception("TILT: Should not get here.");
    159. case UNEXPECTED_ARGUMENT:
    160. return unexpectedArgumentMessage();
    161. case MISSING_STRING:
    162. return String.format("Could not find string parameter for -%c.",
    163. errorArgumentId);
    164. case INVALID_INTEGER:
    165. return String.format("Argument -%c expects an integer but was '%s'.",
    166. errorArgumentId, errorParameter);
    167. case MISSING_INTEGER:
    168. return String.format("Could not find integer parameter for -%c.",
    169. errorArgumentId);
    170. }
    171. return " ";
    172. }
    173. private String unexpectedArgumentMessage() {
    174. StringBuffer message = new StringBuffer("Argument(s) -");
    175. for (char c : unexpectedArguments) {
    176. message.append(c);
    177. }
    178. message.append(" unexpected.");
    179. return message.toString();
    180. }
    181. public boolean getBoolean(char arg) {
    182. Args.ArgumentMarshaler am = marshalers.get(arg);
    183. boolean b = false;
    184. try {
    185. b = am != null && (Boolean) am.get();
    186. } catch (ClassCastException e) {
    187. b = false;
    188. }
    189. return b;
    190. }
    191. public String getString(char arg) {
    192. Args.ArgumentMarshaler am = marshalers.get(arg);
    193. try {
    194. return am == null ? " " : (String) am.get();
    195. } catch (ClassCastException e) {
    196. return " ";
    197. }
    198. }
    199. public int getInt(char arg) {
    200. Args.ArgumentMarshaler am = marshalers.get(arg);
    201. try {
    202. return am == null ? 0 : (Integer) am.get();
    203. } catch (Exception e) {
    204. return 0;
    205. }
    206. }
    207. public boolean has(char arg) {
    208. return argsFound.contains(arg);
    209. }
    210. public boolean isValid() {
    211. return valid;
    212. }
    213. private class ArgsException extends Exception {
    214. }
    215. private abstract class ArgumentMarshaler {
    216. public abstract void set(String s) throws ArgsException;
    217. public abstract Object get();
    218. }
    219. private class BooleanArgumentMarshaler extends ArgumentMarshaler {
    220. private boolean booleanValue = false;
    221. public void set(String s) {
    222. booleanValue = true;
    223. }
    224. public Object get() {
    225. return booleanValue;
    226. }
    227. }
    228. private class StringArgumentMarshaler extends ArgumentMarshaler {
    229. private String stringValue = " ";
    230. public void set(String s) {
    231. stringValue = s;
    232. }
    233. public Object get() {
    234. return stringValue;
    235. }
    236. }
    237. private class IntegerArgumentMarshaler extends ArgumentMarshaler {
    238. private int intValue = 0;
    239. public void set(String s) throws ArgsException {
    240. try {
    241. intValue = Integer.parseInt(s);
    242. } catch (NumberFormatException e) {
    243. throw new ArgsException();
    244. }
    245. }
    246. public Object get() {
    247. return intValue;
    248. }
    249. }
    250. }

    After all that work, this is a bit disappointing. The structure is a bit better, but we still have all those variables up at the top; there’s still a horrible type-case in setArgument; and all those set functions are really ugly. Not to mention all the error processing. We still have a lot of work ahead of us.

    I’d really like to get rid of that type-case up in setArgument [G23]. What I’d like in setArgument is a single call to ArgumentMarshaler.set. This means I need to push setIntArg, setStringArg, and setBooleanArg down into the appropriate ArgumentMarshaler derivatives. But there is a problem.

    If you look closely at setIntArg, you’ll notice that it uses two instance variables: args and currentArg. To move setIntArg down into BooleanArgumentMarshaler, I’ll have to pass both args and currentArgs as function arguments. That’s dirty [F1]. I’d rather pass one argument instead of two. Fortunately, there is a simple solution. We can convert the args array into a list and pass an Iterator down to the set functions. The following took me ten steps, passing all the tests after each. But I’ll just show you the result. You should be able to figure out what most of the tiny little steps were.

    1. public class Args {
    2. private String schema;
    3. private String[] args;
    4. private boolean valid = true;
    5. private Set<Character> unexpectedArguments = new TreeSet<Character>();
    6. private Map<Character, ArgumentMarshaler> marshalers =
    7. new HashMap<Character, ArgumentMarshaler>();
    8. private Set<Character> argsFound = new HashSet<Character>();
    9. private Iterator<String> currentArgument;
    10. private char errorArgumentId = '\0';
    11. private String errorParameter = "TILT";
    12. private ErrorCode errorCode = ErrorCode.OK;
    13. private List<String> argsList;
    14. private enum ErrorCode {
    15. OK, MISSING_STRING, MISSING_INTEGER, INVALID_INTEGER,
    16. UNEXPECTED_ARGUMENT
    17. }
    18. public Args(String schema, String[] args) throws ParseException {
    19. this.schema = schema;
    20. argsList = Arrays.asList(args);
    21. valid = parse();
    22. }
    23. private boolean parse() throws ParseException {
    24. if (schema.length() == 0 && argsList.size() == 0)
    25. return true;
    26. parseSchema();
    27. try {
    28. parseArguments();
    29. } catch (ArgsException e) {
    30. }
    31. return valid;
    32. }
    33. }
    34. ---
    35. private boolean parseArguments() throws ArgsException {
    36. for (currentArgument = argsList.iterator(); currentArgument.hasNext(); ) {
    37. String arg = currentArgument.next();
    38. parseArgument(arg);
    39. }
    40. return true;
    41. }
    42. ---
    43. private void setIntArg(ArgumentMarshaler m) throws ArgsException {
    44. String parameter = null;
    45. try {
    46. parameter = currentArgument.next();
    47. m.set(parameter);
    48. } catch (NoSuchElementException e) {
    49. errorCode = ErrorCode.MISSING_INTEGER;
    50. throw new ArgsException();
    51. } catch (ArgsException e) {
    52. errorParameter = parameter;
    53. errorCode = ErrorCode.INVALID_INTEGER;
    54. throw e;
    55. }
    56. private void setStringArg(ArgumentMarshaler m) throws ArgsException {
    57. try {
    58. m.set(currentArgument.next());
    59. } catch (NoSuchElementException e) {
    60. errorCode = ErrorCode.MISSING_STRING;
    61. throw new ArgsException();
    62. }
    63. }

    These were simple changes that kept all the tests passing. Now we can start moving the set functions down into the appropriate derivatives. First, I need to make the following change in setArgument:

    This change is important because we want to completely eliminate the if-else chain. Therefore, we needed to get the error condition out of it.

    Now we can start to move the set functions. The setBooleanArg function is trivial, so we’ll prepare that one first. Our goal is to change the setBooleanArg function to simply forward to the BooleanArgumentMarshaler.

    1. private boolean setArgument(char argChar) throws ArgsException {
    2. ArgumentMarshaler m = marshalers.get(argChar);
    3. if (m == null)
    4. return false;
    5. try {
    6. if (m instanceof BooleanArgumentMarshaler)
    7. setBooleanArg(m, currentArgument);
    8. else if (m instanceof StringArgumentMarshaler)
    9. setStringArg(m);
    10. else if (m instanceof IntegerArgumentMarshaler)
    11. setIntArg(m);
    12. } catch (ArgsException e) {
    13. valid = false;
    14. errorArgumentId = argChar;
    15. throw e;
    16. }
    17. return true;
    18. }
    19. ---
    20. private void setBooleanArg(ArgumentMarshaler m, Iterator<String> currentArgument)
    21. throws ArgsException {
    22. try {
    23. m.set("true");
    24. } catch (ArgsException e) {
    25. }
    26. }

    Didn’t we just put that exception processing in? Putting things in so you can take them out again is pretty common in refactoring. The smallness of the steps and the need to keep the tests running means that you move things around a lot. Refactoring is a lot like solving a Rubik’s cube. There are lots of little steps required to achieve a large goal. Each step enables the next.

    Why did we pass that iterator when setBooleanArg certainly doesn’t need it? Because setIntArg and setStringArg will! And because I want to deploy all three of these functions through an abstract method in ArgumentMarshaller, I need to pass it to setBooleanArg.

    So now setBooleanArg is useless. If there were a set function in ArgumentMarshaler, we could call it directly. So it’s time to make that function! The first step is to add the new abstract method to ArgumentMarshaler.

    1. private abstract class ArgumentMarshaler {
    2. public abstract void set(Iterator<String> currentArgument)
    3. throws ArgsException;
    4. public abstract void set(String s) throws ArgsException;
    5. public abstract Object get();
    6. }

    Of course this breaks all the derivatives. So let’s implement the new method in each.

    1. private class BooleanArgumentMarshaler extends ArgumentMarshaler {
    2. private boolean booleanValue = false;
    3. public void set(Iterator<String> currentArgument) throws ArgsException {
    4. booleanValue = true;
    5. }
    6. public void set(String s) {
    7. booleanValue = true;
    8. }
    9. public Object get() {
    10. return booleanValue;
    11. }
    12. }
    13. private class StringArgumentMarshaler extends ArgumentMarshaler {
    14. private String stringValue = "";
    15. public void set(Iterator<String> currentArgument) throws ArgsException {
    16. }
    17. public void set(String s) {
    18. stringValue = s;
    19. }
    20. public Object get() {
    21. return stringValue;
    22. }
    23. }
    24. private class IntegerArgumentMarshaler extends ArgumentMarshaler {
    25. private int intValue = 0;
    26. public void set(Iterator<String> currentArgument) throws ArgsException {
    27. }
    28. public void set(String s) throws ArgsException {
    29. try {
    30. intValue = Integer.parseInt(s);
    31. } catch (NumberFormatException e) {
    32. throw new ArgsException();
    33. }
    34. }
    35. public Object get() {
    36. return intValue;
    37. }
    38. }

    And now we can eliminate setBooleanArg!

    1. private boolean setArgument(char argChar) throws ArgsException {
    2. ArgumentMarshaler m = marshalers.get(argChar);
    3. if (m == null)
    4. return false;
    5. try {
    6. if (m instanceof BooleanArgumentMarshaler)
    7. m.set(currentArgument);
    8. else if (m instanceof StringArgumentMarshaler)
    9. setStringArg(m);
    10. else if (m instanceof IntegerArgumentMarshaler)
    11. setIntArg(m);
    12. } catch (ArgsException e) {
    13. valid = false;
    14. errorArgumentId = argChar;
    15. throw e;
    16. }
    17. return true;
    18. }

    The tests all pass, and the set function is deploying to BooleanArgumentMarshaler! Now we can do the same for Strings and Integers.

    1. private boolean setArgument(char argChar) throws ArgsException {
    2. ArgumentMarshaler m = marshalers.get(argChar);
    3. if (m == null)
    4. return false;
    5. try {
    6. if (m instanceof BooleanArgumentMarshaler)
    7. m.set(currentArgument);
    8. else if (m instanceof StringArgumentMarshaler)
    9. m.set(currentArgument);
    10. else if (m instanceof IntegerArgumentMarshaler)
    11. m.set(currentArgument);
    12. } catch (ArgsException e) {
    13. valid = false;
    14. errorArgumentId = argChar;
    15. throw e;
    16. }
    17. return true;
    18. }
    19. ---
    20. private class StringArgumentMarshaler extends ArgumentMarshaler {
    21. private String stringValue = "";
    22. public void set(Iterator<String> currentArgument) throws ArgsException {
    23. try {
    24. stringValue = currentArgument.next();
    25. } catch (NoSuchElementException e) {
    26. errorCode = ErrorCode.MISSING_STRING;
    27. throw new ArgsException();
    28. }
    29. }
    30. public void set(String s) {
    31. }
    32. public Object get() {
    33. return stringValue;
    34. }
    35. }
    36. private class IntegerArgumentMarshaler extends ArgumentMarshaler {
    37. private int intValue = 0;
    38. public void set(Iterator<String> currentArgument) throws ArgsException {
    39. String parameter = null;
    40. try {
    41. parameter = currentArgument.next();
    42. set(parameter);
    43. } catch (NoSuchElementException e) {
    44. errorCode = ErrorCode.MISSING_INTEGER;
    45. throw new ArgsException();
    46. } catch (ArgsException e) {
    47. errorParameter = parameter;
    48. errorCode = ErrorCode.INVALID_INTEGER;
    49. throw e;
    50. }
    51. }
    52. public void set(String s) throws ArgsException {
    53. try {
    54. intValue = Integer.parseInt(s);
    55. } catch (NumberFormatException e) {
    56. throw new ArgsException();
    57. }
    58. }
    59. public Object get() {
    60. return intValue;
    61. }
    62. }

    And so the coup de grace: The type-case can be removed! Touche!

    1. private boolean setArgument(char argChar) throws ArgsException {
    2. ArgumentMarshaler m = marshalers.get(argChar);
    3. if (m == null)
    4. return false;
    5. try {
    6. m.set(currentArgument);
    7. return true;
    8. } catch (ArgsException e) {
    9. valid = false;
    10. errorArgumentId = argChar;
    11. throw e;
    12. }
    13. }

    Now we can get rid of some crufty functions in IntegerArgumentMarshaler and clean it up a bit.

    1. private class IntegerArgumentMarshaler extends ArgumentMarshaler {
    2. private int intValue = 0
    3. public void set(Iterator<String> currentArgument) throws ArgsException {
    4. String parameter = null;
    5. try {
    6. parameter = currentArgument.next();
    7. intValue = Integer.parseInt(parameter);
    8. } catch (NoSuchElementException e) {
    9. errorCode = ErrorCode.MISSING_INTEGER;
    10. throw new ArgsException();
    11. } catch (NumberFormatException e) {
    12. errorParameter = parameter;
    13. errorCode = ErrorCode.INVALID_INTEGER;
    14. throw new ArgsException();
    15. }
    16. }
    17. public Object get() {
    18. return intValue;
    19. }
    20. }

    We can also turn ArgumentMarshaler into an interface.

    1. private interface ArgumentMarshaler {
    2. void set(Iterator<String> currentArgument) throws ArgsException;
    3. Object get();
    4. }

    So now let’s see how easy it is to add a new argument type to our structure. It should require very few changes, and those changes should be isolated. First, we begin by adding a new test case to check that the double argument works correctly.

    1. public void testSimpleDoublePresent() throws Exception {
    2. Args args = new Args("x##", new String[]{"-x", "42.3"});
    3. assertTrue(args.isValid());
    4. assertEquals(1, args.cardinality());
    5. assertTrue(args.has('x'));
    6. assertEquals(42.3, args.getDouble('x'), .001);
    7. }

    Now we clean up the schema parsing code and add the ## detection for the double argument type.

    1. private void parseSchemaElement(String element) throws ParseException {
    2. char elementId = element.charAt(0);
    3. String elementTail = element.substring(1);
    4. validateSchemaElementId(elementId);
    5. if (elementTail.length() == 0)
    6. marshalers.put(elementId, new BooleanArgumentMarshaler());
    7. else if (elementTail.equals("*"))
    8. marshalers.put(elementId, new StringArgumentMarshaler());
    9. else if (elementTail.equals("#"))
    10. marshalers.put(elementId, new IntegerArgumentMarshaler());
    11. else if (elementTail.equals("##"))
    12. marshalers.put(elementId, new DoubleArgumentMarshaler());
    13. else
    14. throw new ParseException(String.format(
    15. "Argument: %c has invalid format: %s.", elementId, elementTail), 0);
    16. }

    Next, we write the DoubleArgumentMarshaler class.

    1. private class DoubleArgumentMarshaler implements ArgumentMarshaler {
    2. private double doubleValue = 0;
    3. public void set(Iterator<String> currentArgument) throws ArgsException {
    4. String parameter = null;
    5. try {
    6. parameter = currentArgument.next();
    7. doubleValue = Double.parseDouble(parameter);
    8. } catch (NoSuchElementException e) {
    9. errorCode = ErrorCode.MISSING_DOUBLE;
    10. throw new ArgsException();
    11. } catch (NumberFormatException e) {
    12. errorParameter = parameter;
    13. errorCode = ErrorCode.INVALID_DOUBLE;
    14. throw new ArgsException();
    15. }
    16. }
    17. public Object get() {
    18. return doubleValue;
    19. }
    20. }

    This forces us to add a new ErrorCode.

    1. private enum ErrorCode {
    2. OK, MISSING_STRING, MISSING_INTEGER, INVALID_INTEGER, UNEXPECTED_ARGUMENT,
    3. MISSING_DOUBLE, INVALID_DOUBLE
    4. }

    And we need a getDouble function.

    1. public double getDouble(char arg) {
    2. Args.ArgumentMarshaler am = marshalers.get(arg);
    3. try {
    4. return am == null ? 0 : (Double) am.get();
    5. } catch (Exception e) {
    6. return 0.0;
    7. }
    8. }

    And all the tests pass! That was pretty painless. So now let’s make sure all the error processing works correctly. The next test case checks that an error is declared if an unparseable string is fed to a ## argument.

    1. public void testInvalidDouble() throws Exception {
    2. Args args = new Args("x##", new String[]{"-x", "Forty two"});
    3. assertFalse(args.isValid());
    4. assertEquals(0, args.cardinality());
    5. assertFalse(args.has('x'));
    6. assertEquals(0, args.getInt('x'));
    7. assertEquals("Argument -x expects a double but was ‘Forty two'.",
    8. args.errorMessage());
    9. }
    10. ---
    11. public String errorMessage() throws Exception {
    12. switch (errorCode) {
    13. case OK:
    14. throw new Exception("TILT: Should not get here.");
    15. case UNEXPECTED_ARGUMENT:
    16. return unexpectedArgumentMessage();
    17. case MISSING_STRING:
    18. return String.format("Could not find string parameter for -%c.",
    19. errorArgumentId);
    20. case INVALID_INTEGER:
    21. return String.format("Argument -%c expects an integer but was ‘%s’.",
    22. errorArgumentId, errorParameter);
    23. case MISSING_INTEGER:
    24. return String.format("Could not find integer parameter for -%c.",
    25. errorArgumentId);
    26. case INVALID_DOUBLE:
    27. return String.format("Argument -%c expects a double but was ‘%s’.",
    28. errorArgumentId, errorParameter);
    29. case MISSING_DOUBLE:
    30. return String.format("Could not find double parameter for -%c.",
    31. errorArgumentId);
    32. }
    33. return "";
    34. }

    And the tests pass. The next test makes sure we detect a missing double argument properly.

    1. public void testMissingDouble() throws Exception {
    2. Args args = new Args("x##", new String[]{"-x"});
    3. assertFalse(args.isValid());
    4. assertEquals(0, args.cardinality());
    5. assertFalse(args.has('x'));
    6. assertEquals(0.0, args.getDouble('x'), 0.01);
    7. assertEquals("Could not find double parameter for -x.",
    8. args.errorMessage());
    9. }

    This passes as expected. We wrote it simply for completeness.

    The exception code is pretty ugly and doesn’t really belong in the Args class. We are also throwing out ParseException, which doesn’t really belong to us. So let’s merge all the exceptions into a single ArgsException class and move it into its own module.

    1. public class ArgsException extends Exception {
    2. private char errorArgumentId = '\0';
    3. private String errorParameter = "TILT";
    4. private ErrorCode errorCode = ErrorCode.OK;
    5. public ArgsException() {
    6. }
    7. public ArgsException(String message) {
    8. super(message);
    9. }
    10. public enum ErrorCode {
    11. OK, MISSING_STRING, MISSING_INTEGER,
    12. INVALID_INTEGER, UNEXPECTED_ARGUMENT,
    13. MISSING_DOUBLE, INVALID_DOUBLE
    14. }
    15. }
    16. ---
    17. public class Args {
    18. private char errorArgumentId = '\0';
    19. private String errorParameter = "TILT";
    20. private ArgsException.ErrorCode errorCode = ArgsException.ErrorCode.OK;
    21. private List<String> argsList;
    22. public Args(String schema, String[] args) throws ArgsException {
    23. this.schema = schema;
    24. argsList = Arrays.asList(args);
    25. valid = parse();
    26. }
    27. private boolean parse() throws ArgsException {
    28. if (schema.length() == 0 && argsList.size() == 0)
    29. return true;
    30. parseSchema();
    31. try {
    32. parseArguments();
    33. } catch (ArgsException e) {
    34. }
    35. return valid;
    36. }
    37. private boolean parseSchema() throws ArgsException {
    38. }
    39. private void parseSchemaElement(String element) throws ArgsException {
    40. else
    41. throw new ArgsException(
    42. String.format("Argument: %c has invalid format: %s.",
    43. elementId, elementTail));
    44. }
    45. private void validateSchemaElementId(char elementId) throws ArgsException {
    46. if (!Character.isLetter(elementId)) {
    47. throw new ArgsException(
    48. "Bad character:" + elementId + "in Args format: " + schema);
    49. }
    50. }
    51. private void parseElement(char argChar) throws ArgsException {
    52. if (setArgument(argChar))
    53. argsFound.add(argChar);
    54. else {
    55. unexpectedArguments.add(argChar);
    56. errorCode = ArgsException.ErrorCode.UNEXPECTED_ARGUMENT;
    57. valid = false;
    58. }
    59. }
    60. private class StringArgumentMarshaler implements ArgumentMarshaler {
    61. private String stringValue = "";
    62. public void set(Iterator<String> currentArgument) throws ArgsException {
    63. try {
    64. stringValue = currentArgument.next();
    65. } catch (NoSuchElementException e) {
    66. errorCode = ArgsException.ErrorCode.MISSING_STRING;
    67. throw new ArgsException();
    68. }
    69. }
    70. public Object get() {
    71. return stringValue;
    72. }
    73. }
    74. private class IntegerArgumentMarshaler implements ArgumentMarshaler {
    75. private int intValue = 0;
    76. public void set(Iterator<String> currentArgument) throws ArgsException {
    77. String parameter = null;
    78. try {
    79. parameter = currentArgument.next();
    80. intValue = Integer.parseInt(parameter);
    81. } catch (NoSuchElementException e) {
    82. errorCode = ArgsException.ErrorCode.MISSING_INTEGER;
    83. throw new ArgsException();
    84. } catch (NumberFormatException e) {
    85. errorParameter = parameter;
    86. errorCode = ArgsException.ErrorCode.INVALID_INTEGER;
    87. throw new ArgsException();
    88. }
    89. }
    90. public Object get() {
    91. return intValue;
    92. }
    93. }
    94. private class DoubleArgumentMarshaler implements ArgumentMarshaler {
    95. private double doubleValue = 0;
    96. public void set(Iterator<String> currentArgument) throws ArgsException {
    97. String parameter = null;
    98. try {
    99. parameter = currentArgument.next();
    100. doubleValue = Double.parseDouble(parameter);
    101. } catch (NoSuchElementException e) {
    102. errorCode = ArgsException.ErrorCode.MISSING_DOUBLE;
    103. throw new ArgsException();
    104. } catch (NumberFormatException e) {
    105. errorParameter = parameter;
    106. errorCode = ArgsException.ErrorCode.INVALID_DOUBLE;
    107. throw new ArgsException();
    108. }
    109. }
    110. public Object get() {
    111. return doubleValue;
    112. }
    113. }
    114. }

    This is nice. Now the only exception thrown by Args is ArgsException. Moving ArgsException into its own module means that we can move a lot of the miscellaneous error support code into that module and out of the Args module. It provides a natural and obvious place to put all that code and will really help us clean up the Args module going forward.

    So now we have completely separated the exception and error code from the Args module. (See Listing 14-13 through Listing 14-16.) This was achieved through a series of about 30 tiny steps, keeping the tests passing between each step.

    Listing 14-13 ArgsTest.java

    1. package com.objectmentor.utilities.args;
    2. import junit.framework.TestCase;
    3. public class ArgsTest extends TestCase {
    4. public void testCreateWithNoSchemaOrArguments() throws Exception {
    5. Args args = new Args("", new String[0]);
    6. assertEquals(0, args.cardinality());
    7. }
    8. public void testWithNoSchemaButWithOneArgument() throws Exception {
    9. try {
    10. new Args("", new String[]{"-x"});
    11. fail();
    12. } catch (ArgsException e) {
    13. assertEquals(ArgsException.ErrorCode.UNEXPECTED_ARGUMENT,
    14. e.getErrorCode());
    15. assertEquals('x', e.getErrorArgumentId());
    16. }
    17. }
    18. public void testWithNoSchemaButWithMultipleArguments() throws Exception {
    19. try {
    20. new Args("", new String[]{"-x", "-y"});
    21. fail();
    22. } catch (ArgsException e) {
    23. assertEquals(ArgsException.ErrorCode.UNEXPECTED_ARGUMENT,
    24. e.getErrorCode());
    25. assertEquals('x', e.getErrorArgumentId());
    26. }
    27. }
    28. public void testNonLetterSchema() throws Exception {
    29. try {
    30. new Args("*", new String[]{});
    31. fail("Args constructor should have thrown exception");
    32. } catch (ArgsException e) {
    33. assertEquals(ArgsException.ErrorCode.INVALID_ARGUMENT_NAME,
    34. e.getErrorCode());
    35. assertEquals('*', e.getErrorArgumentId());
    36. }
    37. }
    38. public void testInvalidArgumentFormat() throws Exception {
    39. try {
    40. new Args("f~", new String[]{});
    41. fail("Args constructor should have throws exception");
    42. } catch (ArgsException e) {
    43. assertEquals(ArgsException.ErrorCode.INVALID_FORMAT, e.getErrorCode());
    44. assertEquals('f', e.getErrorArgumentId());
    45. }
    46. }
    47. public void testSimpleBooleanPresent() throws Exception {
    48. Args args = new Args("x", new String[]{"-x"});
    49. assertEquals(1, args.cardinality());
    50. assertEquals(true, args.getBoolean('x'));
    51. }
    52. public void testSimpleStringPresent() throws Exception {
    53. Args args = new Args("x*", new String[]{"-x", "param"});
    54. assertEquals(1, args.cardinality());
    55. assertTrue(args.has('x'));
    56. assertEquals("param", args.getString('x'));
    57. }
    58. public void testMissingStringArgument() throws Exception {
    59. try {
    60. new Args("x*", new String[]{"-x"});
    61. fail();
    62. } catch (ArgsException e) {
    63. assertEquals(ArgsException.ErrorCode.MISSING_STRING, e.getErrorCode());
    64. assertEquals('x', e.getErrorArgumentId());
    65. }
    66. }
    67. public void testSpacesInFormat() throws Exception {
    68. Args args = new Args("x, y", new String[]{"-xy"});
    69. assertEquals(2, args.cardinality());
    70. assertTrue(args.has('x'));
    71. assertTrue(args.has('y'));
    72. }
    73. public void testSimpleIntPresent() throws Exception {
    74. Args args = new Args("x#", new String[]{"-x", "42"});
    75. assertEquals(1, args.cardinality());
    76. assertTrue(args.has('x'));
    77. assertEquals(42, args.getInt('x'));
    78. }
    79. public void testInvalidInteger() throws Exception {
    80. try {
    81. new Args("x#", new String[]{"-x", "Forty two"});
    82. fail();
    83. } catch (ArgsException e) {
    84. assertEquals(ArgsException.ErrorCode.INVALID_INTEGER, e.getErrorCode());
    85. assertEquals('x', e.getErrorArgumentId());
    86. assertEquals("Forty two", e.getErrorParameter());
    87. }
    88. }
    89. public void testMissingInteger() throws Exception {
    90. try {
    91. new Args("x#", new String[]{"-x"});
    92. fail();
    93. } catch (ArgsException e) {
    94. assertEquals(ArgsException.ErrorCode.MISSING_INTEGER, e.getErrorCode());
    95. assertEquals('x', e.getErrorArgumentId());
    96. }
    97. }
    98. public void testSimpleDoublePresent() throws Exception {
    99. Args args = new Args("x##", new String[]{"-x", "42.3"});
    100. assertEquals(1, args.cardinality());
    101. assertTrue(args.has('x'));
    102. assertEquals(42.3, args.getDouble('x'), .001);
    103. }
    104. public void testInvalidDouble() throws Exception {
    105. try {
    106. new Args("x##", new String[]{"-x", "Forty two"});
    107. fail();
    108. } catch (ArgsException e) {
    109. assertEquals(ArgsException.ErrorCode.INVALID_DOUBLE, e.getErrorCode());
    110. assertEquals('x', e.getErrorArgumentId());
    111. assertEquals("Forty two", e.getErrorParameter());
    112. }
    113. }
    114. public void testMissingDouble() throws Exception {
    115. try {
    116. new Args("x##", new String[]{"-x"});
    117. fail();
    118. } catch (ArgsException e) {
    119. assertEquals(ArgsException.ErrorCode.MISSING_DOUBLE, e.getErrorCode());
    120. assertEquals('x', e.getErrorArgumentId());
    121. }
    122. }
    123. }

    Listing 14-14 ArgsExceptionTest.java

    1. public class ArgsExceptionTest extends TestCase {
    2. public void testUnexpectedMessage() throws Exception {
    3. ArgsException e =
    4. new ArgsException(ArgsException.ErrorCode.UNEXPECTED_ARGUMENT,
    5. 'x', null);
    6. assertEquals("Argument -x unexpected.", e.errorMessage());
    7. }
    8. public void testMissingStringMessage() throws Exception {
    9. ArgsException e = new ArgsException(ArgsException.ErrorCode.MISSING_STRING,
    10. 'x', null);
    11. assertEquals("Could not find string parameter for -x.", e.errorMessage());
    12. }
    13. public void testInvalidIntegerMessage() throws Exception {
    14. ArgsException e =
    15. new ArgsException(ArgsException.ErrorCode.INVALID_INTEGER,
    16. 'x', "Forty two");
    17. assertEquals("Argument -x expects an integer but was 'Forty two'.",
    18. e.errorMessage());
    19. }
    20. public void testMissingIntegerMessage() throws Exception {
    21. ArgsException e =
    22. new ArgsException(ArgsException.ErrorCode.MISSING_INTEGER, 'x', null);
    23. assertEquals("Could not find integer parameter for -x.", e.errorMessage());
    24. }
    25. public void testInvalidDoubleMessage() throws Exception {
    26. ArgsException e = new ArgsException(ArgsException.ErrorCode.INVALID_DOUBLE,
    27. 'x', "Forty two");
    28. assertEquals("Argument -x expects a double but was 'Forty two'.",
    29. e.errorMessage());
    30. }
    31. public void testMissingDoubleMessage() throws Exception {
    32. ArgsException e = new ArgsException(ArgsException.ErrorCode.MISSING_DOUBLE,
    33. 'x', null);
    34. assertEquals("Could not find double parameter for -x.", e.errorMessage());
    35. }
    36. }

    Listing 14-15 ArgsException.java

    1. public class ArgsException extends Exception {
    2. private char errorArgumentId = '\0';
    3. private String errorParameter = "TILT";
    4. private ErrorCode errorCode = ErrorCode.OK;
    5. public ArgsException() {
    6. }
    7. public ArgsException(String message) {
    8. super(message);
    9. }
    10. public ArgsException(ErrorCode errorCode) {
    11. this.errorCode = errorCode;
    12. }
    13. public ArgsException(ErrorCode errorCode, String errorParameter) {
    14. this.errorCode = errorCode;
    15. this.errorParameter = errorParameter;
    16. }
    17. public ArgsException(ErrorCode errorCode, char errorArgumentId,
    18. String errorParameter) {
    19. this.errorCode = errorCode;
    20. this.errorParameter = errorParameter;
    21. this.errorArgumentId = errorArgumentId;
    22. }
    23. public char getErrorArgumentId() {
    24. return errorArgumentId;
    25. }
    26. public void setErrorArgumentId(char errorArgumentId) {
    27. this.errorArgumentId = errorArgumentId;
    28. }
    29. public String getErrorParameter() {
    30. return errorParameter;
    31. }
    32. public void setErrorParameter(String errorParameter) {
    33. this.errorParameter = errorParameter;
    34. }
    35. public ErrorCode getErrorCode() {
    36. return errorCode;
    37. }
    38. public void setErrorCode(ErrorCode errorCode) {
    39. this.errorCode = errorCode;
    40. }
    41. public String errorMessage() throws Exception {
    42. switch (errorCode) {
    43. case OK:
    44. throw new Exception("TILT: Should not get here.");
    45. case UNEXPECTED_ARGUMENT:
    46. return String.format("Argument -%c unexpected.", errorArgumentId);
    47. case MISSING_STRING:
    48. return String.format("Could not find string parameter for -%c.",
    49. errorArgumentId);
    50. case INVALID_INTEGER:
    51. return String.format("Argument -%c expects an integer but was '%s'.",
    52. errorArgumentId, errorParameter);
    53. case MISSING_INTEGER:
    54. return String.format("Could not find integer parameter for -%c.",
    55. errorArgumentId);
    56. case INVALID_DOUBLE:
    57. return String.format("Argument -%c expects a double but was '%s'.",
    58. errorArgumentId, errorParameter);
    59. case MISSING_DOUBLE:
    60. return String.format("Could not find double parameter for -%c.",
    61. errorArgumentId);
    62. }
    63. return "";
    64. }
    65. public enum ErrorCode {
    66. OK, INVALID_FORMAT, UNEXPECTED_ARGUMENT, INVALID_ARGUMENT_NAME,
    67. MISSING_STRING,
    68. MISSING_INTEGER, INVALID_INTEGER,
    69. MISSING_DOUBLE, INVALID_DOUBLE
    70. }
    71. }

    Listing 14-16 Args.java

    1. public class Args {
    2. private String schema;
    3. private Map<Character, ArgumentMarshaler> marshalers =
    4. new HashMap<Character, ArgumentMarshaler>();
    5. private Set<Character> argsFound = new HashSet<Character>();
    6. private Iterator<String> currentArgument;
    7. private List<String> argsList;
    8. public Args(String schema, String[] args) throws ArgsException {
    9. this.schema = schema;
    10. argsList = Arrays.asList(args);
    11. parse();
    12. }
    13. private void parse() throws ArgsException {
    14. parseSchema();
    15. parseArguments();
    16. }
    17. private boolean parseSchema() throws ArgsException {
    18. for (String element : schema.split(",")) {
    19. if (element.length() > 0) {
    20. parseSchemaElement(element.trim());
    21. }
    22. }
    23. return true;
    24. }
    25. private void parseSchemaElement(String element) throws ArgsException {
    26. char elementId = element.charAt(0);
    27. String elementTail = element.substring(1);
    28. validateSchemaElementId(elementId);
    29. if (elementTail.length() == 0)
    30. marshalers.put(elementId, new BooleanArgumentMarshaler());
    31. else if (elementTail.equals("*"))
    32. marshalers.put(elementId, new StringArgumentMarshaler());
    33. else if (elementTail.equals("#"))
    34. marshalers.put(elementId, new IntegerArgumentMarshaler());
    35. else if (elementTail.equals("##"))
    36. marshalers.put(elementId, new DoubleArgumentMarshaler());
    37. else
    38. throw new ArgsException(ArgsException.ErrorCode.INVALID_FORMAT,
    39. elementId, elementTail);
    40. }
    41. private void validateSchemaElementId(char elementId) throws ArgsException {
    42. if (!Character.isLetter(elementId)) {
    43. throw new ArgsException(ArgsException.ErrorCode.INVALID_ARGUMENT_NAME,
    44. elementId, null);
    45. }
    46. }
    47. private void parseArguments() throws ArgsException {
    48. for (currentArgument = argsList.iterator(); currentArgument.hasNext(); ) {
    49. String arg = currentArgument.next();
    50. parseArgument(arg);
    51. }
    52. }
    53. private void parseArgument(String arg) throws ArgsException {
    54. if (arg.startsWith("-"))
    55. parseElements(arg);
    56. }
    57. private void parseElements(String arg) throws ArgsException {
    58. for (int i = 1; i < arg.length(); i++)
    59. parseElement(arg.charAt(i));
    60. }
    61. private void parseElement(char argChar) throws ArgsException {
    62. if (setArgument(argChar))
    63. argsFound.add(argChar);
    64. else {
    65. throw new ArgsException(ArgsException.ErrorCode.UNEXPECTED_ARGUMENT,
    66. argChar, null);
    67. }
    68. }
    69. private boolean setArgument(char argChar) throws ArgsException {
    70. ArgumentMarshaler m = marshalers.get(argChar);
    71. if (m == null)
    72. return false;
    73. try {
    74. m.set(currentArgument);
    75. return true;
    76. } catch (ArgsException e) {
    77. e.setErrorArgumentId(argChar);
    78. throw e;
    79. }
    80. }
    81. public int cardinality() {
    82. return argsFound.size();
    83. }
    84. public String usage() {
    85. if (schema.length() > 0)
    86. return "-[" + schema + "]";
    87. else
    88. return "";
    89. }
    90. public boolean getBoolean(char arg) {
    91. ArgumentMarshaler am = marshalers.get(arg);
    92. boolean b = false;
    93. try {
    94. b = am != null && (Boolean) am.get();
    95. } catch (ClassCastException e) {
    96. b = false;
    97. }
    98. return b;
    99. }
    100. public String getString(char arg) {
    101. ArgumentMarshaler am = marshalers.get(arg);
    102. try {
    103. return am == null ? "" : (String) am.get();
    104. } catch (ClassCastException e) {
    105. return "";
    106. }
    107. }
    108. public int getInt(char arg) {
    109. ArgumentMarshaler am = marshalers.get(arg);
    110. try {
    111. return am == null ? 0 : (Integer) am.get();
    112. } catch (Exception e) {
    113. return 0;
    114. }
    115. }
    116. public double getDouble(char arg) {
    117. ArgumentMarshaler am = marshalers.get(arg);
    118. try {
    119. return am == null ? 0 : (Double) am.get();
    120. } catch (Exception e) {
    121. return 0.0;
    122. }
    123. }
    124. public boolean has(char arg) {
    125. return argsFound.contains(arg);
    126. }

    The majority of the changes to the Args class were deletions. A lot of code just got moved out of Args and put into ArgsException. Nice. We also moved all the ArgumentMarshaller s into their own files. Nicer!

    Much of good software design is simply about partitioning—creating appropriate places to put different kinds of code. This separation of concerns makes the code much simpler to understand and maintain.

    Of special interest is the errorMessage method of ArgsException. Clearly it was a violation of the SRP to put the error message formatting into Args. Args should be about the processing of arguments, not about the format of the error messages. However, does it really make sense to put the error message formatting code into ArgsException?

    Frankly, it’s a compromise. Users who don’t like the error messages supplied by ArgsException will have to write their own. But the convenience of having canned error messages already prepared for you is not insignificant.

    By now it should be clear that we are within striking distance of the final solution that appeared at the start of this chapter. I’ll leave the final transformations to you as an exercise.

    CONCLUSION It is not enough for code to work. Code that works is often badly broken. Programmers who satisfy themselves with merely working code are behaving unprofessionally. They may fear that they don’t have time to improve the structure and design of their code, but I disagree. Nothing has a more profound and long-term degrading effect upon a development project than bad code. Bad schedules can be redone, bad requirements can be redefined. Bad team dynamics can be repaired. But bad code rots and ferments, becoming an inexorable weight that drags the team down. Time and time again I have seen teams grind to a crawl because, in their haste, they created a malignant morass of code that forever thereafter dominated their destiny.

    So the solution is to continuously keep your code as clean and simple as it can be. Never let the rot get started.