Name for collection of command objects - java

I am developing a command handler where each command can have sub-commands indefinitely. All commands are managed at the root level by a "CommandManager" which takes user input parses options then finds the right command and passes the input to it. As both the CommandManager and the Command both have a similar way of getting and storing specified commands and as both classes are very cluttered I would like to factor out the logic that finds and stores commands into a common superclass, however, I can't think of a descriptive name to call it.
The reason for me to try and make the CommandMagager and the Command both extend another class is that the command manager acts like a command at the root level. Commands don't actually contain any logic to process commands, they just provide a way to register and retrieve commands with a certain name.
Are there any general conventions that may help me find a name or is this the wrong way to be looking at the problem?

Yes there are a few rules about that, nothing written in stone, just kind of practices which became accepted best practices by experience and imitation.
Overview
Make the responsibility clear.
Use Camel Case.
Name objects, not classes.
Use nouns.
Avoid words like Info, Processor or Manager.
Use singular if there are objects.
Use plural for utility classes.
Prefix abstract base class with Abstract.
Suffix hidden implementation class with Impl.
Do not prefix interface names with I.
Use design pattern names correctly.
Prefix names with their specialization.
Use data structure names correctly
Details
Make the Responsibility Clear
It's important that the name reflects the responsibility nicely. The name shall communicate its intent.
Name Objects, not Classes
Use a name which looks good when using a single object. Name the object, not the class.
Use Camel Case
UseCamelCaseForNamesOfTypesInJava.
Use nouns
Use nouns for objects. If the object represents an action, turn the verb into a noun. If the object represents an attribute, turn the adjective into a noun. For example, if the action is compile(), use Compiler if it is an active action, or Compilable if it is a passive ability. If the action is run(), use Runner if it is an active action, Runnable if it is a passive ability.
Avoid words like Info, Processor or Manager
In most of the cases, they're just synonyms for "I don't know what to call this" (Robert C. Martin). This itself is a symptom of "I don't know what this thing is doing" or "This thing is doing more than one thing". Which is why we often rightfully feel the urge to refactor when we see such names.
Use singular if there are objects
Class names usually are singular, especially if you can obtain multiple objects of a single class. We like to reserve the plural for variable names of collections of such objects.
Good Example
JButton button;
List<JButton> buttons;
Bad Example
Properties is a bad class name because it is plural although there are objects. We like to call a List<JButton> jButtons. So, how do you call a List<Properties> - propertiess? propertieses? propertiessies???
Use plural for utility classes
A class is a utility class if it contains only static methods which exist for the sole purpose to provide utility methods for another type.
Good Examples
Collections, Spilterators, Arrays, Executors, FileSystems, Files, Paths.
Prefix abstract base class with Abstract
An abstract base implementation for an interface Foo is usually called AbstractFoo.
Examples: AbstractAction, AbstractList, AbstractMap, AbstractQueue and so forth.
Make sure that this name is a name the user would hardly ever see, AbstractSomething is a nice name for the implementor / extensor, not for the user. And only choose this name in the absence of a better name.
Suffix hidden implementation class with Impl
A class which provides the default implementation for an interface or abstract class Foo is sometimes just called FooImpl.
Make sure the user never sees this name. Never ever. It's only good for the implementor, nobody else. A name like XyzImpl must not be visible to the user. And only choose this name in the absence of a better name.
Do not prefix interface names with I
The purpose of a type in an OO language usually is to encapsulate and hide things. Whether a type is a class, an interface, an enum or an #interface annotation is a detail of that type. There are only two situations where you need to know these details about a type: When you want to extend the type, and when you want to create an object of that type. These use cases are the minority of the use cases of types. By prefixing interface names with I, you violate this principle by loudly declaring an implementation detail that in fact should be hidden.
Putting an I in front of the names of interfaces is like using Hungarian notation. Hungarian notation only makes sense when you're working in an environment where keeping track of these physical aspects of your types is essential. (And for that matter it even is not necessary in C these days!)
Besides, you don't want to look like an idiot when
You decide to change a class in an interface or vice versa and do not rename the type, you end up with an interface without I-prefix or a class with I-prefix.
You decide to change a class in an interface or vice versa and rename the type, you end up annoying your users.
Oracle removes the differences between class and interface in a future version of Java (not so unlikely, look at how interfaces have static and default methods now).
You port your API to another language which doesn't distinguish between class and interface and now have classes with I prefix, or classes which have different names.
Use Design Pattern Names Correctly
If you use a design pattern, you may use its name if it seems appropriate. But if you do not use a design pattern, avoid names of design patterns.
It's optional to use a design pattern name when using a design pattern - use it if it helps or is common practice to use the name of the design pattern, like the Factory-suffix for abstract factories.
But it's almost mandatory to avoid a design pattern name when you're actually not using it. It might be confusing if you name something Command but it doesn't implement the Command pattern, if you name something Strategy but it doesn't implement the Strategy pattern, if you name something Factory but it doesn't implement the Factory pattern.
It's not always confusing, some judgement might be required. For example, you might have a framework for writing command line programs with an interface and an abstract base class for these command line programs. You might want to call them Command and AbstractCommand despite the fact that this is not really the Command design pattern, at least not from the perspective of the language itself.
Examples where the name is used
KeyFactory Factory design pattern
DocumentBuilder Builder design pattern
Action Command design pattern (aka Action, Transaction)
Examples where the name is not used
Runnable, Callable - Command design pattern but different, more specialized names.
Collections.synchronizedList() - Factory Method for a Decorator
Prefix Names with their Specialization
It is common for class names to grow as we advance downwards in the inheritance tree by prefixing the name of a base class with information about the specialization.
Examples
List: AbstractList, ArrayList, AbstractSequentialList, LinkedList
Set: AbstractSet, HashSet, LinkedHashSet
Use data structure names correctly
If you implement data structures, use the appropriate names.
The concept of having key/value pairs regardless of how they are maintained is called dictionary, so an interface describing that should be named Dictionary. (The reason that Java named it Map instead was that the original collections in Java 1.0 were purely designed and already used an abstract class Dictionary, so the interface needed a new name.)
Your Case
In your case, I could imagine the following design:
interface Command { void execute(); } for everything that can be executed.
interface CommandQueue { void submit(Command); } for something to which commands can be submitted.
interface CommandRunner extends CommandQueue { void start(); void stop(); }
I could update this section in case you give a little bit more details. For something which queues and processes commands you might also want to think about parallelization and have a look at java.util.concurrent.

From the way you describe your model it looks like you are dealing with something very close to a composition pattern (CM is the root command, while C represents individual commands.)
If this is the case, then the names you are trying to find are:
Command
CompositeCommand
SimpleCommand
In other words, what you've called CommandManager would play the role of CompositeCommand, your current Command class would be SimpleCommand and, finally, the (abstract) superclass your are looking for would be Command in the terminology I'm proposing. Both the root as well as any other nested commands would be instances of CompositeCommand. Of course, if the root has some special behavior you could also model this as:
Command
CompositeCommand
RootCommand
SimpleCommand
This way, RootCommand would take the place of your CommandManager, it would be composite in itself and any other command with subcommands will be of class CompositeCommand, while "leaves" would be of class SimpleCommand.
I know, some people will dislike concrete classes with subclasses. If that is your case you should do something like this:
Command
CompositeCommand
Subcommand
RootCommand
SimpleCommand
Now Command and CompositeCommand are abstract and all three concrete classes are subclass free.
You might still be wondering why I'm using so many names and not CommandManager. It is because, in my opinition, there is no such thing as a command manager.
Finally, you might need another object (from a different hierarchy), say CommandParser, that would provide parsing services in a more abstract way. The Command hierarchy would use the services of the parser and add semantics to otherwise abstract tokens. It is very likely that this separation will bring more simplicity to the Command code. At the same time it would decouple the syntax of your command language from the internal representation, which would add more flexibility to your design because you could offer, say, two different syntaxes without having to modify the Command hierarchy.

Related

UML/OOP: Using an interface for similar methods in different classes

Suppose I have two different classes that need to print different things:
OrderManager wants to print the order history, and MenuManager wants to print perhaps a menu. Since both want to do a similar function (but actual implementation is different), is it advisable to use an interface like this? The problem is that the function "print" is not very well-defined and self-explanatory as opposed to "printOrderHistory", and I can only implement the method with the exact name as defined in the interface.
Is there a workaround to this or am I using the interface concept wrongly? In fact, nothing seems to be stopping me from just defining their own print functions for each class without an interface...
This is the purpose of an interface! It defines a set of operations, and any class that implements this interface needs to implement these operations. This allows then to refer to a Printable object and call print(), knowing that it will perform as relevant for that object.
Your UML diagram, is therefore ambiguous: as OrderManager realizes (in java, "implements") Printable it should have its own print(). There are three solutions in UML and in Java:
Comply to the interface, as your diagram promises, and rename printOrderHistory() into print(). This makes sense if there is only one meaningfull way to print and order manager, and if there are no other constraints.
Add a print() operation (in java, "method") to OrderManager(), that just forwards the call to printOrderHistory(). But this looks like overcomplicated. It's justifiable only if the order manager would really e a printable, and if print() would add some relevant functionality such as selecting the right printing function depending on some factors.
Use the adapter pattern and leave the OrderManager clean, using an intermediate object for the dirty things. This makes especially sense if the name of OrderManager's printing function is constrained, or if there are different printing functions for different purposes. THis is the most flexible approach
Here a possible diagram for solution 3:
The idea with interfaces is to have a contract to fullfill. That means, that you have to you use method names and parameters defined in the interface when you build an implementation.
From my personal experience, it's always a bad idea to force an interface on classes, that are not similar, as in they do have a different purpose. While you could work with print() in both classes, it only makes sense if they are exchangeable in your code.

Wondering about Microstream class StorageConfiguration

there are two questions with microstream database and its class StorageConfiguration:
1) What ist the difference of the methods New() and Builder() and the DEFAULT construct?
2) Why the methods are writting uppercased? That does not seem to be Java naming convention.
Thanks for any answers!
I am the MicroStream lead developer and I can gladly answer those questions.
To 1)
"New" is a "static factory method" for the type itself.
"Builder" is a static factory method for a "builder" instance of the type.
Both terms can be perfectly googled for more information about them.
A quick service as a starting point:
"static factory method":
https://www.baeldung.com/java-constructors-vs-static-factory-methods
"builder pattern":
https://en.wikipedia.org/wiki/Builder_pattern
--
To your actually second question, about the "DEFAULT" construct:
If I may, there is no "DEFAULT" construct, but "Default".
(Conventions are important ... mostly. See below.)
"Default" is simply the default implementation (= class) of the interface StorageConfiguration.
Building a software architecture directly in classes quickly turns out to be too rigid and thus bad design. Referencing and instantiating classes directly creates a lot of hardcoded dependencies to one single implementation that can't be changed or made more flexible later on. Inheritance is actually only very rarely flexible enough to be a solution for arising architecture flexibility problems. Interfaces, on the other hand, only define a type and the actual class implementing it hardly matters and can even be easily interchangeable. For example, by only designing via interfaces, every instance can easily be "wrapped" by any desired logic via using the decorator pattern. E.g. adding a logging aspect to a type.
There is a good article with an anecdote about James Gosling (the inventor of Java) named "Why extends is evil" that describes this:
https://www.javaworld.com/article/2073649/why-extends-is-evil.html
So:
"Default" is just the default class implementing the interface it is nested in. It makes sense to name such a class "Default", doesn't it? There can be other classes next to it, like "Wrapper" or "LazyInitializing" or "Dummy" or "Randomizing" or whatever.
This design pattern is used in the entire code of MicroStream, giving it an incredibly flexible and powerful architecture. For example:
With a single line of code, every part of MicroStream (every single "gear" in the machine) can be replaced by a custom implementation. One that does things differently (maybe better?) or fixes a bug without even needing a new MicroStream version. Or one that adds logging or customized exception handling or that introduces object communication where there normally is none. Maybe directly with the application logic (but at your own risk!). Anything is possible, at least inside the boundaries of the interfaces.
Thinking in interfaces might be confusing in the beginning (which is why a lot of developers "burn mark" interfaces with a counterproductive "I" prefix. It hurts me every time I see that), but THEY are the actual design types in Java. Classes are only their implementation vehicles and next to irrelevant on the design level.
--
To 2)
I think a more fitting term for "static factory method" is "pseudo constructor". It is a method that acts as a public API constructor for that type, but it isn't an actual constructor. Following the argumentation about the design advantages of such constructor-encapsulating static methods, the question about the best, consistent naming pattern arose to me. The JDK gives some horribly bad examples that should not be copied. Like "of" or "get". Those names hardly carry the meaning of the method's purpose.
It should be as short but still as descriptive as possible. "create" or "build" would be okay, but are they really the best option? "new" would be best, but ironically, that is a keyword associated with the constructors that should be hidden from public API. "neW" or "nEw" would look extremely ugly and would be cumbersome to type. But what about "New"? Yes, it's not strictly Java naming conventions. But there already is one type of methods that does is an exception to the general naming rule. Which one? Constructors! It's not "new person(...") but "new Person(...)". A method beginning with a capital letter. Since the beginning of Java. So if the static method should take the place of a constructor, wouldn't it be quite logical and a very good signal to apply that same exception ... or ... "extension" of the naming convention to that, too? So ... "New" it is. Perfectly short, perfectly clear. Also not longer and VERY similar to the original constructors. "Person.New" instead of "new Person".
The "naming convention extension" that fits BOTH naming exceptions alike is: "every static method that starts with a capital letter is guaranteed to return a new instance of that type." Not a cached one. Always a new one. (this can be sometime crucial to guarantee the correctness of algorithms.)
This also has some neat side effects. For example:
The pseudo-constructor method for creating a new instance of
"StorageConfigurationBuilder" can be "StorageConfiguration.Builder()".
It is self-explaining, simple, clear.
Or if there is a method "public static Vector Normalized(Vector v)", it implicitely
tells that the passed instance will not be changed, but a new instance will
be returned for the normalized vector value. It's like having the
option to give constructors proper names all of a sudden. Instead of
a sea of different "Vector(...)" methods and having to rely on the
JavaDoc to indirectly explain their meaning, the explanation is right
there in the name. "New(...)", "Normalized(...)", "Copy(...)" etc.
AND it also plays along very nicely with the nested-Default-class
pattern: No need to write "new StorageConfiguration.Default()" (which
would be bad because too hardcoded, anyway), but just
"StorageConfiguration.New" suffices. It will internally create and
return a new "StorageConfiguration.Default" instance. And should that
internal logic ever change, it won't even be noticable by the API
user.
Why do I do that if no one else does?
If one thinks about it, that cannot be a valid argument. I stick VERY closely to standards and conventions as far as they make sense. They do about 99% of the time, but if they contain a problem (like forbidding a static method to be called "new") or lacking a perfectly reasonable feature (like PersonBuilder b = Person.Builder()" or choosing properly speaking names for constructors), then, after careful thought, I br... extend them as needed. This is called innovation. If no one else had that insight so far, bad for them, not for me. The question is not why an inventor creates an improvment, but why no one else has done it so far. If there is an obvious possibility for improvement, it can't be a valid reason not to do it just because no one else did it. Such a thinking causes stagnation and death of progress. Like locking oneself in a 1970ies data storing technology for over 40 years instead of just doing the obviously easier, faster, direct, better way.
I suggest to see the capital letter method naming extension as a testimony to innovation: If a new idea objectively brings considerably more advantages than disadvantages, it should - or almost MUST - be done.
I hereby invite everyone to adopt it.

Choice of design pattern - serial execution

I have a simple design problem - I am looking for the best pattern to implement a simple functionality. Let's say, I am going to create an xml message in java. This message consists of many fields in different logic groups.
So, the first idea - create a class to set all fields. I can do it one method (which will be really long...) or split the method into multiple smaller (for each of the logical groups). However, I don't think it is a good approach, because the class will be really long and difficult to mantain.
The second idea is to create a functional interface and some implementations for different groups, for instance GroupXxxSetter, GroupYyySetter, etc. I can create and keep all instances in a list or a set and call the method defined inside the interface for each object stored inside the collection. It seems to be very similar to the 'Chain of responsibility' pattern. However, the idea of this pattern is different, so I am not sure if it is a good idea to use this pattern in my case.
Should I use the 'chain of responsibility' pattern here? Or, maybe there is something better?
Thanks in advance.
Should I use the 'chain of responsibility' pattern here?
Clearly, no. You don't have the notion of candidate responsible to respond to a request. All elements will do a processing.
Or, maybe there is something better?
You have multiple possibilities.
Your context is not totally set. So it is hard to propose one rather than another.
I may propose you a implementation with the Builder pattern (Java Effective reference and not GOF).
For each logic group, you could have a specific class.
You would also have a composite class that is composed of logic group instances.
Instead of providing a public constructor or setters that prevent immutability and that can make rules validation cumbersome, you could use the Builder pattern for each one logic group class and in the composite class, you could use the same kind of Builder pattern where you will build the final message from the previously created logic group instances.
You could so create the instances in this way :
OneLogicGroup oneLogicGroup = OneLogicGroup.builder().fieldXXX(...).fieldYYY(...).build();
AnotherLogicGroup anotherLogicGroup = AnotherLogicGroup .builder().fieldXXX(...).fieldYYY(...).build();
MyMessage myMessage = MyMessage.builder().oneLogicGroup(oneLogicGroup).anotherLogicGroup(anotherLogicGroup).build().
I can create and keep all instances in a list or a set and call the
method defined inside the interface for each object stored inside the
collection.
It seems referring to a structural concern.
It is not directly related to the creation of the object. It is much related to how to share the created objects.
The flyweight pattern addresses this need and may be used conjointly with the presented builder Pattern.

Do method names always have to be verb?

I am new to java programming, and I am currently working on a command reading program (basically the user types in a command and my program evaluates what to do and does it). I have a separate class that contains all my commands, but they're stored as methods and aren't always using verbs as names. I understand that it is customary have methods stored as verbs. Am I using methods wrong and is there a better way to store my commands? Separate class for each command? Example of calling one of my methods:
else if (command[0].equals("math")) Commands.math();
Do method names always have to be verb?
As far as the Java language (i.e. the Java compiler) is concerned, no. The language spec only requires you to follow some rules about what characters are used, and about contextual uniqueness.
Typical Java Style Guides don't require method names to be verbs either. But they typically recommend this. (Note that this is not something that automated style checkers check, because of the difficulty of reliably distinguishing nouns and verbs.)
I understand that it is customary have methods stored as verbs.
That is a better characterization.
This actually comes out of Object Oriented Design. A class in the design maps to a Java class, and the Java methods represent actions on the instances on the design classes. It is "natural" (and customary) to use noun-like identifiers for classes, and verb-like identifiers for methods.
But it is NOT a requirement.
In your example, you could simply address the dilemma by using "doMath" as the method name. That is a verb phrase. (The "do xyz" is a commonly used convention, albeit that it doesn't "read" very well.)
However, it seems like you could, and possibly should avoid hard-wiring the command names into the method names. Take a look at the "Command" design pattern: http://www.fluffycat.com/Java-Design-Patterns/Command/ (archived).
Design patterns are something you will need to learn in the long run, but they are possibly too much for a beginner programmer to digest.
Must methods be verbs? No. As long as the compiler is concerned, it doesn't matter.
Should they be verbs? As a convention that will make programs easier to understand: Clearly yes.
Variables represent objects and data, so you should normally use a noun. Methods represent actions, so you should normally use a verb. There are exceptions, of course but that is the normal rule. Ideally the name of a variable or method should be enough to identify it's function in the class.
To make it more object oriented you may consider using Abstract Class Command and separe classes extending it as classes
In this case, you should put all the methods in the same class, but other than that, you are using methods correctly.
I'm a Java programmer, and I've never heard of the verb custom. However, If you want to follow it, some suggestions for method names are doMath() or calculateMath() or something similar.
Also, you should NOT be splitting up methods by class. Generally, you should only use multiple classes if you are planning to instantiate objects of the different classes. Putting each method in a separate class is pretty ridiculous.

Object Conversion Pattern

I have several different classes coming from external sources (unmodifiable) that represent the same concept. For example Address. I have com.namespace1.Address (with fields houseNum, street, city), com.namespace2.Address (with fields h, s, c), namespace3.com.CoolAddress (with fields house_num, street, city).
The problem is that certain web services I use require certain Address object types so I am required to create a com.namespace1.Address given a namespace3.com.CoolAddress. The fields are easy enough to map but I'm looking for a pattern on how to do it.
From my point of view, an instance object AddressConverter doesn't make sense as there is no state (only behaviour) and when classes only have behaviour it boils down to static methods in a utility class. In the long term, anytime I need to map new objects to one another, I have one place to add/modify/remove methods. How it's done might change, but I know where the code sits (in once place) and can change the mapping when I need to.
Thoughts?
I think what you're looking for is a factory class. The factory pattern is used when you need to be able to instantiate one of several related classes, to be determined by the factory, not the developer.
See http://en.wikipedia.org/wiki/Factory_method_pattern
You're right to try to keep all this business logic in one place instead of doing ClassOne.toClassTwo(), ClassOne.toClassThree(),...
The most flexible way I can think of implementing this (but not the easiest by far) would be to have the factory start with a simple class with only basic common methods in it, and add handlers to a Hashtable or other container. That way you don't need concrete implementations of every possible combinations of features.
Of course it would be quicker to have a concrete implementation for each possible address variant, but there would be a fair amount of duplicated code, and it would be a little harder to add new address class types.
Since you can't modify the classes themselves, I'd suggest an implementation of the Adapter pattern for each direction. As you said, the adapter methods themselves can be static, but you can group both directions inside a single class so that the logic is all in one place.
At the end of the day you're going to be performing the same task no matter what you call it, or where you put the code. I'd suggest that both directions live in the same file, as they'll often both need updating when either direction changes.
If you are always converting to the same Class I would keep it simple and put all you conversion code in that Class and not worry about factories and the like, especially if you are only dealing with a couple of different classes. Why does there always have to be a complicated pattern for these things?!
public class A {
...
public static A convertB(B b) {
...
}
}
Are the classes you need to output final? If not, you could subclass them to create proper Adapters. Otherwise I'd go with dj_segfault's suggestion of a Factory with a table of handlers.
Or, wait -- is it just a web service you need to talk to? If so, there should be no reason your implementations of its datatypes can't be Adapters wrapping the input datatypes, or some intermediate object of your own.

Categories