Java Magazine, May/June 2018
ORACLE COM JAVAMAGAZINE MAY JUNE 2018 24 design patterns The book Refactoring to Patterns calls such code a conditional dispatcher because it uses a conditional statement a long chain of if statements but a switch is also common Theres nothing inherently wrong with writing code this way but it can lead to really long methods that are hard to read You could extract each bit of code into a named method but that leads to a lot of method names Ideally for a couple of reasons conditional dispatcher code is refactored to use the Command pattern One reason is if the code requires more flexibility Another as the book says is the following Some conditional dispatchers become enormous and unwieldy as they evolve to handle new requests or as their handler logic becomes ever more complex with new responsibilities That is exactly a description of the line editors main loop as more commands are implemented the size of the code in the if else chain or switch statement will grow larger without bound So I replaced the main loop with a table of Command implementations an array indexed by the first letter of each command is nice and simple This approach also forced me to provide standardized parsing of the input lines which up to now was done on demand in the various sections I introduced the ParsedLine class to hold the information about the input line and in fact it is a form of Command object because it describes what to do but not how and the receiver is still implicitly this public class ParsedLine char cmdLetter a for append d for delete etc boolean startFound commaFound endFound int startNum endNum String operands The rest of the line public String toString return String format d d c s startNum endNum cmdLetter operands null operands
You must have JavaScript enabled to view digital editions.