How important are naming conventions for getters in Java? - java

I’m a huge believer in consistency, and hence conventions.
However, I’m currently developing a framework in Java where these conventions (specifically the get/set prefix convention) seem to get in the way of readability. For example, some classes will have id and name properties and using o.getId() instead of o.id() seems utterly pointless for a number of reasons:
The classes are immutable so there will (generally) be no corresponding setter,
there is no chance of confusion,
the get in this case conveys no additional semantics, and
I use this get-less naming schema quite consistently throughout the library.
I am getting some reassurance from the Java Collection classes (and other classes from the Java Platform library) which also violate JavaBean conventions (e.g. they use size instead of getSize etc.).
To get this concern out of the way: the component will never be used as a JavaBean since they cannot be meaningfully used that way.
On the other hand, I am not a seasoned Java user and I don’t know what other Java developers expect of a library. Can I follow the example of the Java Platform classes in this or is it considered bad style? Is the violation of the get/set convention in Java library classes deemed a mistake in retrospect? Or is it completely normal to ignore the JavaBean conventions when not applicable?
(The Sun code conventions for Java don’t mention this at all.)

If you follow the appropriate naming conventions, then 3rd-party tools can easily integrate with and use your library. They will expect getX(), isX() etc. and try to find these through reflection.
Although you say that these won't be exposed as JavaBeans currently, I would still follow the conventions. Who knows what you may want to do further down the line ? Or perhaps at a later stage you'll want to extract an interface to this object and create a proxy that can be accessed via other tools ?

I actually hate this convention. I would be very happen if it was replaced by a real java tool that would provide the accessor/modifier methods.
But I do follow this convention in all my code. We don't program alone, and even if the whole team agrees on a special convention right now, you can be assured that future newcomers, or a future team that will maintain your project, will have a hard time at the beginning... I believe the inconvenience for get/set is not as big as the inconvenience from being non-standard.
I would like to raise another concern : often, java software uses too many accessors and modifiers (get/set). We should apply much more the "Tell, don't ask" advice. For example, replace the getters on B by a "real" method:
class A {
B b;
String c;
void a() {
String c = b.getC();
String d = b.getD();
// algorithm with b, c, d
}
}
by
class A {
B b;
String c;
void a() {
b.a(c); // Class B has the algorithm.
}
}
Many good properties are obtained by this refactor:
B can be made immutable (excellent for thread-safe)
Subclasses of B can modify the computation, so B might not require another property for that purpose.
The implementation is simpler in B it would have been in A, because you don't have to use the getter and external access to the data, you are inside B and can take advantage of implementation details (checking for errors, special cases, using cached values...).
Being located in B to which it has more coupling (two properties instead of one for A), chances are that refactoring A will not impact the algorithm. For a B refactoring, it may be an opportunity to improve the algorithm. So maintenance is less.

The violation of the get/set convention in the Java library classes is most certainly a mistake. I'd actually recommend that you follow the convention, to avoid the complexity of knowing why/when the convention isn't followed.

Josh Bloch actually sides with you in this matter in Effective Java, where he advocates the get-less variant for things which aren't meant to be used as beans, for readability's sake. Of course, not everyone agrees with Bloch, but it shows there are cases for and against dumping the get. (I think it's easier to read, and so if YAGNI, ditch the get.)
Concerning the size() method from the collections framework; it seems unlikely it's just a "bad" legacy name when you look at, say, the more recent Enum class which has name() and ordinal(). (Which probably can be explained by Bloch being one of Enum's two attributed authors. ☺)

The get-less schema is used in a language like scala (and other languages), with the Uniform Access Principle:
Scala keeps field and method names in the same namespace, which means we can’t name the field count if a method is named count. Many languages, like Java, don’t have this restriction, because they keep field and method names in separate namespaces.
Since Java is not meant to offer UAP for "properties", it is best to refer to those properties with the get/set conventions.
UAP means:
Foo.bar and Foo.bar() are the same and refer to reading property, or to a read method for the property.
Foo.bar = 5 and Foo.bar(5) are the same and refer to setting the property, or to a write method for the property.
In Java, you cannot achieve UAP because Foo.bar and Foo.bar() are in two different namespaces.
That means to access the read method, you will have to call Foo.bar(), which is no different than calling any other method.
So this get-set convention can help to differentiate that call from the others (not related to properties), since "All services (here "just reading/setting a value, or computing it") offered by a module cannot be available through a uniform notation".
It is not mandatory, but is a way to recognize a service related to get/set or compute a property value, from the other services.
If UAP were available in Java, that convention would not be needed at all.
Note: the size() instead of getSize() is probably a legacy bad naming preserved for the sake of Java's mantra is 'Backwardly compatible: always'.

Consider this: Lots of frameworks can be told to reference a property in object's field such as "name". Under the hood the framework understands to first turn "name" into "setName", figure out from its singular parameter what is the return type and then form either "getName" or "isName".
If you don't provide such well-documented, sensible accessor/mutator mechanism, your framework/library just won't work with the majority of other libraries/frameworks out there.

Related

Post Java-14 getter/setter naming convention

Java 14 introduced records feature. Record creates getter with the same name as field, so one would write print(person.name()) for example. But old Java bean convention dictates that one should name this method as getName().
Using both styles in the same code base does not look very nice. Migrating everything to records is not possible, as they are too limited to replace all use-cases.
Is there any official or semi-official guidelines how to name getters and setters after Java 14 in new code?
Quote from JEP 359:
It is not a goal to declare "war on boilerplate"; in particular, it is not a goal to address the problems of mutable classes using the JavaBean naming conventions.
My understanding, based on the same document is that records are transparent holders for shallowly immutable data.
That being said:
Records are not the place to look for getters/setters syntactical sugar, as they are not meant to replace JavaBeans.
I strongly agree with you that JavaBeans are too verbose. Maybe an additional feature (called beans instead of records) could be implemented - very similar behavior with the records feature but that would permit mutability. In that case, records and beans would not be mutually exclusive.
As it has been mentioned, records are in preview mode. Let's see what the feedback from community would be.
All in all, IMHO they are a step forward... I wrote this example set where you can see a code reduction to ~15% LOC from standard JavaBeans.
Also, note that records behave like normal classes: they can be declared top level or nested, they can be generic, they can implement interfaces (from the same document). You can actually partly simulate JavaBeans (only getters would make sense, though) by extracting an interface containing the getters - however that would be a lot of work and not a really clean solution...
So, based on the logic above, to address your question, no - I didn't see any (semi)official guideline for getters and setters and I don't think that there is a motivation for it right now because, again, records are not a replacement for JavaBeans...
The record spec is now "final" as of Java 17 and this naming convention discrepancy has unfortunately not been addressed. I stumbled upon it when attempting to leverage Records as shallow holder classes to implement interfaces part of an existing domain model.
Whilst this isn't as neat a solution as I'd like, Records can have methods, so you could add "legacy" getters to your record, as in the following (contrived but simple) example.
public interface Nameable {
public String getName();
}
public record Person(String name) implements Nameable {
public String getName() {
return name; // or return name();
}
}
At least this allows client code to continue to use that tried and tested (over 20 years old) convention, which - let's face it - is used far more than in pure JavaBeans context.
You could say that the language designers have lived up to their remit of "not declaring war on boilerplate"
I stumbled up this when researching naming conventions for my project. Looking at the "recent" additions to the std lib (e.g. Path, FileSystem, HttpRequest, ...) the only more-or-less "pattern" I could detect was that .prop() implies direct, unmodified access to the field value, and thus existance of the field with that very type.
Whereas "getXXX" conveys that you cannot/should not assume the existence of a field. This property might be calculated, direct field access or read-only wrapped (e.g. List.copyOf) or converted.
So my conclusion is: if you want to communicate "structure" or enforce the precence of fields use .prop(). In all other cases stick to getXXX as it is more flexible (implementers can be entity classes, records or service classes.
Btw: I am aware that there are big offenders to this logic even in the jdk. e.g. BigDecimal that's why I focused on more recent additions.
In Java records, object fields must be private and final.
So there is just one kind of getter and one kind of setter possible.
In Java classes, object fields may be private or public.
In the latter type of field, one can get or set them simply by adding a period and the field name, e.g.
Employee emp = new Employee(); // Nullary constructor
emp.name = "John Schmidt"; // Setter
. . .
. . .
if (emp.name != "Buddy") // Getter
{
emp.bonus = 100.00;
}
Non-private fields are used a lot in Android apps to save memory and time extracting data. But there's no reason not to use them in Java where it's safe to do so.
Now, if you change away from the usual way in Java classes to something like that used in record types, e.g.
String name = emp.name(); // New getter convention for private field
you have a serious risk of confusion by code readers who might misinterpret this as a non-private object field.
And if you change the record getter to what is used in Java objects, i.e.
obj.getField()
then there is a risk of confusion by coder reviewers and possibly a compiler may treat it as a Java object, depending on execution decision criteria.
In short, it's a different type of object to the normal Java class or enum. Its accessors indicate this new type unambiguously.
That's how I see it anyhow.
Maybe someone on the Java development committee may be able to enlighten us further.

Java Getter Setter Codestyle

Outside of the context of beans, reflection, introspection or any other often referenced nonsense, is there an important reason that Java Getter/Setter are always notated as Type getAttribute() and void setAttribute(Type a)?
I read and wrote a lot of C++ code in recent times and when coming back to Java, I suddenly felt the urge to use Type attribute() and void attribute(Type a) as signatures for getters and setters as they somehow feel more comfortable to use all of a sudden. It reminds me of functional programming, having the attribute as a method of the object instead of having a method explicitly change or access the attribute.
The shorter style is the one I use. AFAIK Those in low level Java programming tend to use it possibly because it's more like C++, or because it's less like EJB's.
The problem with the JavaBean getter/setter style is it assumes an implementation of just setting and getting the variable, however this is not always the case.
You can use the methods the way you are comfortable with;
Type attribute() and void attribute(Type a)
The reason it is as you first example
Type getAttribute() and void setAttribute(Type a)
is used is to make it obvious what the method is to be used for. For example and new developer to a project can pick up and understand the flow of code without moving between different classes to see what that method does.
Getters & Setters are usually only one line functions. If a function is to do some data manipluation, it with usually use a descriptive name rather have a get or a set.
Summary:
Getters & Setters are mainly used for entity objects, where no data manipluation should be done, NOT saying that it can't be done.
The Java Naming Conventions state that "Methods should be verbs", which is commonly generalized by the community to "Methods should start with a verb". It is a question of consistency. You may very well use attribute, but I can guarantee you that people will confuse it. So if you expect other people to read and change you code, I strongly suggest to go for getAttribute and setAttribute. This argument is supported by Robert C. Martin in his book Clean Code (Section "Method Names"). It explicitly deals with your case.
That being said, the Java-API itself violates this rule sometimes (for example with the method size() in Collections). This is a known problem but shouldn't stop you from doing it better.

Java 8 default methods as traits : safe?

Is it a safe practice to use default methods as a poor's man version of traits in Java 8?
Some claim it may make pandas sad if you use them just for the sake of it, because it's cool, but that's not my intention. It is also often reminded that default methods were introduced to support API evolution and backward compatibility, which is true, but this does not make it wrong or twisted to use them as traits per se.
I have the following practical use case in mind:
public interface Loggable {
default Logger logger() {
return LoggerFactory.getLogger(this.getClass());
}
}
Or perhaps, define a PeriodTrait:
public interface PeriodeTrait {
Date getStartDate();
Date getEndDate();
default isValid(Date atDate) {
...
}
}
Admitedly, composition could be used (or even helper classes) but it seems more verbose and cluttered and does not allow to benefit from polymorphism.
So, is it ok/safe to use default methods as basic traits, or should I be worried about unforeseen side effects?
Several questions on SO are related to Java vs Scala traits; that's not the point here. I'm not asking merely for opinions either. Instead, I'm looking for an authoritative answer or at least field insight: if you've used default methods as traits on your corporate project, did it turn out to be a timebomb?
The short answer is: it's safe if you use them safely :)
The snarky answer: tell me what you mean by traits, and maybe I'll give you a better answer :)
In all seriousness, the term "trait" is not well-defined. Many Java developers are most familiar with traits as they are expressed in Scala, but Scala is far from the first language to have traits, either in name or in effect.
For example, in Scala, traits are stateful (can have var variables); in Fortress they are pure behavior. Java's interfaces with default methods are stateless; does this mean they are not traits? (Hint: that was a trick question.)
Again, in Scala, traits are composed through linearization; if class A extends traits X and Y, then the order in which X and Y are mixed in determines how conflicts between X and Y are resolved. In Java, this linearization mechanism is not present (it was rejected, in part, because it was too "un-Java-like".)
The proximate reason for adding default methods to interfaces was to support interface evolution, but we were well aware that we were going beyond that. Whether you consider that to be "interface evolution++" or "traits--" is a matter of personal interpretation. So, to answer your question about safety ... so long as you stick to what the mechanism actually supports, rather than trying to wishfully stretch it to something it does not support, you should be fine.
A key design goal was that, from the perspective of the client of an interface, default methods should be indistinguishable from "regular" interface methods. The default-ness of a method, therefore, is only interesting to the designer and implementor of the interface.
Here are some use cases that are well within the design goals:
Interface evolution. Here, we are adding a new method to an existing interface, which has a sensible default implementation in terms of existing methods on that interface. An example would be adding the forEach method to Collection, where the default implementation is written in terms of the iterator() method.
"Optional" methods. Here, the designer of an interface is saying "Implementors need not implement this method if they are willing to live with the limitations in functionality that entails". For example, Iterator.remove was given a default which throws UnsupportedOperationException; since the vast majority of implementations of Iterator have this behavior anyway, the default makes this method essentially optional. (If the behavior from AbstractCollection were expressed as defaults on Collection, we might do the same for the mutative methods.)
Convenience methods. These are methods that are strictly for convenience, again generally implemented in terms of non-default methods on the class. The logger() method in your first example is a reasonable illustration of this.
Combinators. These are compositional methods that instantiate new instances of the interface based on the current instance. For example, the methods Predicate.and() or Comparator.thenComparing() are examples of combinators.
If you provide a default implementation, you should also provide some specification for the default (in the JDK, we use the #implSpec javadoc tag for this) to aid implementors in understanding whether they want to override the method or not. Some defaults, like convenience methods and combinators, are almost never overridden; others, like optional methods, are often overridden. You need to provide enough specification (not just documentation) about what the default promises to do, so the implementor can make a sensible decision about whether they need to override it.

JavaBean equivalent in Python

I am fairly new to using Python as a OOP. I am coming from a Java background. How would you write a javabean equivalent in python? Basically, I need a class that:
Implements serializable.
Has getters and setters -> private properties
dummy constructor
Any inputs? I am looking for a sample code!
You don't, because Python is not Java. Most likely you should just write a less trivial class, construct a namedtuple, pass a dictionary, or something like that. But to answer the question:
Neither serializable nor "implementing an interface" makes sense in Python (well, in some frameworks and advanced use cases it does, but not here). Serialization modules, such as pickle, work without implementing or inheriting anything special (you can customize the process in other ways, but you almost never need to).
You don't write getters and setters. You just use public attributes. Should you later require a nontrivial getter/setter, you can turn it into a property transparently.
There's no need for a dummy constructor, unless you want to create the attributes and set default values for them. But that's probably a bad idea (for a bean-ish class), as not assigning values to those attributes is most likely an error, and dubious even when it isn't. So just let Python catch those errors for you (it raises AttributeError when a non-existent attribute is accessed).
Well, I'd think that data classes would be similar to Java beans and that using them is actually a good idea, as it removes boiler plate.
You can serialize most object via the pickle module;
There are no such things as private attributes in Python (see also:
Does python have 'private' variables in classes?,
Actual implementation of private variables in python class);
Classes that do not define a constructor will use a default (according to the method resolution order).
Example for constructor 'chain':
>>> class A(object):
... def __init__(self):
... print("A")
...
...
>>> class B(A): pass # has no explicit contructor
...
>>> b = B()
A
>>>
And - as #delnan wrote - you might want to read: http://dirtsimple.org/2004/12/python-is-not-java.html -- Java and Python have quite different cultures, it takes some time to dive into (and appreciate) both.
Also, after writing some code, it might be helpful to compare it to common idioms, as listed here (I certainly learned a lot this way):
http://www.jeffknupp.com/blog/2012/10/04/writing-idiomatic-python/
http://python.net/~goodger/projects/pycon/2007/idiomatic/handout.html
http://python3porting.com/improving.html
Implements serializable.
Pick your favorite format, and write a function that will serialize it for you. JSON, Pickle, YAML, any work. Just decide!
Has getters and setters -> private properties
We don't do that here, those are attributes of bondage languages, we are all adults in this language.
dummy constructor
Again not something we really worry about as our constructors are a little bit smarter than other languages. So you can just define one __init__ and it can do all your initialization, if you must then write a factory or subclass it.
As pointed by miku:
Objects can be serialized by picke module, but there is not an interface to be implemented, Python is not Java.
There is no private attribute in python, usually people use bar (the underscore) to mean private attributes, but they can be accessed from external world. Getters and setters are waste of time of both CPU and programmers.
Nothing to add to miku answer.
about properties: Real world example about how to use property feature in python?
good text: http://dirtsimple.org/2004/12/python-is-not-java.html

Java equivalent of .NET constructs

I've been writing .NET software for years but have started to dabble a bit in Java. While the syntax is similar the methodology is often different so I'm asking for a bit of help in these concept translations.
Properties
I know that properties are simply abstracted get_/set_ methods - the same in C#. But, what are the commonly accepted naming conventions? Do you use 'get_' with an underscode or just 'get' by itself.
Constructors
In C# the base constructor is called automatically. Is this also true in Java?
Events
Like properties, events in .NET are abstracted add_/remove_/fire_ methods that work on a Delegate object. Is there an equivalent in Java? If I want to use some sort of subscriber pattern do you simply define an interface with an Invoke/Run method and collect objects or is there some built-in support for this pattern?
Update: One more map:
String Formatting
Is there an equivalent to String.Format?
Java from a C# developer's perspective
Dare Obasanjo has updated his original 10 year old article with a version 2:
C# from a Java Developer's Perspective v2.0
Although for you its the other way round :)
To answer your specific questions:
Properties
By convention, Java uses "get" or "set" followed by the variable name in upper camel case. For example, "getUserIdentifier()". booleans often will use "is" instead of "get"
Constructors
In Java, superclass constructors are called first, descending down the type hierarchy.
Events
By convention (this is the one you'll get the least agreement on...different libraries do it slightly differently), Java uses methods named like "addEventTypeListener(EventTypeListener listener)" and "removeEventTypeListener(EventTypeListener listener)", where EventType is a semantic name for the type of event (like MouseClick for addMouseClickListener) and EventTypeListener is an interface (usually top-level) that defines the methods available on the receivers - obviously one or more of those references is essentially a "fire" method.
Additionally, there is usually an Event class defined (for example, "MouseClickEvent"). This event class contains the data about the event (perhaps x,y coordinates, etc) and is usually an argument to the "fire" methods.
Wikipedia has a nice in depth comparison here: http://en.wikipedia.org/wiki/Comparison_of_C_Sharp_and_Java
A bean property in java is preceeded by a get followed by the bean name starting with a capital letter. For instance the property 'color' would be associated with the methods 'getColor()' and 'setColor(int color)' (assuming the property is of type int). There is a special case for boolean properties, the getter will be called 'is'... as in 'isWhite()', 'isBlack()'. The setter remains the same.
When a class is created in java, all its parent class constructors are called in order, parents before children.
Events in Java are specific to a given event model, and not a core part of the language. Examine the documentation for Swing or SWT for information on the event models of those GUI toolkits.
Sun's Code Conventions are a great reference for the Java way of doing and naming things.
Property getters and setters can go by whichever naming convention you desire, or that your organization has standardized. A good naming convention is simply one that is common among those who will use/see it. That said, most in the Java community use 'getSomething/setSomething' as the naming convention on getters and setters.
Base constructors are called automatically, just like C#.

Categories

Resources