So I have a file to process that contains a command on each line. Currently it's implemented like this(this is a refactoring assignment):


The objects(4) inside the hashmap, each contain a different sendCommand method.

The thing is each of these method implementations are just 2 or 3 lines and this feels a bit wrong because those object don't store anything and they just have one method.

Should I instead make this a into a switch and instead process all the commands in one function?

Is there any other way to do this? Any design pattern meant to this? Any other reason the initial implementation is bad or good?

  • 5
    Small objects with a single short method don't look that bad. It is when your classes accumulate pages of crap that you should start worrying. – 5gon12eder Nov 19 '15 at 4:46
  • Actually there was lots of crap, I refactored them to a private method in the super class. Now it's like that. So you're telling me it's fine as it is? – Farid Nouri Neshat Nov 19 '15 at 4:47

The good thing about a switch statement is that it is fast, if you need speed. The bad thing is that in a command processor it lacks flexibility; if you need to add a new kind of command, its time to rewrite the command processor.

With this hash table for decision making it is better, but with hardcoded methods for the command actions, you still face the same problem of recoding the command processor if a new command is added.

If I were in your shoes I would think about an interface or abstract method to define a command and perhaps handle some of the common tasks and having a child class for each command. Your processor could have or call a factory method that would instantiate the correct command class. This way as your command set evolves, less of your code would be affected. Hope this is a help.

  • 2
    And make sure it's a @FunctionalInterface, after all, what is a command but a function? – Jörg W Mittag Nov 19 '15 at 6:13
  • 2
    Switch statements are not fast. The larger the switch, the slower it becomes as each condition has to be evaluated in a linear fashion. It's for that reason that compilers will often turn switch statements into a hashmap as they are faster for a large number of cases. – David Arno Nov 19 '15 at 10:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.