Do method names always have to be verb? - java

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.

Related

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.

How should I handle basic functions in OOP?

In an OOP program, where would I put functions for basic operations?
For example, if I had a class that, in one of the functions needed code that could invert an array, I could just make a method called invertArray() within the class.
On the other hand, I could create a whole new Functions class, where I could dump all these basic functions like inverting an array into. However, with this approach, I would have to instantiate this class in pretty much every other class I use. In addition, it isn't really an "object," but more of a conglomeration of functions that don't belong anywhere else, which kind of defeats the purpose of "object-oriented" programming.
Which implementation is better? Is there a better implementation I should use?
Thanks in advance.
Edit: Should this kind of post even belong in Stack Overflow? If not, could you please guide me to a more appropriate Stack Exchange website? Thanks.
Depending on your language it can depend where you put things.
However, given your an example, an invertArray lives on an Array class. In some languages you might make an ArrayHelper or ArrayExtension class. But the principle is "invert" is something you want to tell an array.
You will generally find all your functions will generally live somewhere on some class and there will be a logical place for them.
It's generally not a good idea to make a class that holds a mishmash of functions. You can end up with things like "Math" which is a bunch of "static" functions ( they don't work on an object ) they simply do some calculation with parameters and return a result. But they are still grouped by the idea they are common mathmatical functions
As per your question is regarding Java:
if I had a class that, in one of the functions needed code that could invert an array, I could just make a method called invertArray() within the class.
Then yes you can do this, but if you are willing to implement OOPS concept in Java the you can also do :
I could create a whole new Functions class, where I could dump all these basic functions like inverting an array into.
For this part :
I would have to instantiate this class in pretty much every other class I use.
You can also create an interface as Java provides you this functionality where in you can just declare you functions and provide its implementation in their respective classes. This is also helpful if in case you want different functionality with same function then you can choose this way and you don't have to rewrite your function definitions again and again.
And, OOPS concept comes handy when your are dealing with big projects with n number of classes. It depends whether you are learning or implementing on projects.

Name for collection of command objects

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.

Is there a name for a java method considered as separate from any particular class?

This is a terminological question, which makes it hard to ask!
Let me give an example. Suppose I am writing a symbolic-differentiation algorithm. I have an abstract class Exp that is a superclass of a bunch of expression types (sums, integrals, whatever). There is an abstract method derivative such that e.derivative() is supposed to be the derivative of the expression e. All the concrete subclasses of Exp (imagine a whole hierarchy here) implement a derivative method that captures knowledge of how to differentiate expressions of that type. A given method will typically compute the derivative of an expression by combining derivatives of subexpressions.
The details of the example are not important. The important thing is that all of these scattered methods can be considered pieces of one (recursive) algorithm. This is not true of all methods, but it's true of many of them (and the use of overloading to reuse the same method name for fundamentally different operations is considered a Bad Idea). The question is, what is the term for 'derivative,' considered as a single function? It's not a method; in another language it would be a function, and the various clauses (what to do with sums, what to do with integrals) would be in the same place. I don't care which approach or languaage is better, or whether that style can be used in Java. I just want to know what term to use for 'derivative' considered as a single function or procedure (the idea is not limited to functional programming, nor is recursion a key feature). When I tell someone what I did today, I'd like to say "I tried to implement a symbolic-differentation __, but every algorithm I thought of didn't work." What goes in the blank?
I assume the same issue comes up for other OO languages, but Java is the one I'm most familiar with. I'm so familiar with it that I'm pretty sure there is no standard term, but I thought I would ask our fine battery of experts here before jumping to that conclusion.
That sounds like "normal" subtype polymorphism. The subclasses/implementations do the work but the interface is defined in a base-type. This "scatter" method is in contrast to say, the Visitor Pattern ("as good as Java gets") or Pattern Matching (not in Java) or a big manky switch/if-else controller. I'm not sure I really would call it anything else as an aggregate.
Addendum: you may find Are Scala case-classes a failed experiment? a nice read. In particular, the comments which talk about "column" vs. "row" organization and the "difference of locality" each approach has:
...in OO, you divide by rows. Each row is a module, called a class. All the functions pertaining to that data variant are grouped together. This is a reasonable way of organizing things, and it's very common. The advantage is that's easy to add a data variant ... However the disadvantage is that it's hard to add new functions that vary by data type. You have to go through every class to add a new method.
I'm not sure if this is what you're looking for but I think I can answer this in terms of design pattern terminology. Your example sounds vaguely like the GoF Strategy Pattern. Here is an example of the Strategy Pattern implemented in Java.
On the contrary, I think that "method" is the standard term for this in the Java context.
A polymorphic function can be applied to values of different types. The function may be implemented by more than one Java method.

Why is using a class as a struct bad practice in Java?

We recently had a code review . One of my classes was used so that I could return/pass more than one type of data from/to methods . The only methods that the class had were getters/setters . One of the team's members ( whose opinion I respect ) said that having a class like that is bad practice ( and not very OOP ) . Why is that ?
There's an argument that classes should either be "data structures" (i.e., focus on storing data with no functionality) or "functionality oriented" (i.e., focus on performing certain actions while storing minimal state). If you follow that argument (which makes sense but isn't always easy to do) then there is nothing necessarily wrong with that.
In fact, one would argue that beans and entity beans are essentially that - data containers with getters and setters.
I have seen certain sources (e.g., the book "clean code") arguing that one should avoid methods with multiple parameters and instead pass them as a single object with getters and setters. This is also closer to the "smalltalk model" of named parameters where order does not matter.
So I think that when used appropriately, your design makes sense.
Note that there are two separate issues here.
Is a "struct-like" class sensible?
Is creating a class to return multiple values from a method sensible?
Struct-like classes
An object class should -- for the most part -- represent a class of real-world objects. A passive, struct-like java bean (all getters and setters) may represent a real-world thing.
However, most real-world things have rules, constraints, behaviors, and basic verbs in which they engage. A struct-like class is rarely a good match for a real-world thing, it's usually some technical thing. That makes it less than ideal OO design.
Multiple returns from a method
While Python has this, Java doesn't. Multiple return values isn't an OO question, per se. It's a question of working through the language limitations.
Multiple return values may mean that an object has changed state. Perhaps one method changes the state and some group of getters return the values stemming from this state change.
To be honest, it sounds fine to me. What alternative did the reviewer suggest?
Following OOP "best practices" and all is fine, but you've got to be pragmatic and actually get the job done.
Using Value Objects like this (OO speak for 'struct') is a perfectly legitimate approach in some cases.
In general, you'll want to isolate the knowledge needed to operate upon a class into the class itself. If you have a class like this, either it is used in multiple places, and thus can take on some of the functionality in both of those places, or it is in a single place, and should be an inner class. If it is used in multiple ways, but in completely different ways, such that there is no shared functionality, having it be a single class is misleading, indicating a shared functionality where there is none.
However, there are often specific reasons for where these general rules may or may not apply, so it depends on what your class was supposed to represent.
I think he might be confusing "not very OOP" for bad practice. I think he expected you to provide several methods that would each return 1 value that was needed (as you will have to use them in your new class anyway that isn't too bad).
Note that in this case you probably shouldn't use getters/setters, just make the data public. No this is "not very OOP" but is the right way to do it.
Maybe Josh Bloch offers some insight into this here.

Categories