As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 12 years ago.
Some might like to argue that this is a candidate for the least important issue of all times. Yet code style is a very important topic for me, and I want to ensure that I write code in a readable way - for me and the majority of developers.
That's why I'm wondering where you guys are declaring your inner classes.
I'm following the following method ordering scheme, because it is quite common:
public void foo() {
usedByFoo();
}
private void usedByFoo() {
}
public void bar() {
}
I order them from top to bottom, every method as close to where it is used.
Now I could do the same with inner classes, like this:
class Outer {
private Inner inner;
private class Inner {};
public Outer() {
}
...
}
I think this is the most consistent style to follow for me, but I've also often seen people declare all inner classes either at the top or at the bottom of the file.
Which style should I follow, given my way of ordering methods? What is the most common way to do this?
I would declare inner-classes in the bottom of the file - usually you're not interested in their implementations and just want to get to your main class' methods, so they shouldn't get in the way.
My preferred style is to put them wherever they seem to make most sense. Usually this is at the bottom so they're out the way, but sometimes I find it makes more sense to put them before a certain group of methods (if these are the methods that use the inner class.)
If the class gets too unwieldy with loads of methods and inner classes though, it's probably a bad design choice (cohesion is too low.) I've sometimes let classes get this way by accident and they're horrible to deal with later - these days if I can see one going that way I'll generally refactor it out, perhaps even into its own package. If you get to the point where you've got so many inner classes you don't know what to do with them, I'd take this approach. There's even some that advise against using inner classes at all for this reason (though I disagree - they're a valuable resource when used properly, you just need to take care they don't get out of hand.
Related
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
I'm currently in the process of cleaning up a a large Java code base, and I was wondering what was the proper (standard?) structure/ordering of a Java class.
What I mean is:
Should public static final fields be first among the fields of a Class?
Where should a static initializer be?
Where should private static helper methods be?
Also, as a side question: is it a good idea to have large harcoded SQL queries for PrepareStatements in the code?
You should be more worried about naming convention, clear code documentation and overall the correctness of the program (i.e. no bugs), after this you can worry about the order of defining variables, methods etc
This is the code convention for Java
To answer (some) of your points:
static initializer usually appears in the begining of your classes, after the variables if it happen to come first.
private methods can go to the end of your class (before variables if they are at the end), but it is matter of preference, because usually the one who reads the code care more about the public methods that the class expose to the rest of the program
Having the SQL statement inside the program or stored externally (e.g. properties file) depends on how often they are changing; but as long as you are using PreparedStatement you should be OK.
Well, here you're gonna find Java code conventions: Java Code Conventions
I really don't like harcoded SQL statements. But, sometimes they are necessary. See if you can encapsulate that on a library (like hibernate or something), or if at least you can break it into minor sql codes.
Adding
I would also take a look at: How to Write Doc Comments for the Javadoc Tool to mantain your code well documented.
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
Is it best practice to have all the classes public in a Java project? I have noticed that in all Java projects I have worked with, there have only been public classes.
It isn't a guideline, no.
The information hiding principle tells us to only exposed what is required, and nothing more, to minimize coupling.
So, for example, if a class lets you handle logic in a separate class easier, and is only used by that class, there's no reason to have it public, nor should you make it public.
The simple answer to your question is "no!"
The slightly more complicated one is that you should only make a class public if it needs to be used by other classes outside it's own package. But if, like me, you break you project up into many packages for readability, then then if will often be the case that your classes will need to be public to be usable.
While your question is simple to ask, it is far from simple in its nature. Much will depend upon the kind of code your writing. It you're writing a library then use externally is probably high on your agenda. In an application less so.
I have found that I prefer the public approach. I try and design for reuse because it keeps my options open, causes me to think more carefully about my implementation because of the reuse issues, and that leads to better code. But it really is horses for courses, you are the biggest variable in this equation.
It depends, For top level class's, If you want other class's in a different package to view your class you should mark it public. If you only want class's in the same package to view you class mark it default(no-modifier).
So, your question is really, should all top level classes be public? I think it boils down to the usage of the package access that you do in your project. This question was relevant to that, some time ago.
Usually most classes are indeed public but there are cases when you might want to use default or private scope as well.
A class using the default scope is only accessible to other classes in the same package. In case of helper classes for example it's often a good practice to limit their use this way as your code becomes more encapsulated. The private scope can often be used for inner classes for the same reason.
No it is not. There are lot of classes with other access specifiers or even anonymous. For an example, you can write private or anonymous classes that can be registered to listeners like
'ActionListener' and 'ItemListener'. Just like that, for various purposes, we do write lot of classes with no public specifier. It really helps to separate your work into pieces.
However, in Java, normally every source file contains a public class. That is because if your source file's name is 'Reader.java', you cannot have a private or other access specifier for the class 'Reader' inside that source file. It must be public or default. Apart from that, no other class can have the access specifier 'public' instead of 'Reader' class.
Other thing is, private, protected and other types (except default) of classes cannot be written in a source file as "Independent classes". For an example, following is an error
Check.java
private class Check
{
}
It definitely is not best practice. You are seeing it because most programmers don't know that a top-level class doesn't have to be public.
Ideally, a package isn't just a way to organize classes into groups. There is no minimum or maximum number of classes that belong in a single package; rather, subpackages should be created only when there is a need for package-level classes and/or members. Java APIs do this a lot, and since the javadoc distributed from Sun/Oracle is generated for protected-level classes and members, some packages may appear to be sparse, even to the point of appearing nonsensically so.
For instance, the javax.swing.colorchooser package appears to have only four classes, but it actually has 17 (actual number may vary depending on the version of Java). Four are public; the rest are only for use with JColorChooser internals.
I've found that an inner class that is becoming too big to be easily maintained as an inner class is usually a good candidate for being a non-public top-level class.
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
What is the purpose of nested classes?
Any examples?
I don't really see the need for them. Why not just create a new class? It seems really unorganized when using a nested class.
Why Use Nested Classes?
There are several compelling reasons for using nested classes, among them:
It is a way of logically grouping classes that are only used in one place.
It increases encapsulation.
Nested classes can lead to more readable and maintainable code.
Logical grouping of classes—If a class is useful to only one other class, then it is logical to embed it in that class and keep the two together. Nesting such "helper classes" makes their package more streamlined.
Increased encapsulation—Consider two top-level classes, A and B, where B needs access to members of A that would otherwise be declared private. By hiding class B within class A, A's members can be declared private and B can access them. In addition, B itself can be hidden from the outside world.
More readable, maintainable code—Nesting small classes within top-level classes places the code closer to where it is used.
Uses for nested classes:
eliminate namespace pollution
provide the nested class access to private members of the outer class
organize related code together
hide implementations of interfaces from the outside world
There are probably other uses, but these, off the top of my head, should be enough to suggest that there might, actually, be a use for them.
It is a way of logically grouping classes that are only used in one place.
It increases encapsulation.
Nested classes can lead to more readable and maintainable code.
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
Using a getter/setter in the internal code of a class instead of accessing the instance variable directly, is it good or bad practice? At least for setters one could add additional code validating the value, but for the getters it's just overhead? How intelligent is the Java compiler, if my getters/setters just set/get the value directly, will Java optimize my code and replace the getters/setters by direct access to the instance variables, so there's no method calling overhead?
It is more common to access the field directly. The value of a setFieldName method is more obvious for programmers using your code in other classes. With the implementation details hidden, they might not realize what ranges of values are acceptable, so keeping fields private and forcing other developers to go through a setter makes sense. But inside your own class, the case for using a setter is much weaker. If you look at the source for the java API you'll find that getter / setter methods are generally not used within a class.
There is no need to do that inside a class, unless want to perform additional operations in those getters / setters.
The access to the class members can be direct to the class internally, as:
The reason for hiding is mainly to hide the implementation (and there's no need to hide the implementation from the class itself)
The getters and setters access the members directly, so to call them just to avoid access the members directly is somewhat, umm... redundant.
Regarding performance - I honestly think that in most cases, you shouldn't think about it, you should decide whether to call a method or access directly in terms of readability, scalability and maintenance, not in terms of whether it will take another nano second or not. This approach pays off in the long run. There are places for optimizations, and you should be efficient, but keeping your code clear and maintainable is much more important once the code base is over 20 lines.
Accessing directly is a good thing. However, no one can say getter/setter access is bad, inside the same class. If you are developing a Java bean, you will definitely understand what I am saying. Think you are trying to get the user input of a JTextField as a String. In this case, the getter methods will allow you to do lot of things including String truncating, trim, uppercase, lowercase, etc. If you are trying to do this all just by accessing the direct variable (eg: String s = textField.getText()), you will find it quite difficult to do it. So, what I think is, the good or bad depends on the situation and what you are developing
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 11 years ago.
I'm reading some books about coding standard in Java.
I always loved beautiful and clean code.
But there are some things that bother me. For example, a method name should start with a lowercase word, and if it has a second word, it should be start with a uppercase character. But the standard for variables is the same thing. I think this is a little confusing.
So I'm asking you guys, what's your coding standard in Java?
Like:
How do you name objects, methods, classes, etc.
If you have more than one object from same class, how do you name the second one?
If you have one object in the argument of a method and you have another object from the same class inside this method, how you do name both of them?
What is the best trade-off for performance/code beauty, a lot of small methods, or some longer methods?
Feel free to say something more. =)
Mostly following the Java code convention.
I try to not make it matter what kind of class an object is. If I for instance have five different strings, the name of each variable should describe what information/content the variable represents, and not that is is a string.
I find it often silly to try coming up with variations of a variable just because it exists both as a method argument and a class variable. I mostly use the same name with this syntax this.theVariable = theVariable
A method should be as short as possible: as few lines as possible, and as few nested levels as possible (i.e. max one if-statement, and not ifs inside ifs etc.)
Robert Martin's Clean Code is highly recommended!
Just to address one specific point, because it's one I commonly see people doing horrific things with:
If you have more than one object from same class, how do you name the second one?
By their purpose, surely. If you have two different objects of the same class, you must be using them for different purposes, so name it after that purpose. I think all of these examples would be pretty self-explanatory to most readers:
public void copyAddresses(Customer source, Customer destination) {
public void sendMessage(Mailbox sender, Mailbox recipient) {
public void changeContactCompany(User contact, Company from, Company to) {
public void eatWatermelon(Bowl servingBowl, Bowl bowlForSeedSpitting) {
or whatever... you get the idea.
You should start with the official Java Code Conventions.
They will explain why code conventions are needed, different conventions and, what your question seems to be about, naming conventions. They add various examples too.
What is the best trade-off for
performance/code beauty, a lot of
small methods, or some longer methods?
"Premature optimization is the root of all evil" - Donald Knuth
Remember:
Make it work.
Make it right.
Make it fast.
You should only worry about performance if it is warranted; if the current code is too slow to meet requirements.
In that case you should find the 'hot-spots' and optimize those. Check if performance is good enough. If not, repeat.
Well since most of these are easily googled I will add my own standard Java naming practices:
I usually suffix the name of classes of what they extend or implement.
In other words Spring MVC controllers are suffixed with "Controller". This makes it easy in Eclipse to do a Crtl-Shift-R *Controller.
Second if I find I need to aggregate a whole bunch of static methods in a class I usually suffix that class with "Utils". I got this from Apache Commons and has just stuck.
Finally derived methods that do special expensive stuff and are transient I avoid calling them getXXX. The reason is to avoid problems with serializers.
Look here at the official guide