In Java, when is the interface Name (which extends CharSequence) useful? Why not just use final String instead? I do not see any classes that implement Name.
Alternatively, what I am interested is the use cases of Name, CharSequence, and the String class.
It is more than just a String.
In the description of the equals method it says:
Note that the identity of a Name is a function both of its content in
terms of a sequence of characters as well as the implementation which
created it.
So this implies that there is more to an object that implements Name than just its character representation. It also has to know about the implementation which created it.
If you want to just compare the content you have to use contentEquals.
But you are probably not going to be creating classes using this interface yourself. It is part of the Java language model.
To summarize the answer based on the comments: By #Mark Rotteveel
This is part of the package java.lang.model.element which is "Interfaces used to model elements of the Java programming language.". In other words, it is not general purpose. And there are implementations, but just not in a public API as these interfaces are the API (e.g. in Temurin 11, there are
com.sun.tools.javac.util.Name,
com.sun.tools.javac.util.SharedNameTable.NameImpl and
com.sun.tools.javac.util.UnsharedNameTable.NameImpl).
And it is more than just a string based on #rghome answer.
Moreover, the reason the modeling is also provided in the same language is: By #Zabuzard
It is mostly for the meta-aspects that Java provides, in particular the reflection API that allows you to inspect the code and retrieve meta-information about it, or to dynamically trigger stuff. For example call a method by its name, given by user input.
CharSequence is a very general interface, more so than String, and contrary to the obiquitous usage of String one could have used CharSequence instead, so one could pass a StringBuilder too.
However pro String (a class) counts its evident immutability and extra methods. Though the interface CharSequence itself does not have mutable functions too. As only StringBuilder and String are the most useful implementation, one may normally forget about using CharSequence.
Name is a dedicated interface for language modeling itself. It is a form of wrapping a value type (String here) in its own type for specific usage. Like wrapping a time String in a Time. Note that for a case-insensitive language the Name#equals could ignore the case (as in PascalName implements Name). The class/interface should not be used outside language modeling. In the model a Name may contain its declaration.
Related
Consider
String foo = s.toString();
for a non-null java.lang.String instance s.
Is this defined to return itself, or is it up to a particular Java implementation? Out of interest is a "deep copy" taken?
Examining my source code of my JDK affirms that s is returned, but does the JLS insist on that? I've been brought up to regard toString() as an arbitrary serialisation, perhaps representative of the object, but not necessarily so. For example, it's entirely plausible (in my opinion at least) that an implementation could surround the string in quotation characters.
You wouldn't find any guarantee in the JLS but you do have one in the javadoc:
This object (which is already a string!) is itself returned.
Yes. See Java Language Specification §1.4 – Relationship to Predefined Classes and Interfaces:
As noted above, this specification often refers to classes of the Java SE platform API. In particular, some classes have a special relationship with the Java programming language. Examples include classes such as Object, Class, ClassLoader, String, Thread, and the classes and interfaces in package java.lang.reflect, among others. This specification constrains the behavior of such classes and interfaces, but does not provide a complete specification for them. The reader is referred to the Java SE platform API documentation.
So the javadoc of those classes (which is the "Java SE platform API documentation") is normative and part of the overall language spec. And that states explicitly:
public String toString()
This object (which is already a string!) is itself returned.
There's no room for interpretation.
(It would break countless programs if they changed it to do anything different anyway.)
It returns itself
/**
* This object (which is already a string!) is itself returned.
*
* #return the string itself.
*/
public String toString() {
return this;
}
Looking at source code you can easily find this out.
I'm sure that we can't find Java language specification for each method's implementation. Just like any other Java class toString() method of String class just Returns a string representation of it's own.
Update :
Since your actual question is about why it is returning it self rather than a copy or some hack like quotes to make a new String, I'll slightly disagree on that. My reasons for the same (may be there are other good reasons than this) since you are invoking toString() method on actual string instance (s) itself, I see no harm here. If you want to play around you'll do that with s instance directly anyway.
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.
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.
This might be a very basic question, apologies if this was already asked.
Should toString() in Java be used for actual program logic or is it only for debugging/human reading only. My basic question is should be using toString() or write a different method called asString() when I need to use the string representation in the actual program flow.
The reason I ask is I have a bunch of classes in a web service that rely on a toString() to work correctly, in my opinion something like asString() would have been safer.
Thanks
Except for a few specific cases, the toString should be used for debugging, not for the production flow of data.
The method has several limitations which make it less suitable for use in production data flow:
Taking no parameters, the method does not let you easily alter the string representation in response to the environment. In particular, it is difficult to format the string in a way that is sensitive to the current locale.
Being part of the java.Object class, this method is commonly overridden by subclasses. This may be harmful in situations when you depend on the particular representation, because the writers of the subclass may have no idea of your restrictions.
The obvious exceptions to this rule are toString methods of the StringBuilder and the StringBuffer classes, because these two methods simply make an immutable string from the mutable content of the corresponding object.
It is not just for debugging/human reading only, it really depends on the context in which the object is being used. For example, if you have a table which is displaying some object X, then you may want the table to display a readable textual representation of X in which case you would usually implement the toString() method. This of course is a basic example but there are many uses in which case implementing toString() would be a good idea.
If a String object is immutable (and thus obviously cannot change its length), why is length() a method, as opposed to simply being public final int length such as there is in an array?
Is it simply a getter method, or does it make some sort of calculation?
Just trying to see the logic behind this.
Java is a standard, not just an implementation. Different vendors can license and implement Java differently, as long as they adhere to the standard. By making the standard call for a field, that limits the implementation quite severely, for no good reason.
Also a method is much more flexible in terms of the future of a class. It is almost never done, except in some very early Java classes, to expose a final constant as a field that can have a different value with each instance of the class, rather than as a method.
The length() method well predates the CharSequence interface, probably from its first version. Look how well that worked out. Years later, without any loss of backwards compatibility, the CharSequence interface was introduced and fit in nicely. This would not have been possible with a field.
So let's really inverse the question (which is what you should do when you design a class intended to remain unchanged for decades): What does a field gain here, why not simply make it a method?
This is a fundamental tenet of encapsulation.
Part of encapsulation is that the class should hide its implementation from its interface (in the "design by contract" sense of an interface, not in the Java keyword sense).
What you want is the String's length -- you shouldn't care if this is cached, calculated, delegates to some other field, etc. If the JDK people want to change the implementation down the road, they should be able to do so without you having to recompile.
Perhaps a .length() method was considered more consistent with the corresponding method for a StringBuffer, which would obviously need more than a final member variable.
The String class was probably one of the very first classes defined for Java, ever. It's possible (and this is just speculation) that the implementation used a .length() method before final member variables even existed. It wouldn't take very long before the use of the method was well-embedded into the body of Java code existing at the time.
Perhaps because length() comes from the CharSequence interface. A method is a more sensible abstraction than a variable if its going to have multiple implementations.
You should always use accessor methods in public classes rather than public fields, regardless of whether they are final or not (see Item 14 in Effective Java).
When you allow a field to be accessed directly (i.e. is public) you lose the benefit of encapsulation, which means you can't change the representation without changing the API (you break peoples code if you do) and you can't perform any action when the field is accessed.
Effective Java provides a really good rule of thumb:
If a class is accessible outside its package, provide accessor methods, to preserve the flexibility to change the class's internal representation. If a public class exposes its data fields, all hope of changing its representation is lost, as client code can be distributed far and wide.
Basically, it is done this way because it is good design practice to do so. It leaves room to change the implementation of String at a later stage without breaking code for everyone.
String is using encapsulation to hide its internal details from you. An immutable object is still free to have mutable internal values as long as its externally visible state doesn't change. Length could be lazily computed. I encourage you to take a look as String's source code.
Checking the source code of String in Open JDK it's only a getter.
But as #SteveKuo points out this could differ dependent on the implementation.
In most current jvm implementations a Substring references the char array of the original String for content and it needs start and length fields to define their own content, so the length() method is used as a getter. However this is not the only possible way to implement String.
In a different possible implementation each String could have its own char array and since char arrays already have a length field with the correct length it would be redundant to have one for the String object, since String.length() is a method we don't have to do that and can just reference the internal array.length .
These are two possible implementations of String, both with their own good and bad parts and they can replace each other because the length() method hides where the length is stored (internal array or in own field).