Java Enum type naming convention - java

What is the best practice of naming convention of enum
public enum SystemTypeEnum {
RRD, FFR, DDE
}
Currently the name is SystemTypeEnum. Is this ok or we should have name as SystemType
Would like to know best practice.

Disclaimer: I realize that my Answer can be considered opinionated, so my answer reflects my own experience.
I think it's better to rename to SystemType It's clear that its enum, all modern IDE show that. Following this logic, if you have, for example, interface
interface Calculator {
int plus(int a, int b);
int minus(int a, int b);
}
It should be renamed to CalculatorInterface - sounds weird, right?
Another example:
class Person {
String name;
int age;
}
Do you think its a good idea to rename it to PersonClass only because of its a class?
Bottom line, as I said, you can rely on IDE here - it will provide a visual hint for you for what it is.

Outcome
This is a highly opinion based topic, so I will try to keep this unbiased.
There are different standards and opinions and there is no very clear outcome to the discussion.
To my knowledge the most commonly used style is to not have a suffix or prefix.
Arguments
The discussion typically also includes pre- or suffixes for abstract classes and interfaces, not only enums. Also frequently seen are prefixes like E, A, I instead of suffix.
Some argue it does not add any useful additional information to the name and only clutters it. Some say it should not matter whether it is, lets say, and interface or a class. Some say it is the job of the IDE and not the name to indicate the type, for example with colors and icons. But there are also opinions in favor of that naming standard.
Style guidelines
A widely adopted style guideline is Googles style, quoting:
In Google Style, special prefixes or suffixes are not used. For example, these names are not Google Style: name_, mName, s_name and kName.
Another style that is commonly referred to is the style used in the JDK by the Java developers themselves, they also do not use a prefix or suffix.
But again, those are just some styles, there are also others.

Related

Should I avoid commonly used class names?

Some class names are so "generic" that they are often found in several different packages, including in libraries and application code. Some examples:
Comment
Component
Factory
Location
Region
In my IDE, attempting to auto-complete the import for a class like one of these summons several competing suggestions.
When naming classes, is it a good idea to avoid class names already used elsewhere?
For some of these examples, I would imagine that using such class name is discouraged because it is simply not meaningful enough (e.g. Factory), but I am wondering whether it is discouraged to use a class name because it is used (frequently) elsewhere.
You should use class names where they make the most sense for you. None of the names above that you've proposed are off limits, and there's no reason why you can't use them (assuming a language that supports namespaces and can avoid naming conflicts in this way).
However, you may consider drilling down to class names that are more specific and precise, which will better describe the meaning of the objects in your code. For example:
Instead of Comment: LineComment or BreakComment could easily be class names in a compiler project where you would like to create semantic blocks for comments.
Instead of Component: ListComponent, CalendarComponent, or ViewComponent make particular sense when implementing a UI library where you have class-based components.
Instead of Factory: PizzaFactory makes more sense if you're trying to make pizzas!
Instead of Location: GeographicLocation or SemanticLocation makes more sense when implementing a directions based navigation app, and you're trying to distinguish between '45 deg N, 77 deg W' and 'next to the pizza place'.
Region: CodeRegion could be used in a compiler, and GeographicRegion could be used in a Maps app.
If you're afraid to be specific, namespaces and packages help. However, there is nothing discouraging you from using the same name for a class as another package where it makes sense. The class names specifically aren't copyrighted, and most IDEs now are smart enough to make distinctions between what packages you're referring to when using autocompletion.
For the most part, specificity is helpful in assisting other developers to read your code, which every developer can appreciate!
Comment, Region, and Location seem fine. Personally, so subjectively, Component and Factory are definitely too common to use but objectively I can't think of any conventional reason not to use them as names. I'd definitely try and couple those names with their respective usage, for example; TaskFactory, WidgetComponent, ButtonFactory, etc.
Depends if we are talking about business or technical part.
In technical part: using common names is actually a way to let others know about the patterns used, Factory is a good example - when you see a class named like SomethingFactory, you can expect a Factory Pattern. It goes further to frameworks, libraries etc. - SomethingAutoConfiguration with Spring-Boot, SomethingEntity with JPA, I think with frontend frameworks (React, Angular) Component is a really common word. So ye, by all means, use them, as long as you use them correctly.
In business part: simple, if those words describe your business domain, then by all means use them. Don't try to invent some fancy names (or thesaurus!) just because the words seem common, it's your business domain - it's sacred.

Eclipse getter/setter generation strange behaviour depending on capitalization [duplicate]

if I have the following private member:
private int xIndex;
How should I name my getter/setter:
getXindex()
setXindex(int value)
or
getxIndex()
setxIndex(int value)
EDIT: or
getXIndex()
setXIndex(int value);
?
The correct answer is
getxIndex()
setxIndex(int value)
if you want them to be used as properties according to section 8.8: Capitalization of inferred names of the JavaBeans API specification (e.g. access them via ${object.xIndex} in a JSP.
In accordance with JavaBeans API specification from 1997
it should be as Thomas Einwaller describes:
// According to JavaBeans API specification
public int getxIndex() { return xIndex; }
public void setxIndex(int xIndex) { this.xIndex = xIndex; }
This is unfortunate, getx and setx are not words. In the rare case when this would form a word or acronym it would be disinformative, eg the method setiMessage most
likely has nothing to do with SETI.
Using the only valid measurement of code quality (WTFs per minute),
I assess that this is bad code.
If we modify this to follow the convention for
naming a method it would be:
// According to Java naming convention
public int getXIndex() { return xIndex; }
public void setXIndex(int xIndex) { this.xIndex = xIndex; }
Why does the JavaBeans specification violate the convention? It all comes down to this sentence of the JavaBeans specification:
However to support the occasional use of all upper-case names, we check if the first two characters of the name are
both upper case and if so leave it alone.
Exactly what kind of use of all upper-case names this refers to is unclear to me. Field names should, according to
convention, be camel cased. It seems
to me that we generate unconventional method names in order to support unconventional field names as decided by a
20+ year old document.
It should also be noted that even though it seems to be an overwhelming support for the JavaBeans specification in tools,
it is not exclusively used. Eg. Kotlin will not recognize xIndex as a property in the above example. Reversely, the
Kotlin property var xIndex = 0 will result in the Java methods getXIndex and setXIndex. This seems to be a bug
according to the JetBrains support, but I fail to see how they can fix that without making a breaking change.
Some tools that does support the JavaBeans specification has not always done so, eg Jackson
and Swagger Code Generator have been patched to conform to it.
Even though IntelliJ generate accessors according to the JavaBeans specification, the example
in the documentation differs from it. Probably because people don't know about the standard and naturally prefers the
normal method naming convention.
So when should we follow the JavaBeans specification? When property names should be inferred by accessors by tools that
rely on this standard, then we might want to use it. For instance, Jackson will rely
on the property xIndex being accessed through getxIndex and setxIndex methods unless we use annotations.
When should we avoid this standard? Per my recommendation: When the code should be read and understood by humans.
Because to not use proper camel casing when naming methods is disinformative.
If I would have it my way, we would use normal naming conventions, ie getXIndex and setXIndex. But, given the state
of things, the best solution I see is suggested by #vaxquis:
Name your field "indexX" or whatever else, your problem is solved... don't overcomplicate things - even if setxIndex
is the correct way for Beans, having method named setxIndex increases the WTF factor of the code without giving you
anything in return.
Any comments regarding the JavaBeans specification should, according the specification itself, be sent to
java-beans#java.sun.com.
Should be:
getXIndex()
setXIndex(final int xIndex)
Methods should be verbs, in mixed case with the first letter lowercase, with the first letter of each internal word capitalized.
You should use Introspector.decapitalize from package java.beans and you have no problem beacause it is compliant with java rules.
Eclipse ide automatically generates setters and getters as:
getxIndex()
setxIndex(int value)
Which is according to the java beans API specification.
I think getXindex() is the best way. The getter should start with 'get', followed by the member name, with its first letter capitalized. Also the latest conventions I heard of, say that we should avoid multiple capital letters one after another. For example getHTMLtooltip is wrong. it should be getHtmlTooltip instead. Also you should try to make all your members final and there should not be a need of setters, since the class will be immutable ;)

Awkward naming convention of getter of Delegated boolean existential property

Please refer to Naming conventions for java methods that return boolean(No question mark)
to make a comparison about what I am NOT asking.
My question concerns properties derived from delegates embedded in a container object.
While the setters of all properties regardless of type is easily and conveniently prefixed with "set" (e.g. setValueRequired(blah) ), there are various types of boolean properties each whose getter is conventionally named {verb}{PropertyName}. e.g.,
the most common is existential, by convention is prefixed by "is". e.g. isEmpty().
possessive property, prefixed by "has", e.g. hasValue().
affirming necessity, prefixed by "requires", e.g. requiresResize(), providesResize().
By far, most property getters are somehow converted into existential properties. e.g. isRequireResize, isValued, etc. Therefore, my question concerns only expressing existential boolean properties (of a delegate class).
Let us say the container class is Printer, which contains the class Queue.
class Queue {
boolean empty, resettable, resizable;
}
class Printer {
Queue queue;
}
How then should Printer name its delegated properties for Queue? Because the following, by English comprehension convention, is awkward, as they sound like asking a question, not affirming its status.
isQueueEmpty()
isQueueResettable()
isQueueResizable()
The boolean property should be affirmative and not sound like asking a question. Therefore for comprehensible English, they should be
queueIsEmpty()
queueIsResettable()
queueIsResizable()
Or alternatively, could be
isEmptyQueue()
isResettableQueue()
isResizableQueue()
However, automated delegate method code generators invariably generate names isQueueEmpty(), isQueueResettable(), isQueueResizable().
That is awkward when placed into an if
if (isQueueResettable() && !isQueueEmpty()) resetQueue();
As this sounds better
if (isResizableQueue() && !isEmptyQueue()) resetQueue();
~
My Questions actually
If there a JSR recommending naming conventions of property getters? What is it? Certainly there must be, otherwise wouldn't all the code generators out there be limping around with ambiguous conventions?
If there is, does the JSR have recommendation for delegated boolean existential property getters?
If not JSR, at least some form of RFCs in Apache, JBoss, Eclipse, etc?
Don't you think the convention I recommend is better than code generators creating questioning getters?
I don't know much about JSR, but I am just trying to give my understanding.
You say isResettableQueue() sounds better than isQueueResettable to you( and probably to many others).
When you break up isResettableQueue() into is - Resettable - Queue, the main object(thing) about which you are talking comes into context at the last (in this case Queue).
But when you break up isQueueResettable() into is - Queue - Resettable, the main object(thing) about which you are talking comes into context at early stage (at least not at the last.
So you can tell Ok now I am talking about Queue for which I am checking if it is empty
Method names should start with a verb, so queueIsEmpty shouldn't be used.
I can't find any articles about naming conventions that mention this particular case, but the most natural choice would still be isQueueEmpty. isEmptyQueue would refer to this instead of this.queue. It would return whether "This object is an empty queue" instead of "This object's queue is empty".
Oracle also uses method names on the form isQueueEmpty.
Here are relevant method names defined in AbstractButton, JFrame, JTable and their super-classes:
isAlwaysOnTopSupported, isBackgroundSet, isBorderPainted, isCellEditable, isCellSelected, isColumnSelected, isContentAreaFilled, isCursorSet, isFocusPainted, isFocusTraversalPolicySet, isFontSet, isForegroundSet, isMaximumSizeSet, isMinimumSizeSet, isOptimizedDrawingEnabled, isPreferredSizeSet isRequestFocusEnabled, isRolloverEnabled, isRootPaneCheckingEnabled, isRowSelected

Questions about Java code styles [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
So I have seen a lot of different coding styles, but I'm only going to talk about two big ones. I use a style where I just name everything like their class name when used in a general sense, like this:
String str = "This is some text";
But over at Java Practices, I see a style where they will put an 'I' in front of Interfaces class names, or they put 'f' or 'a' in front of object names. Take this snippet from "Don't subclass JDialog or JFrame"':
/**
Constructor.
<P>Called when adding a new {#link Movie}.
*/
MovieView(JFrame aParent) {
fEdit = Edit.ADD;
buildGui(aParent, "Add Movie");
fStandardDialog.display();
}
Why do programmers code in this style? Do a lot of people use it? And also, do professional programmers use this style?
Thanks in advance :)
This my personal opinion.
I prefer not to use prefixes on interface (or anything else for that matter). I just prefer to call it what it is. Interfaces are meant to represent an object (or part of it) without making any implication towards it's actual implementation.
Say you have a Car interface. And AudiA4 could be an implementation of that car. If you just bought a new Audi A4, you say, "I bought a new AudiA4" to those you think care about the kind of car you bought. To others, you can say "I bought a new Car". Certainly, you never say, I bought a new IAudiA4 or a new ICar.
The JFrame naming came about because it's a Swing Frame and Swing came after AWT (the original Java windowing toolkit, which already had a Frame class). Since both AWT and Swing where available at the same time, they used the 'J' prefix to demarcate the toolkits (note that JFrame extends Frame, btw). They could have called it SwingFrame but the 'J' prefix was apparently a good choice to represent the Swing package. So basically this prefix is just a naming choice, not a convention similar to the 'I' for interfance (or Impl suffix for implementations you see sometimes as well)
My point is you always have to name your classes and interface according to exactly what they represent. No more, no less. No point having a CarImpl class. Who cares that it's an implementation. Which implementation is it? Why does it need its own class? What more do I get when I use a CarImpl? What happens when I make a second implementation, I call it CarImpl2? All this is very constraining and doesn't bring much value.
Call it what it is. That's the only rule I'd set forth.
All this being said, the Eclipse project, amongst many others, does indeed use the I-for interface notation (WIKI). But it's their choice. I've seen professionals use it as well. I don't like it, but generally speaking, I respect the team's naming convention.
There is a book about such things - Code Complete by Steve McConnell
I might be wrong but the only universal convention I've seen when naming Java variables is using Camel-Case notation, that's regarding the format of the name.
As for the name itself, I've always found useful to name the variables according to what they actually are. In your String example, although you mention this would be in a general purpose variable, I would still give it a more meaningful name, like:
String message = "This is some text";
Or:
String msg = "This is some text";
Some of the Java libraries I've seen source code from tend to be quite verbose when naming variables, others just use single letter names when the variable is used in a reduced context:
public Rectangle setLocation(Point p) {
return setLocation(p.x(), p.y());
}
I think the main goal when naming variables (or anything else for that matter) is always to communicate in the best way possible the intent of what you were trying to do.
Code styles help make it easier for developers to read and understand each others code. Java conventions prescribe the use of short and descriptive identifiers, but unfortunately short and descriptive cannot always be achieved together so you may have to compromise shortness for clarity hence: atmosPres - still clear but short, atmosphericPressure - this can't be mistaken, atm - because everyone just knows ATM, right?, ap - WTF?
I first encountered the practice of prefixing variable names with a three letter type identifier while developing programs in C# - it helps the reader know what data type is contained in a variable without having to look for its declaration (due to short memory or maybe laziness?). Arrays are also prefixed with I e.g IList to distinguish them from other data types (and for what purpose, I just dunno).
For me, the worst code conventions are in C++ (if indeed there are any at all) - there's a mix of case types for data types and variables, conflicting method and function naming styles and endless cryptic abbreviation which all make it hard for non-regular C++ coders to read and understand C++ code.
What you're describing is sometimes referred to as "Hungarian notation", though it's not "Hungarian" in the truest sense of the term.
Basically, the idea is to differentiate between different classes of variables -- instance variables, local variables, parameters, et al. This serves two basic purposes:
It helps avoid name collisions, where, say, there might naturally (using "descriptive" variable naming) be an instance variable ralphsLeftFoot and a local variable ralphsLeftFoot. Using a prefix allows the two to co-exist, and, especially in languages where the local might (without warning message) "hide" the instance variable, prevents unintended changes in semantics from such collisions.
It makes the scope of variables obvious, so that, during maintenance, one does not accidentally assume that a local variable has instance scope or vice-versa.
Is this approach worthwhile? Many developers use a subset of the scheme, apparently to good effect. For instance, many Objective-C developers will name the instance variable behind a "property" with a leading "_" character, to clearly differentiate between the two and to avoid accidentally using the instance variable when the property was intended.
Likewise, many developers in a number of languages will prefix instance variables with a letter (often "m") to differentiate them from "normal" local/parameter variables.
What's probably most important is to pick a style that you (and your team) likes and stick with it. If the team likes the prefixes then use the prefixes. If the team prefers something else, stick with that. Of course, changing preferences, when a better choice is "revealed" to you, is OK, but don't switch back and forth willy-nilly.
So I have seen a lot of different coding styles, but I'm only going to
talk about two big ones. I use a style where I just name everything
like their class name when used in a general sense, like this:
String str = "This is some text";
That is awful. Imagine if someone were reading your code, trying to understand what it was doing, and they came across a variable named str. It doesn't convey any meaning to the person who has to read this code as to your intentions.
Conventions are used by and for people to improve readability, and thus the overall quality of software. Without a convention, any project that has more than one developer will suffer from varying styles that will only hurt the readability of the code. If you want to know what professionals do, look around on the internet for various conventions.

Absence of property syntax in Java

C# has syntax for declaring and using properties. For example, one can declare a simple property, like this:
public int Size { get; set; }
One can also put a bit of logic into the property, like this:
public string SizeHex
{
get
{
return String.Format("{0:X}", Size);
}
set
{
Size = int.Parse(value, NumberStyles.HexNumber);
}
}
Regardless of whether it has logic or not, a property is used in the same way as a field:
int fileSize = myFile.Size;
I'm no stranger to either Java or C# -- I've used both quite a lot and I've always missed having property syntax in Java. I've read in this question that "it's highly unlikely that property support will be added in Java 7 or perhaps ever", but frankly I find it too much work to dig around in discussions, forums, blogs, comments and JSRs to find out why.
So my question is: can anyone sum up why Java isn't likely to get property syntax?
Is it because it's not deemed important enough when compared to other possible improvements?
Are there technical (e.g. JVM-related) limitations?
Is it a matter of politics? (e.g. "I've been coding in Java for 50 years now and I say we don't need no steenkin' properties!")
Is it a case of bikeshedding?
I think it's just Java's general philosophy towards things. Properties are somewhat "magical", and Java's philosophy is to keep the core language as simple as possible and avoid magic like the plague. This enables Java to be a lingua franca that can be understood by just about any programmer. It also makes it very easy to reason about what an arbitrary isolated piece of code is doing, and enables better tool support. The downside is that it makes the language more verbose and less expressive. This is not necessarily the right way or the wrong way to design a language, it's just a tradeoff.
For 10 years or so, sun has resisted any significant changes to the language as hard as they could. In the same period C# has been trough a riveting development, adding a host of new cool features with every release.
I think the train left on properties in java a long time ago, they would have been nice, but we have the java-bean specification. Adding properties now would just make the language even more confusing. While the javabean specification IMO is nowhere near as good, it'll have to do. And in the grander scheme of things I think properties are not really that relevant. The bloat in java code is caused by other things than getters and setters.
There are far more important things to focus on, such as getting a decent closure standard.
Property syntax in C# is nothing more than syntactic sugar. You don't need it, it's only there as a convenience. The Java people don't like syntactic sugar. That seems to be reason enough for its absence.
Possible arguments based on nothing more than my uninformed opinion
the property syntax in C# is an ugly
hack in that it mixes an
implementation pattern with the
language syntax
It's not really necessary, as it's fairly trivial.
It would adversly affect anyone paid based on lines of code.
I'd actually like there to be some sort of syntactical sugar for properties, as the whole syntax tends to clutter up code that's conceptually extremely simple. Ruby for one seems to do this without much fuss.
On a side note, I've actually tried to write some medium-sized systems (a few dozen classes) without property access, just because of the reduction in clutter and the size of the codebase. Aside from the unsafe design issues (which I was willing to fudge in that case) this is nearly impossible, as every framework, every library, every everything in java auto-discovers properties by get and set methods.They are with us until the very end of time, sort of like little syntactical training wheels.
I would say that it reflects the slowness of change in the language. As a previous commenter mentioned, with most IDEs now, it really is not that big of a deal. But there are no JVM specific reasons for it not to be there.
Might be useful to add to Java, but it's probably not as high on the list as closures.
Personally, I find that a decent IDE makes this a moot point. IntelliJ can generate all the getters/setters for me; all I have to do is embed the behavior that you did into the methods. I don't find it to be a deal breaker.
I'll admit that I'm not knowledgeable about C#, so perhaps those who are will overrule me. This is just my opinion.
If I had to guess, I'd say it has less to do with a philosophical objection to syntactic sugar (they added autoboxing, enhanced for loops, static import, etc - all sugar) than with an issue with backwards compatibility. So far at least, the Java folks have tried very hard to design the new language features in such a way that source-level backwards compatibility is preserved (i.e. code written for 1.4 will still compile, and function, without modification in 5 or 6 or beyond).
Suppose they introduce the properties syntax. What, then does the following mean:
myObj.attr = 5;
It would depend on whether you're talking about code written before or after the addition of the properties feature, and possibly on the definition of the class itself.
I'm not saying these issues couldn't be resolved, but I'm skeptical they could be resolved in a way that led to a clean, unambiguous syntax, while preserving source compatibility with previous versions.
The python folks may be able to get away with breaking old code, but that's not Java's way...
According to Volume 2 of Core Java (Forgotten the authors, but it's a very popular book), the language designers thought it was a poor idea to hide a method call behind field access syntax, and so left it out.
It's the same reason that they don't change anything else in Java - backwards-compatibility.
- Is it because it's not deemed important enough when compared to other possible improvements?
That's my guess.
- Are there technical (e.g. JVM-related) limitations?
No
- Is it a matter of politics? (e.g. "I've been coding in Java for 50 years now and I say: we don't need no steenkin' properties!")
Most likely.
- Is it a case of bikeshedding?
Uh?
One of the main goals of Java was to keep the language simple.
From the: Wikipedia
Java suppresses several features [...] for classes in order to simplify the language and to prevent possible errors and anti-pattern design.
Here are a few little bits of logic that, for me, lead up to not liking properties in a language:
Some programming structures get used because they are there, even if they support bad programming practices.
Setters imply mutable objects. Something to use sparsely.
Good OO design you ask an object to do some business logic. Properties imply that you are asking it for data and manipulating the data yourself.
Although you CAN override the methods in setters and getters, few ever do; also a final public variable is EXACTLY the same as a getter. So if you don't have mutable objects, it's kind of a moot point.
If your variable has business logic associated with it, the logic should GENERALLY be in the class with the variable. IF it does not, why in the world is it a variable??? it should be "Data" and be in a data structure so it can be manipulated by generic code.
I believe Jon Skeet pointed out that C# has a new method for handling this kind of data, Data that should be compile-time typed but should not really be variables, but being that my world has very little interaction with the C# world, I'll just take his word that it's pretty cool.
Also, I fully accept that depending on your style and the code you interact with, you just HAVE to have a set/get situation every now and then. I still average one setter/getter every class or two, but not enough to make me feel that a new programming structure is justified.
And note that I have very different requirements for work and for home programming. For work where my code must interact with the code of 20 other people I believe the more structured and explicit, the better. At home Groovy/Ruby is fine, and properties would be great, etc.
You may not need for "get" and "set" prefixes, to make it look more like properties, you may do it like this:
public class Person {
private String firstName = "";
private Integer age = 0;
public String firstName() { return firstName; } // getter
public void firstName(String val) { firstName = val; } // setter
public Integer age() { return age; } // getter
public void age(Integer val) { age = val; } //setter
public static void main(String[] args) {
Person p = new Person();
//set
p.firstName("Lemuel");
p.age(40);
//get
System.out.println(String.format("I'm %s, %d yearsold",
p.firstName(),
p.age());
}
}

Categories