Breaking java generics naming convention? [duplicate] - java

This question already has answers here:
Generic type parameter naming convention for Java (with multiple chars)?
(5 answers)
Closed 7 years ago.
I have an interface whose declaration is as follows:
/**
* #param T - the type of entity.
* #param C - the type of entity container will be returned.
*/
public interface FindByNamedQuery<T extends Serializable, C extends Collection<T>> extends Command {
C executeNamedQuery(String namedQuery);
}
I wonder if I can (should) break the Java naming convention to do this:
public interface FindByNamedQuery<ENTITY_TYPE extends Serializable, RETURNED_CONTAINER extends Collection<ENTITY_TYPE>> extends Command {
RETURNED_CONTAINER executeNamedQuery(String namedQuery);
}

I am beginning to disagree with the single-character convention, after using it since the mid-1990s.
I find the readable names more readable. This is helpful in understanding both the implementation and interface of generic types.
The ambiguity problem seems overstated for Java. Few class names are all-uppercase. Constants are not used in the same context as class names.
It's true that the #param JavaDoc elements can provide a longer description. But it's also true that the JavaDocs are not necessarily visible. (For example, there's a content assist in Eclipse that shows the type parameter names.)
For example, compare :
public final class EventProducer<L extends IEventListener<E>,E>
implements IEventProducer<L,E> {
to:
public final class EventProducer<LISTENER extends IEventListener<EVENT>,EVENT>
implements IEventProducer<LISTENER, EVENT> {
Although the single-character names have been recommended as a convention by Sun/Oracle, conventions can be changed. The consequences of challenging this convention are minor. If you and your team prefer meaningful names for your type parameters, I personally would go for it.
Edit (2015)
Google style for Java allows both single-letter names and multi-character class-like names ending in T.
5.2.8 Type variable names
Each type variable is named in one of two styles:
A single capital letter, optionally followed by a single numeral (such as E, T, X, T2)
A name in the form used for classes (see Section 5.2.2, Class names), followed by the capital letter T (examples: RequestT,
FooBarT).

I wonder if I can (should) break the java naming convention to do this:
No, this should be avoided as it becomes easier to confuse the type parameters with constants and other identifiers.
Here's a quote from the official trail on generics:
Type Parameter Naming Conventions
By convention, type parameter names are single, uppercase letters. This stands in sharp contrast to the variable naming conventions that you already know about, and with good reason: Without this convention, it would be difficult to tell the difference between a type variable and an ordinary class or interface name.
The most commonly used type parameter names are:
E - Element (used extensively by the Java Collections Framework)
K - Key
N - Number
T - Type
V - Value
S,U,V etc. - 2nd, 3rd, 4th types
You'll see these names used throughout the Java SE API and the rest of this tutorial.

Using TDescription is pretty common in C#. It maintains the T name but is also descriptive at the same time, like so:
public interface FindByNamedQuery<
TEntityType extends Serialiazble,
TReturnedContainer extends Collections<TEntityType>> extends Command
{
TReturnedContainer executeNamedQuery(String namedQuery);
}
As others have said ALL_CAPS almost always indicates a constant.
IMO, "it would be difficult to tell the difference between a type variable and an ordinary class or interface name." does not apply here, because the T prefix easily identifies it as a type variable.
Again, this is C# but see MSDN: Naming Conventions For Generics
In all other cases, the official
Microsoft guidelines for generic
naming conventions are:
Name generic type parameters with descriptive names, unless a single
letter name is completely self
explanatory and a descriptive name
would not add value.
public interface ISessionChannel<TSession>
{...}
public delegate TOutput Converter<TInput,TOutput>(TInput from);
Consider indicating constraints placed on a type parameter in the name of parameter. For example, a parameter constrained to ISession may be called TSession.

The compiler might not complain, but your teammates might not appreciate you using what looks to be a constant in a place where they're expecting a type parameter.

I think this is the gripe of many people using generics. I don't quite agree with Sun's statement that if you use a full fledged name then it will confuse with an existing class name or something else. In that case we can start the placeholder name with a dollar like this:
public class HashMap<$Key,$Value> implements Map<$Key,$Value>{}
No one in their sane mind names a class starting with a dollar sign. And a dollar sign also is used to denote a placeholder many templating languages velocity, struts, spring, etc. I think this is the way to go.
I have got more details about this and the reasoning behind not having to use a single letter notation in my blog post if anyone is interested.
http://readsethu.wordpress.com/2012/05/23/a-generic-class-and-why-is-it-confusing/

Like Allen before, my advice comes more from C# (which I use extensively since 5 months) than Java (which I played with, but it never went very far...), but I find Java and C# code quite similar in spirit (that is, when compared by, say, C++)
Anyway, when using a C#/Java generic (or a C++ template) on a simple type, I usually use T:
// C++
template<typename T>
class MyClass { /* ... */ } ;
// C#
public MyClass<T> { /* etc. */ }
// Java
public MyClass<T> { /* etc. */ }
Usually, the type T goes with the class, so there is no need to describe it more.
But when really describing the type adds to the code clarity, I do it.
Or when I have two or more types in the same generic/template declaration, it helps to make the difference between two types. For example (real life example in C#) :
// C++
template<typename T_Data, typename T_Underlying>
class MyClass { /* ... */ } ;
// C#
public MyClass<T_Data, T_Underlying> { /* etc. */ }
// Java
public MyClass<T_Data, T_Underlying> { /* etc. */ }
This way, it is easy to make the difference between the two typenames in the code, where T and U are, well... kinda anonymous: For those using Visual C++, going in debug inside Dinkumware's STL code, full of T, _U, and other mono-letter typenames can be quite frustrating... I guess the same goes for C# or Java code.
You will note that in each case (C++, Java or C#), I don't follow the convention somewhere in my type namings: The reason is that sometimes, you just have to try something else instead of following the herd, even if in the end, you'll find you're wrong.
In the current case, the violation of naming convention is not critical (there are worst problems in Java than this petty crime), and at the very last, you'll learn personally and exactly WHY it is wrong, instead of quoting old documents.
And if you find in the end you're right, well...

I would name type variables similar to types, in camel casing, but prefixed with "_".
public interface FindByNamedQuery
<_EntityType extends Serialiazble,
_ReturnedContainer extends Collections<_EntityType>>
extends Command
{
_ReturnedContainer executeNamedQuery(String namedQuery);
}

Related

Java naming guide (specific class type naming - not conventions)

(This has nothing to do with Java conventions)
I'm looking for a guide that can help me understand how to name classes that function in certain ways.
I have looked online and read on various websites about this; but, all I learned is what not to do. i.e lower casing/dashes/dollar-signs.
But what I really want to know is how to name classes like these:
(Looking through similar projects I see that people named it "Module")
In this example, I will be naming them "Function".
public class HouseButtonsFunction extends ButtonSwitchFunction{
#Override
public void interact(Person p, Object...args){
//if person turns a light switch or open-garage switch
}
}
public class CarButtonsFunction extends ButtonSwitchFunction{
#Override
public void interact(Person p, Object...args){
//if person turns on ignition or roof lights
}
}
There are also superclasses like
PersonInteractionFunction
that would deal with things like:
PersonWalkingFunction extends PersonInteractionFunction
PersonSittingDownFunction extends PersonInteractionFunction
PersonDrivingFunction extends PersonInteractionFunction
So is "Function" the correct word here?
Where can I find out the correct nomenclature?
I suggest you to read the classic an most famous document that was written about naming which is called "Ottinger's Rules for Variable and Class Naming".
It was written by Tim Ottinger back in 1997 and it is still relevant as it was written today.
I would also suggest you to read the books Clean Code written by Robert C. Martin (Uncle Bob) and Implementation Patterns written by Kent Beck
I would use neither "Module" nor "Function" here.
"Module" is associated with a storage. For instance, it can be a class that holds a collection or gathers information about classes that can be logically grouped together.
"Function" is a means to transform something into something else. For example, a Function<Person, Rabbit> turns a human into a rabbit.
I would go with the word "Action" since you defined a single method interact.
There is no rule/conventions about how to name your class and methods. You have to follow the common sense : Name things explicitly so you and others can understand what it is and what it does
As example, for the case of a button in a house, with a function that interact this button. You can think of different valid naming. The class could be named HouseButtonFunction or HouseButtonAction, etc. And the method could be named interact() or action(), etc. The difference depend on what does exactly your method. If it toggles something, use toggle(). Use the one you find the most understandable and the most explicit. In your case, personnaly, since your class define the interaction of this button, I would suggest to name it HouseButtonInteraction
In all the case, I strongly recommend to comment your stuff so there is no more possible confusion.
/**
* This method is called when a person interact with the House button.
* This method will action the given object
* #param p : the person that interact with the house button
* #param o : the object to action
*/
public void interact(Person p, Object o) { ... }
Also try to always be consistent in your naming. i.e. If for the house button you name the class HouseButtonFunction and the method interact. Do not change the naming for the car button :
//not to do !!
class : CarButtonAction
method : actionObject()
//To do
class : CarButtonFunction
method : interact()
Ideally the name of the class should be a noun which is specific and is easy to understand to someone reading the code. Ending the class name with 'Function' is fine considering the super class seems to be named Function as well. But if you can rename the super class i would name them ending with Handler. Like
PersonWalkingHandler
PersonSittingDownHandler
PersonDrivingHandler
etc
There is no hard rule as many stated in comments. Naming convention is a best practice so when all developers follow a certain naming standard then they can easily correlate and understand code effectively, otherwise it's cumbersome task to build relation.
In general practice a Class should be referred to Noun where as methods refer to action so those are associated with verbs.
In above case, I would suggest something like this..
HouseButtonsFunction => House or HouseBotton
ButtonSwitchFunction => Switch or SwitchBotton
CarButtonsFunction => CarButton
PersonWalkingFunction => Walker
PersonSittingDownFunction => Sitter
PersonDrivingFunction => Driver etc..
Note that it all depends on naming convention you follow..

Constructor name and class name are the same in Java. Why? [duplicate]

This question already has answers here:
Why constructors will always have same name as of class and how they are invoked implicitly?
(7 answers)
Closed 8 years ago.
Please give me a logical answer of naming a class and constructor with same name. Why we cannot choose a different name other than class name for a constructor?
class Temp
{
Temp()
{
}
};
Because this syntax does not require any new keywords. Aside from that, there is no good reason.
To minimize the number of new keywords, I didn't use an explicit syntax like this:
class X {
constructor();
destructor();
}
Instead, I chose a declaration syntax that mirrored the use of constructors.
class X {
X();
~X();
This may have been overly clever. [The Design And Evolution Of C++, 3.11.2 Constructor Notation]
Constructor name being same as class name is simply a convention. A logical one too - consider the objects could be constructed like this also
Temp t = Temp();
It might have been called constructor() but then if you are looking at only snippet you wouldn't know what is it constructing?
According to the standard which defines the C++ language, a constructor does not have a name, at least not in the sense of an identifier which becomes declared by a declaration (a declarator-id). It is an anonymous function declared with a particular syntax, and referenced only under certain circumstances by more special syntax. In other contexts, the same term Temp::Temp refers to class Temp itself.
The constructor is declared using a member declaration naming the immediate injected-class-name. It may be referenced by an injected-class-name or other type-name used with the :: punctuation (a nested-name-specifier) in the form type::type, with the last two ::-delimited parts being the same token, in particular contexts such as delegating and inheriting constructors.
The reason for all this is that you cannot take a reference to a constructor, such as to get a function pointer to it or call it without creating a new object. Constructors are intrinsically tied to object lifetimes.
Historically, constructors evolved from factory functions, which returned initialized object of a given type. This pattern, where function names may alias types and constructors are merely convention, may still be seen in some languages. The current syntax evolved from something like what you might see in JavaScript. Some early C++ compilers (thinking about THINK C, not sure about earliest versions of Cfront) did not treat constructors as members at all.

What are these notations in class diagrams?

I know basics of UML and java's OO interpretations using class diagrams. But after looking at this class, I felt weird. What are the member variables and what do they represent in the actual language? I guessed the first one which is a boolean type (If I'm right), but what are the other member variables especially those which take some arguments? Any help would be appreciated. Thanks
This diagram you include is not strict uml. From what i can understand it means the following:
You have a class called ElectricFan
Your class has the following member variables (power, speed, maxSpeed, type, etc). In parenthesis i guess that the author has included the values applicable to each member variable.
Also, the author includes the methods that are applicable in this class (i.e. switchOnOff(), changeSpeed(), etc).
An important piece of information that the author doesn't include is the visibility and type of the member variables as well method arguments and return types.
If you are interested in learning more about UML you could start by reading Marting Fowler's UML distilled (http://www.amazon.com/UML-Distilled-Standard-Modeling-Language/dp/0321193687).
The values given in brackets are not arguments, instead they seem like enumerator types.
As far as the speed parameter is concerned it looks like an unsigned int.

Generic type parameter naming convention for Java (with multiple chars)?

In some interfaces I wrote I'd like to name generic type parameters with more than one character to make the code more readable.
Something like....
Map<Key,Value>
Instead of this...
Map<K,V>
But when it comes to methods, the type-parameters look like java-classes which is also confusing.
public void put(Key key, Value value)
This seems like Key and Value are classes. I found or thought of some notations, but nothing like a convention from Sun or a general best-practice.
Alternatives I guessed or found...
Map<KEY,VALUE>
Map<TKey,TValue>
Oracle recommends the following in Java Tutorials > Generics > Generic Types:
Type Parameter Naming Conventions
By convention, type parameter names are single, uppercase letters. This stands in sharp contrast to the variable naming conventions that you already know about, and with good reason: Without this convention, it would be difficult to tell the difference between a type variable and an ordinary class or interface name.
The most commonly used type parameter names are:
E - Element (used extensively by the Java Collections Framework)
K - Key
N - Number
T - Type
V - Value
S,U,V etc. - 2nd, 3rd, 4th types
You'll see these names used throughout the Java SE API and the rest of this lesson.
I'd stick to it to avoid the confusion among the developers and possible maintainers.
Append Type
A good discussion can be found in the comments on the DZone page, Naming Conventions for Parameterized Types.
See the comment by Erwin Mueller. His suggestion makes perfect obvious sense to me: Append the word Type.
Call an apple an apple, a car a car. The name in question is the name of a data type, right? (In OOP, a class essentially defines a new data type.) So call it a “Type”.
Mueller’s example, drawn from the original post’s article:
public interface ResourceAccessor < ResourceType , ArgumentType , ResultType > {
public ResultType run ( ResourceType resource , ArgumentType argument );
}
Append T
A duplicate Question provides this Answer by Andy Thomas. Note the excerpt from Google’s style guide that suggests a multi-character type name should end in a single uppercase T.
Yes, you can use multi-character names for type variables, as long as they are clearly distinguished from class names.
This differs from the convention suggested by Sun with the introduction of generics in 2004. However:
More than one convention exists.
Multi-character names are consistent with other Java styles, such as Google’s style for Java.
The readable names are (surprise!) more readable.
Readability
In some interfaces I wrote I’d like to name generic type parameter with more than one character to make the code more readable.
Readability is good.
Compare:
public final class EventProducer<L extends IEventListener<E>,E>
implements IEventProducer<L,E> {
to:
public final class EventProducer<LISTENER extends IEventListener<EVENT>,EVENT>
implements IEventProducer<LISTENER, EVENT> {
or, with Google’s multi-character convention:
public final class EventProducer<ListenerT extends IEventListener<EventT>,EventT>
implements IEventProducer<ListenerT, EventT> {
public final class EventProducer<ListenerT extends IEventListener<EventT>,EventT>
implements IEventProducer<ListenerT, EventT> {
Google style
The Google Java Style Guide allows both single-letter names and multi-character class-like names ending in T.
5.2.8 Type variable names
Each type variable is named in one of two styles:
A single capital letter, optionally followed by a single numeral (such as E, T, X, T2)
A name in the form used for classes (see Section 5.2.2, Class names), followed by the capital letter T (examples: RequestT, FooBarT).
Issues
“Without this convention, it would be difficult to tell the difference between a type variable and an ordinary class or interface name.” – from the Oracle tutorials, “Generic types”
Single-character names are not the only way to distinguish type parameters from class names, as we’ve seen above.
Why not just document the type parameter meaning in the JavaDoc?
It’s true that the #param JavaDoc elements can provide a longer description. But it’s also true that the JavaDocs are not necessarily visible. (For example, there’s a content assist in Eclipse that shows the type parameter names.)
Multi-character type parameter names don’t follow the Oracle convention!
Many of Sun’s original conventions are followed nearly universally in Java programming.
However, this particular convention is not.
The best choice among competing conventions is a matter of opinion. The consequences of choosing a convention other than Oracle’s in this case are minor. You and your team can choose a convention that best meets your needs.
You can use javadoc to at least give users of your generic class a clue. I still don't like it (I agree with #chaper29) but the docs help.
eg,
/**
*
* #param <R> - row
* #param <C> - column
* #param <E> - cell element
*/
public class GenericTable<R, C, E> {
}
The other thing I have been known to do is use my IDE to refactor a class breaking the convention. Then work on the code and refactor back to single letters. Makes it easier for me anyway if many type parameters are used.
The reason why the official naming convention reccommends using single letter is the following:
Without this convention, it would be difficult to tell the difference
between a type variable and an ordinary class or interface name.
I think with modern IDEs that reason is no longer valid as eg. IntelliJ Idea shows generic type parameters with different colors than regular classes.
Code with generic type as displayed in IntelliJ Idea 2016.1
Because of that distinction I use longer descriptive names for my generic types, with same convention as regular types. I avoid adding prefixes and suffixes such as T or Type as I consider them unnecessary noise and no longer needed to visually distinguish generic types.
Note: As I am not a user of Eclipse or Netbeans, I do not know whether they offers a similliar feature.

Java methods that look like: public static <F extends Field<F>> DenseVector<F> valueOf(F... elements)...what are they?

So, I'm looking through a java library (JScience) after someone here thoughfully pointed me towards it for getting Vectors (mathematical ones, that is) in java.
Unfortunately, I've never seen anything in my life before like:
public static <F extends Field<F>> DenseVector<F> valueOf(F... elements)
as a method you can call in the DenseVector class. What...does that even mean. Is it returning a "<F extends Field<F>>" (and if so, why does Eclipse think it's an input?)
http://jscience.org/api/org/jscience/mathematics/vector/DenseVector.html#valueOf(F...)
It really confuses me. I can't make a new DenseVector() because only the super class has that, and it's protected, and trying to do DenseVector.valueOf() apparently only works if I give it...that...weird thing as an input.
I've seen people having to instantiate methods when trying to instantiate objects (or something like that)...is that like that (or IS it that?)) What is the API trying to get me to do?
I'm kind of confused that I've learned java in school (and used it a bit at work, though we use a lot of differnet stuff besides just java), and never came across anything like this. What's it for? What's it trying to get me to do? Is it new? Old? Obscure?
-Jenny
You should be able to invoke this method to create a vector, like this:
Real r1 = Real.ONE, r2 = Real.valueOf(2D), r3 = Real.ZERO;
DenseVector<Real> v = valueOf(r1, r2, r3);
In this example, the type argument F is Real. Real obeys the constraint "extends Field<F>" because it implements Field<Real>.
For different applications, different fields are likely to be used. For example, security applications might use the ModuloInteger field. It's a little confusing because this is a mathematical field, not a "vector field" like one talks about in physics.
By using type variables, this library helps to make sure you perform all operations within a given field. For example, given v declared as a DenseVector<Real> like above, the compiler will complain if you try to multiply it by a Complex number.
It's a generic return type. See here for a tutorial on Java Generics.
These are called Generic types. They've been added in Java 5 and are similar to C++ templates.
The idea is that you define a collection of items of a particular type rather than something general.
This helps you avoid frequent downcasting. In older Java code, suppose that you knew your vector would contain only X's. Once you retrieved items out of that collection, you would just get Object, and you had to explicitly downcast it.
It is also safer because you can't put Ys into a vector of Xs, and clearer to read for the same reasons.
The story behinds the "extends" in these brackets is that you can define collections of "Xs and all their subtypes" that would still accept subtypes of X but reject Y.
public static <F extends Field<F>> DenseVector<F> valueOf(F... elements)
Lets break this down:
public static
Its a public static method.
<F extends Field<F>>
Its a generic method for any class F where F is an extention of Field
DenseVector<F>
It returns a (generic) DenseVector for F
valueOf(F... elements)
A method named valueOf where parameters are zero or more Fs.

Categories

Resources