Java equivalent of .NET constructs - java

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#.

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 - what is a a prototype?

In a lecture on Java, a computer science professor states that Java interfaces of a class are prototypes for public methods, plus descriptions of their behaviors.
(Source https://www.youtube.com/watch?v=-c4I3gFYe3w #8:47)
And at 8:13 in the video he says go to discussion section with teaching assistants to learn what he means by prototype.
What does "prototype" mean in Java in the above context?
I think the use of the word prototype in this context is unfortunate, some languages like JavaScript use something called prototypical inheritance which is totally different than what is being discussed in the lecture. I think the word 'contract' would be more appropriate. A Java interface is a language feature that allows the author of a class to declare that any concrete implementations of that class will provide implementations of all methods declared in any interfaces they implement.
It is used to allow Java classes to form several is-a relationships without resorting to multiple inheritance (not allowed in Java). You could have a Car class the inherits from a Vehicle class but implements a Product interface, therefor the Car is both a Vehicle and a Product.
What does "prototype" mean in Java in the above context?
The word "prototype" is not standard Java terminology. It is not used in the JLS, and it is not mentioned in the Java Tutorial Glossary. In short there is no Java specific meaning.
Your lecturer is using this word in a broader sense rather than a Java-specific sense. In fact, his usage matches "function prototype" as described in this Wikipedia page.
Unfortunately, the "IT English" language is full of examples where a word or phrase means different (and sometimes contradictory) things in different contexts. There are other meanings for "template" that you will come across in IT. For instance:
In C++ "template" refers to what Java calls a generic class or method.
In Javascript, an object has a "template" attribute that gives the objects methods.
More generally, template-based typing is an alternative (more dynamic) way of doing OO typing.
But the fact that these meanings exist does not mean that your lecturer was wrong to refer to interface method signatures as "templates".
"prototype" is not the the best/right terminus to be used. interfaces are more like "contracts", that implementing classes have to fulfill.
The method's heads/definitions will have to be implemented in the implementing class (using implements keyword in the class head/class definition/public class xy implements ...).
I guess this naming conventions leave much room for many ideological debates.
Or the author had some sort of a mental lapsus and mapped the construct of prototypical inheritance from javascript into java in his mind somehow.
Interfaces are not prototypes for classes in Java.
In languages like C & C++, which compiles to machine code sirectly, compiler should be aware of the nature of any identifier (variable/class/functions) before they are references anywhere in the program. That mean those languages require to know the nature of the identifier to generate a machine code output that is related to it.
In simple words, C++ compiler should be aware of methods and member of a class before that class is used anywhere in the code. To accomplish that, you should define the class before the code line where it is used, or you should at least declare its nature. Declaring only the nature of a function or a class creates a 'prototype'.
In Java, an 'interface' is something like description of a class. This defines what all methods a particular kind of class should mandatory have. You can then create classes that implements those interface. Main purpose that interfaces serve in java is the possibility that a Variable declared as of a particular interface type can hold objects of any class that implements the object.
He tells it in C/C++ way, let me explain, in C++ you can define prototypes for methods at the header files of classes so that other classes can recognize these methods, also in C where there is no class concept, you can define prototypes at the beginning of file and then at somewhere in same file you can implement these prototypes, so that methods can be used even before their implementation is provided. So in Java interfaces provide pretty much same way, you can define prototypes for methods(method headers) that will be implemented by classes that implement this interface.
In a lecture on Java, a computer science professor states that:
Java interfaces of a class are:
1. are prototypes for public methods,
2. plus descriptions of their behaviors.
For 1. Is ok: - yes, they are prototypes for implemented public methods of a class.
For 2. This part could be a little bit tricky. :)
why?
we know: interface definition (contain prototypes), but doesn't define (describe) methods behavior.
computer science professor states: "... plus descriptions of their behaviors.". This is correct only if we look inside class that implements that interface (interface implementation = prototype definitions or descriptions).
Yes, a little bit tricky to understand :)
Bibliography:
Definition vs Description
Context-dependent
Name visibility - C++ Tutorials
ExtraWork:
Note: not tested, just thinking! :)
C++:
// C++ namespace just with prototypes:
// could be used like interface similar with Java?
// hm, could we then define (describe) prototypes?
// could we then inherit namespace? :)
namespace anIntf{
void politeHello(char *msg);
void bigThankYou();
}
Prototypes provide the signatures of the functions you will use
within your code. They are somewhat optional, if you can order
your code such that you only use functions that are previously
defined then you can get away without defining them
Below a prototype for a function that sums two integers is given.
int add(int a, int b);
I found this question because i have the same impression as that teacher.
In early C (and C++ i think) a function, for example "a" (something around lexic analysis or syntactic, whatever) can not be called, for example inside main, before it's declaration, because the compiler doesn't know it (yet).
The way to solve it was, either to declare it before it's usage (before main in the example), or to create a prototype of it (before main in the example) which just specifies the name, return values and parameters; but not the code of the function itself, leaving this last one for wherever now is placed even after it's called.
These prototypes are basically the contents of the include (.h) files
So I think is a way to understand interfaces or the way they say in java "a contract" which states the "header" but not the real body, in this case of a class or methods

What's the conception behind: Type - Element - Mirror

I'm working with Java 6's annotation processing, i.e. what can be found within javax.annotation.processing (not Java 5's APT).
I wonder what the conceptional difference between the various Element, Type, and Mirror classes is. As I don't really understand this, it's hard to efficiently program an annotation processor. There are various methods that 'convert' between these notions but I'm not really sure what I'm doing when using them.
So, for example, let me have an instance of AnnotationMirror.
When I call getAnnotationType() I get an instance of DeclaredType (which implements TypeMirror for whatever reason).
Then I can call asElement() on this one and obtain an instance of Element.
What has happened?
There is indeed on overlap between these concepts.
Element models the static structure of the program, ie packages, classes, methods and variables. Just think of all you see in the package explorer of Eclipse.
Type models the statically defined type constraints of the program, ie types, generic type parameters, generic type wildcards. Just think of everything that is part of Java's type declarations.
Mirror is an alternative concept to reflection by Gilad Bracha and Dave Ungar initially developed for Self, a prototype-based Smalltalk dialect. The basic idea is to separate queries about the structure of code (and also runtime manipulation of the structure, alas not available in Java) from the domain objects. So to query an object about its methods, instead of calling #getClass you would ask the system for a mirror through which you can see the reflection of the object. Thanks to that separation you can also mirror on classes that are not loaded (as is the case during annotation processing) or even classes in a remote image. For example V8 (Google's Javascript engine) uses mirrors for debugging Javascript code that runs in another object space.
This paper may help understanding the design of Java 6 annotation processing:
Gilad Bracha and David Ungar. Mirrors:
Design Principles for Meta-level
Facilities of Object-Oriented
Programming Languages. In Proc. of
the ACM Conf. on Object-Oriented
Programming, Systems, Languages and
Applications, October 2004.
The object of type javax.lang.model.element.AnnotationMirror represents an annotation in your code.
The declared type represents the annotation class.
Its element is the generic class (see http://java.sun.com/javase/6/docs/api/javax/lang/model/element/TypeElement.html for more information on that matter). The element might be the generic version of a class, like List, where as the declared type is the parametrized version, for instance List<String>. However I'm not sure it is possible to have annotations classes use generics and thus the distinction might be irrelevant in that context.
For instance lets say you have the following JUnit4 method:
#Test(expected = MyException.class)
public void myTest() {
// do some tests on some class...
}
The AnnotationMirror represents #Test(expected = NullPointerException.class). The declared type is the org.junit.Test class. The element is more or less the same as there are no generics involved.

How important are naming conventions for getters in 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.

Categories

Resources