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.
Related
This question already has answers here:
class or method alias in java
(8 answers)
Closed 3 years ago.
I have a class with a probably unnecessarily cumbersome name, that contains a lot of static methods I use elsewhere.
Rather than fill my code with a lot of
VeryUnnecessarilyLongCumbersomeName.doThingFoo();
VeryUnnecessarilyLongCumbersomeName.doThingBar();
VeryUnnecessarilyLongCumbersomeName.doThingEgg();
VeryUnnecessarilyLongCumbersomeName.doThingSpam();
I would rather have
VeryUnnecessarilyLongCumbersomeName thing = new VeryUnnecessarilyLongCumbersomeName();
thing.doThingFoo();
thing.doThingBar();
thing.doThingEgg();
thing.doThingSpam();
However, this gets the warning
"the static method doThingFoo() should be accessed in a static way."
I know there are multiple solutions here. Use better class names. Make it not static. Ignore it because it's just a warning.
But I don't actually think it should be a warning. What harm does doing it this way cause? Is there a more elegant/correct way to make my code less clunky that isn't one of the above solutions?
NOTE: I suspect this might warrant the coding-style tag and therefore be considered off-topic and get rejected. I was thinking there's room here for a question like this, however, so I leave it up to y'all.
Although it is not technically harmful because it technically works, the problem with this is it is misleading, and any values that the instance thing contains, do not actually matter at all for the results of the methods.
Typical Java Convention:
When accessing a method through an instance, one would expect the result to be dependent on the values of the instance.
When accessing a method through a Class name, one would expect the result to be independent of the values of any instance.
Your way:
You are accessing a method through an instance and expecting it to be independent of any instance.
So why use an instance for an instance independent method? That is why it is misleading. I would suggest attempting to shorten the class name rather than accessing static methods through an instance.
How about changing the VeryUnnecessarilyLongCumbersomeName class?
Static methods are there to be used without instances. They are meant to be used if you want to invoke the method without first initializing a class. The downside of using static methods is that you lose all kinds of OOP benefits; You lose virtual dispatch and subsequently polymorphism. You can never override that method in a derived class. Of course you can declare a new (static) method in a derived class, but any code that accesses it has to be aware of the entire class hierarchy and do explicit checking and casting, which is precisely what OO is supposed to avoid.
Also, it is confusing. When another programmer sees your code, he/she will think upon seeing a static he/she will assume that it will not require a valid instance to invoke the method.
TLDR; don't do it and stick with the best practices =)
This question already has answers here:
Should I use "this" keyword when I want to refer to instance variables within a method?
(8 answers)
Closed 4 years ago.
I had written a piece of code along the lines of:
public abstract class TestService extends Base {
protected final MappedObject<A, B> mappedObject;
public TestService(Provider provider, ObjectMapper objectMapper) {
mappedObject = new MappedObject.Builder<A, B>(...);
...
}
...
}
However, I have been instructed to prefix this to mappedObject, as it is convention when it comes to setting instance variables. Is this true?
I was under the impression that this as a prefix would only need to be used if there were a parameter with the same name that could cause ambiguity. Hence, a this would be necessary to reference the instance variable rather than the argument passed.
As you seem to be aware, it's not necessary, as long as there is no ambiguity between local and member variables of a class.
However, there are a number of different schools on this, and whether it's "convention" or not varies depending on who you ask (different developers have different preferences, different companies have different conventions, etc.). I would say it's mostly common in school courses. In the real world you might see it in a constructor from time to time, but in my personal experience it's quite rare.
Something that I find is more of a convention, and somewhat ties into this question, is prefixing member variables with m, as in mMappedObject, to indicate that it is a member variable. This is very common - in fact, one could argue that it's probably more common than prefixing this.
This question already has answers here:
In laymans terms, what does 'static' mean in Java? [duplicate]
(6 answers)
Closed 7 years ago.
As I understand it:
A static class only applies to nested classes, and it means that the nested class doesn't have references to the outer class.
A static field is kind of like a global variable, in that there is only one instance of it, and it is shared by other members of the same class.
A static method means that it can be called even if the object hasn't been instantiated yet.
I am taking an introduction to Java course and am trying to cement my knowledge, as well as trying to figure out why different keywords weren't used to signify different meanings.
Your examples are all correct, however, they all share a common feature. The word static means that an enclosing instance is not necessary.
Only a static inner class can exist without an enclosing instance. For example, if you have a class Foo and a non-static inner class Bar then you cannot create an instance of Bar outside an instance of Foo.
A static method means you do not need an instance of the class to call the method. You can call String.format without an actual String instance for example.
A static field will exist even without an instance of the class. If your Foo class has a counter field that is static you can access it without ever instantiating an instance of the Foo class.
Consider, as a clarifying point, that an interface can have static classes, static fields, and static methods. However, it cannot have the non-static version of any of those things (ignoring default methods which are sort of ad-hoc'd into the concept). This is because you can never create an instance of an interface so there could never be an enclosing instance.
You can also declare inner interfaces, annotations, and enums to be static although the keyword in that case is entirely redundant (e.g. similar to declaring an interface method abstract). Interfaces, annotations, and enums have no relationship to an enclosing class to begin with so static can't really take that away.
One last byzantine point. If you do a static import (import static pack.age.Foo.*) you will be able to make unqualified references to any static items in a class (including interfaces, annotations, and enums regardless of whether or not they are redundantly marked static).
Why does static have different meanings depending on the context? Why
didn't aren't different key words used?
It doesn't really have different meanings.
You can take the static keyword to indicate the following wherever it may be encountered:
"without regard or relationship to any particular instance"
A static field is one which belongs to the class rather than to any particular instance.
A static method is defined on the class and has no notion whatsoever of this. Such a method can access no instance fields in any particular instance, except when an instance is passed to it.
A static member class is a nested class that has no notion of its enclosing class and has no relationship to any particular instance of its enclosing class unless such an instance is passed to it (such as an argument to its constructor).
From Core Java by Cay Horstmann:
The term “static” has a curious history. At first, the keyword static was introduced in C to
denote local variables that don’t go away when a block is exited. In that context, the term
“static” makes sense: The variable stays around and is still there when the block is entered
again. Then static got a second meaning in C, to denote global variables and functions
that cannot be accessed from other files. The keyword static was simply reused, to avoid
introducing a new keyword. Finally, C++ reused the keyword for a third, unrelated,
interpretation—to denote variables and functions that belong to a class but not to any
particular object of the class. That is the same meaning the keyword has in Java.
Java inherits from C++ and C. In those languages, static has two additional meanings. A local variable (function scope) qualified as static has meaning somewhat similar to that of a static field in a class. Java however does not support this context of "static". Qualifying a variable or function as static in C or C++ at file scope means "Ssh! Don't tell the linker!". Java does not support this mean of static, either.
In English, the same word can have multiple meanings, depending on context. Look up any commonly-used word in the dictionary and you will find multiple definitions of that word. Some words not only have multiple meanings, they have multiple parts of speech. "Counter", for example, can be a noun, a verb, an adjective, or an adverb, depending on context. Other words can have contradictory meanings, depending on context. "Apology" can mean "I'm so sorry!" or it can mean "I am not sorry at all!" A premier example of the latter is "A Mathematician's Apology" by G. H. Hardy. English is not at all unique in this regard; the same applies to any language humans use to communicate with one another. As humans, we are quite used to words having different meanings depending on context.
There's an inherent conflict between having too few keywords and too many in a computer language. Lisp, forth, and smalltalk are very beautiful languages with very few, if any, keywords. They have a few special characters, e.g., open and close parentheses in lisp. (Full disclosure: I've programmed in all three of those languages, and I loved it.) There's a problem here: Good luck reading the code you yourself wrote six months after the fact. Even better luck turning that code over to someone else. As a result, these languages also have a rather limited number of adherents. Other languages go over the top and reserve a huge number of words as "keywords." (Full disclosure: I've been forced to program in those languages as well, and I hated it.)
Too few or too many keywords in a computer language results in cognitive dissonance. Having the same keyword have different contexts in different does not, because as humans, we are quite used to that.
Java Tutorial says
As with class methods and variables, a static nested class is
associated with its outer class. And like static class methods, a
static nested class cannot refer directly to instance variables or
methods defined in its enclosing class: it can use them only through
an object reference.
Basically "static" means that the entity marked with it is divorced from the instances of a class. Static method doesn't have an instance associated with it. Static field is shared between all instances (essentially exist in the Class, not in the instance).
static nested classes are divorced from the enclosing instance. You are right that it is a bit confusing because you can have an instance of a static nested class with non-static methods and fields inside of it.
Think of the word static as saying "I am declaring an entity, a field, a method or an inner class, which is going to have no relationship to the enclosing instance"
All the mentioned uses of static have some commonality as I see it - in all cases they mean that the class/field/method is less tied to the class instance than would be the case without static. Certainly the equivalence between static fields and static methods in particular should be clear: they are the way to declare singleton (per-classloader) fields and methods that work on those fields, in a similar way to global objects in other languages.
Perhaps then the use of static for nested classes isn't as obviously in the same spirit, but it does share the aspect that you don't need an instance of the containing class to use this construct.
So I don't see these as being particularly inconsistent.
One answer to the more general question of why keywords are re-used for apparently different purposes in a programming language is that often features are introduced as a language evolves - but it is difficult to add new keywords since often break existing programs that may have used that as an identifier. Java, for example, actually reserves the keyword const even though it is unused in the language, perhaps to allow for future expansion!
This reluctance to add new keywords often leads to overloading old ones.
This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
Private vs. Public members in practice (how important is encapsulation?)
Recently I've been coming across a situation where I declare a class variable as public, because it will be used in another class. Someone told me recently that I should make such variables private and write a public method returning the value of the variable. I was told this was good practice. I searched through my Java book and couldnt find any reference to this. My question is, is it good practice to declare as many as possible class variables as private?
Yes. Generally, all variables should be private (not protected, private), and there should be methods to get their values (and possibly set them) if (and only if) you want to allow that by outsiders. The variables you use are an implementation detail, and usually contain data that has to be a certain way. Getters and setters allow you to take responsibility for that data, validate it, synchronize it, etc, instead of letting some jackass store random stuff in it and potentially make your object unusable.
The sole exception might be classes whose only purpose is storage of data so you can ship it around as one object, kinda like a C/C++ struct. But then, you're making a decision that no, you don't want to validate, synchonize, encapsulate that data in any way...and changing your mind later breaks binary compatibility (meaning any code that touched that class will need to be recompiled). Not a big deal in a little private project; huge deal in a public framework/API.
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.