Is there a convention in Java on where to declare fields - before or after methods?
Class layout: see here http://java.sun.com/docs/codeconv/html/CodeConventions.doc2.html#1852
The following table describes the parts of a class or interface declaration, in the order that they should appear
Class/interface documentation comment (/*.../)
class or interface statement
Class/interface implementation comment (/.../), if necessary
Class (static) variables
Instance variables
Constructors
Methods
Most of the code I saw declared fields first, then methods (which is also suggested by the Java code conventions guide: http://www.oracle.com/technetwork/java/codeconventions-141855.html#1852)
Standard Java code conventions from Sun: http://java.sun.com/docs/codeconv/CodeConventions.pdf
And Oracle: http://www.oracle.com/technetwork/java/codeconvtoc-136057.html
Fields before methods is the most common style.
I've mostly seen them at the top. One engineer I respect puts them at the bottom (to emphasize that you shouldnt be thinking about them :). You can avoid the Thinking About problem entirely by coding to interface, not classes. Also, take your vitamins. And floss!
From most code I've seen, fields get declared before methods. This isn't set in stone, as some people follow the common C++ practice of putting public fields and methods first, and then private fields and methods. I wouldn't treat it as a strict guideline; just ask yourself what makes your code more understandable by another person.
According to Sun's "Code Conventions for the Java Programming language", this is indeed the case: static fields first, then instance fields, then constructors, then methods.
However this part of the conventions is not quite as widely confirmed to as others: while using non-capitalized class names or capitalized variable names will immediately yield protests from the vast majority of Java programmers, many will accept putting fields next to the methods that operate on them.
Related
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.
This question already has answers here:
Are there any Java method ordering conventions? [closed]
(8 answers)
Closed 7 years ago.
I have come to the question: what is the most preferred way of placing methods? I mean, should first declare static methods, then constructors, then public methods, then protected, then private, etc? Is there some kind of convention, like I guess everyone places fields (instance variables) on top of the code. Is there the same policy about methods?
I guess it depends on the language you use. What about Java?
This is somewhat opinion based, but the Google Java Style doc puts it nicely:
The ordering of the members of a class can have a great effect on learnability, but there is no single correct recipe for how to do it. Different classes may order their members differently.
What is important is that each class order its members in some logical order, which its maintainer could explain if asked. For example, new methods are not just habitually added to the end of the class, as that would yield "chronological by date added" ordering, which is not a logical ordering.
https://google-styleguide.googlecode.com/svn/trunk/javaguide.html#s3.4.2-class-member-ordering
Most of the code I see in the open source world uses some variation of
static fields
instance fields
constructors
methods (instance and static)
anonymous classes
It comes down to team preference, but it is always good to follow convention
Talking about execution, JVM guarantees the order which we cannot change.manage.
But from code readability point of view , YES ordering does looks good. Following coding standards is what should do.
Static fields -> instance fields/variables
As we know, Static Block is always called once class is loaded, so we should have it.
Then constructors, for object creation, there is no point of writing constructor at the end.
also a good read here as suggested above.
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
As everybody knows, Java follows the paradigms of object orientation, where data encapsulation says, that fields (attributes) of an object should be hidden for the outer world and only accessed via methods or that methods are the only interface of the class for the outer world. So why is it possible to declare a field in Java as public, which would be against the data encapsulation paradigm?
I think it's possible because every rule has its exception, every best practice can be overridden in certain cases.
For example, I often expose public static final data members as public (e.g., constants). I don't think it's harmful.
I'll point out that this situation is true in other languages besides Java: C++, C#, etc.
Languages need not always protect us from ourselves.
In Oli's example, what's the harm if I write it this way?
public class Point {
public final int x;
public final int y;
public Point(int p, int q) {
this.x = p;
this.y = q;
}
}
It's immutable and thread safe. The data members might be public, but you can't hurt them.
Besides, it's a dirty little secret that "private" isn't really private in Java. You can always use reflection to get around it.
So relax. It's not so bad.
For flexibility. It would be a massive pain if I wasn't able to write:
class Point {
public int x;
public int y;
}
There is precious little advantage to hide this behind getters and setters.
Because rigid "data encapsulation" is not the only paradigm, nor a mandatory feature of object orientation.
And, more to the point, if one has a data attribute that has a public setter method and a public getter method, and the methods do nothing other than actually set/get the attribute, what's the point of keeping it private?
Not all classes follow the encapsulation paradigm (e.g. factory classes). To me, this increases flexibility. And anyway, it's the responsibility of the programmer, not the language, to scope appropriately.
Object Oriented design has no requirement of encapsulation. That is a best practice in languages like Java that has far more to do with the language's design than OO.
It is only a best practice to always encapsulate in Java for one simple reason. If you don't encapsulate, you can't later encapsulate without changing an object's signature. For instance, if your employee has a name, and you make it public, it is employee.name. If you later want to encapsulate it, you end up with employee.getName() and employee.setName(). this will of course break any code using your Employee class. Thus, in Java it is best practice to encapsulate everything, so that you never have to change an object's signature.
Some other OO languages (ActionScript3, C#, etc) support true properties, where adding a getter/setter does not affect the signature. In this case, if you have a getter or setter, it replaces the public property with the same signature, so you can easily switch back and forth without breaking code. In these languages, the practice of always encapsulating is no longer necessary.
Discussing good side of public variables... Like it... :)
There can be many reasons to use public variables. Let's check them one by one:
Performance
Although rare, there will be some situations in which it matters. The overhead of method call will have to be avoided in some cases.
Constants
We may use public variables for constants, which cannot be changed after it is initialized in constructor. It helps performance too. Sometimes these may be static constants, like connection string to the database. For example,
public static final String ACCEPTABLE_PUBLIC = "Acceptable public variable";
Other Cases
There are some cases when public makes no difference or having a getter and setter is unnecessary. A good example with Point is already written as answer.
Java is a branch from the C style-syntax languages. Those languages supported structs which were fixed offset aliases for a block of memory that was generally determined to be considered "one item". In other words, data structures were implemented with structs.
While using a struct directly violates the encapsulation goals of Object Oriented Programming, when Java was first released most people were far more competent in Iterative (procedural) programming. By exposing members as public you can effectively use a Java class the same way you might use a C struct even though the underlying implementations of the two envrionments were drastically different.
There are some scenarios where you can even do this with proper encapsulation. For example, many data structure consist of nodes of two or more pointers, one to point to the "contained" data, and one or more to point to the "other" connections to the rest of the data structure. In such a case, you might create a private class that has not visibility outside of the "data structure" class (like an inner class) and since all of your code to walk the structure is contained within the same .java file, you might remove the .getNext() methods of the inner class as a performance optimization.
To use public or not really depends on whether there is an invariant to maintain. For example, a pure data object does not restrict state transition in any fashion, so it does not make sense to encapsulate the members with a bunch of accessors that offer no more functionality that exposing the data member as public.
If you have both a getter and setter for a particular non-private data member that provides no more functionality than getting and setting, then you might want to reevaluate your design or make the member public.
I believe data encapsulation is offered more like an add-on feature and not a compulsory requirement or rule, so the coder is given the freedom to use his/her wisdom to apply the features and tweak them as per their needs.Hence, flexible it is!
A related example can be one given by #Oli Charlesworth
Accesibility modifiers are an implementation of the concept of encapsulation in OO languages (I see this implementation as a way to relax this concept and allow some flexibility). There are pure OO languages that doesn't have accesibility modifiers i.e. Smalltalk. In this language all the state (instance variables) is private and all the methods are public, the only way you have to modify or query the state of an object is through its instance methods. The absence of accesibility modifiers for methods force the developers to adopt certain conventions, for instance, methods in a private protocol (protocols are a way to organize methods in a class) should not be used outside the class, but no construct of the language will enforce this, if you want to you can call those methods.
I'm just a beginner, but if public statement doesn't exists, the java development will be really complicated to understand. Because we use public, private and others statements to simplify the understanding of code, like jars that we use and others have created. That I wanna say is that we don't need to invent, we need to learn and carry on.
I hope apologize from my english, I'm trying to improve and I hope to write clearly in the future.
I really can't think of a good reason for not using getters and setters outside of laziness. Effective Java, which is widely regarded as one of the best java books ever, says to always use getters and setters.
If you don't need to hear about why you should always use getters and setters skip this paragraph. I disagree with the number 1 answer's example of a Point as a time to not use getters and setters. There are several issues with this. What if you needed to change the type of the number. For example, one time when I was experimenting with graphics I found that I frequently changed my mind as to weather I want to store the location in a java Shape or directly as an int like he demonstrated. If I didn't use getters and setters and I changed this I would have to change all the code that used the location. However, if I didn't I could just change the getter and setter.
Getters and setters are a pain in Java. In Scala you can create public data members and then getters and or setters later with out changing the API. This gives you the best of both worlds! Perhaps, Java will fix this one day.
This is a homework question, so I'm not looking for a direct answer. I need a push in the right direction. I'm simply not understanding the question. My answer to this was "The values are, in fact, instances of their own enumeration type." Which came back incorrect. I'm looking at the API now...is this referring to the methods listed in the methods summary?
I'm noticing from this page that modifier types for Java in general refer to access control (private, public, protected) and non-access modifiers (static, final, abstract, volatile).
I'm putting public, protected for my next answer as I see those two listed within the API for access control. Am I thinking about this correctly?
Got back my homework, turns out I was correct.
The modifiers for each constant are implicitly declared, as mentioned in the Java Language Specification, §8.9 Enums. As a corollary, consider which modifiers are associated with all-upper-case identifiers in the widely used Google Java Style or Java Coding Style Guide?
As the homework should be over a while ago and for anyone like me looking for a quick answer:
public static final
For each enum constant c declared in the body of the declaration of E,
E has an implicitly declared public static final field of type E that
has the same name as c. The field has a variable initializer
consisting of c, and is annotated by the same annotations as c.
(taken from trashgod's link: Java Language Specification, §8.9 Enums)
I believe you are correct. In java, all the values in an Enum have the type of that Enum. Instead of being treated like magic values as they are in many other languages, they are instances of a type, a very beautiful OO way of thinking about things.
"The values are, in fact, instances of their own enumeration type."
This is factually correct, but it does not answer the question you were asked about the implicit modifiers for enum values. That is why it is the wrong answer.