Are there any Java method ordering conventions? [closed] - java

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I've got a large-ish class (40 or so methods) that is part of a package I will be submitting as course-work. Currently, the methods are pretty jumbled up in terms of utility public/private etc. and I want to order them in a sensible way. Is there a standard way of doing this? E.g. normally fields are listed before methods, the constructor(s) are listed before other methods, and getters/setters last; what about the remaining methods?

Class (static) variables: First the public class variables, then the
protected, and then the private.
Instance variables: First public, then protected, and then private.
Constructors
Methods: These methods should be grouped by functionality rather
than by scope or accessibility. For example, a private class method
can be in between two public instance methods. The goal is to make
reading and understanding the code easier.
Source: https://www.oracle.com/java/technologies/javase/codeconventions-fileorganization.html

Some conventions list all the public methods first, and then all the private ones - that means it's easy to separate the API from the implementation, even when there's no interface involved, if you see what I mean.
Another idea is to group related methods together - this makes it easier to spot seams where you could split your existing large class into several smaller, more targeted ones.

The more precise link to «Code Conventions»: «Class and Interface Declarations»

Not sure if there is universally accepted standard but my own preferences are;
constructors first
static methods next, if there is a main method, always before other static methods
non static methods next, usually in order of the significance of the method followed by any methods that it calls. This means that public methods that call other class methods appear towards the top and private methods that call no other methods usually end up towards the bottom
standard methods like toString, equals and hashcode next
getters and setters have a special place reserved right at the bottom of the class

40 methods in a single class is a bit much.
Would it make sense to move some of the functionality into other - suitably named - classes? Then it is much easier to make sense of.
When you have fewer, it is much easier to list them in a natural reading order. A frequent paradigm is to list things either before or after you need them , in the order you need them.
This usually means that main() goes on top or on bottom.

My "convention": static before instance, public before private, constructor before methods, but main method at the bottom (if present).

Also, eclipse offers the possibility to sort class members for you, if you for some reason mixed them up:
Open your class file, the go to "Source" in the main menu and select "Sort Members".
taken from here: Sorting methods in Eclipse

Are you using Eclipse? If so I would stick with the default member sort order, because that is likely to be most familiar to whoever reads your code (although it is not my favourite sort order.)

Related

Interfaces and static methods in java [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 months ago.
The community reviewed whether to reopen this question 9 months ago and left it closed:
Original close reason(s) were not resolved
Improve this question
It occurred to me that interfaces cannot be instantiated and hence I could create an interface containing only a bunch of static utilities methods that I need as opposed to a regular class with a private constructor and public static methods. Any comments on that? Should I do it or does it not really matter?
A program is not just a set of instructions for a computer to obey. It's also a message to future developers. You should use the statements in your program to indicate to other developers (or even yourself a few months into the future), what you intend for the computer to do.
That's why we give variables, methods and classes clear names. It's why we lay out our programs in certain expected ways. It's why we use indentation consistently, and why we have naming conventions.
One of those conventions is that if you have a bunch of static methods that need to be organised together, they should be organised into a class, not an interface. Whether or not it's technically possible to put all your methods into an interface is not the question you should be asking. What matters is how to communicate most efficiently what you're actually intending to do.
To that end, please don't set up your program in strange, innovative ways. You're just going to confuse and annoy people.
Although this is possible interfaces should be used
when it is important for disparate groups of programmers to agree to a "contract" that spells out how their software interacts. Each group should be able to write their code without any knowledge of how the other group's code is written. Generally speaking, interfaces are such contracts.
https://docs.oracle.com/javase/tutorial/java/IandI/createinterface.html
Interfaces should be defined as an abstract type used to specify the behavior of a class; therefore they're meant to be later implemented.
What you're trying to do is not completely wrong (interfaces can offer static methods), but it's definitely not what they were designed for. If you want to offer a set of static utilities from a common "place", you could declare a final class with a private constructor, in order to prevent its extension (with possible methods overriding), and avoid its instantiation. The Math class is a perfect example of this.
Alternatively, if you want to declare instances of said class, you could declare your class normally, then declare its methods as final (to prevent their overriding) and offer a public constructor or a factory method.

Does encapsulation of class methods/fields matter if they are only accessed by the class itself? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 2 years ago.
Improve this question
Short context: I made a tetris clone in java (all the game data and methods are a Class) and I am concerned about whether encapsulation matters in this case.
Almost all of the fields and methods are marked as "default", without any getters and setters because the user is not supposed to access them.
Methods manipulate variables directly without any arguments passed, of course only when the thing it is manipulating is unique (there can not be two current pieces, two next block lists, two held pieces and so on)
Do I really need getters and setters if the user is never supposed to get raw members of the class? Methods just directly get and set the values. If I have a simple int that I want to get or set, I am just doing it directly.
No return value, if one exact thing is supposed to happen every time. For example: if a collision happens during spawning, gameOver() is triggered immediately instead of returning false, then doing it outside of function. I chose to not have a return value because it is much simpler to do it inside function instead of surrounding each function call with an if statement doing the same thing.
Do I need to fix some of these things, and how should I, preserving stability in both readability and performance?
It does not.
Why? The understanding is that a class’s fields and methods are working in conjunction towards a common goal. So they are not enemies or careless actors that you have to protect yourself against.
It is only to prevent external actors from mucking up class invariants that you hide your fields and methods as much as possible and expose only that which is necessary.
If you have to use setters and getters to enforce discipline in the code within a class, then you have much bigger problems to handle than maintaining proper encapsulation (and other OO principles.)
No, you do not need getters and setters if you do not intend on anything accessing the member variables from outside of the class.
In your case because the member variables are only accessed from within the class itself then the access modifier(s) should be changed to private.
The use of the default keyword means that you do not want to provide an access modifier and that variable should be available to any other class in the same package.
More info can be found Here

Is it good to Sharing constant strings in Java across many classes? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 5 years ago.
Improve this question
I'd like to have Java constant strings at one place and use them across whole project?I am confusing Is it a good practice for better readability or not?
Simple: when multiple classes need the same information, then that information should have a single "root".
So yes: it is absolutely good practice to avoid re-declaring the same value in different places. Having a "global" constant simply helps with avoiding code duplication - thus preventing errors later on, when you might have to change such values.
One single class with (unrelated) constants has problems. It is a bottleneck:
if in a team a constant is added at the bottom, someone else adding a constant will receive a VCS conflict. Enforce the declarations to be sorted alphabetically. It also ties this package together in other forms. Still many unneeded recompilations would be needed (see also the remark at the end).
In java 9 with modules, you would in every using module need to require the constants classes module, probably causing an unnecessary module graph.
Then there are constants which need not be named and still are not "magic".
In annotations as arguments. An annotation scanning can gather those values if you need uniqueness or such.
And finally there are shared constants. Near the used constructs is still my favourite.
Also the constants class pattern tends to be used often with String constants. That reeks of code smell, as it is a kind of burocracy where one
should use automatic mechanisms, OO, fixed conventions, declarative data.
For database tables and columns there exist better mechanisms.
Classes with constants (still) have the technical compilation problem that in java the constant is incorporated in the .class file itself, and the import disappears. Hence changing the original constant will not notify the compiler to recompile the "using" class. One needs a full clean build after recompiling a constants class.
If you think that your Strings are going to be referenced in many flows, then it is good to use. Moreover, it is a widely accepted practice as well.
It is good to create Interface & declare your all constant in it.
E.G
public interface ICommonConstants {
public static final String ENCODING_TYPE_UTF8="UTF-8";
}
Implement this interface in your all class where you like to use constants.You can use by calling
ICommonConstants.ENCODING_TYPE_UTF8
Code duplication is a code smell and if you wouldn't use readily available constants you need to re-declare the String over and over again for each class using it, which is bad.
This leads to less maintainable code, because when the duplicated String needs to change and you forget to update it in one of the classes, the code breaks.
It's common practice to set up a class holding reusable constants:
public final class MyDefs {
public static final String A = "a";
public static final String B = "b";
private MyDefs() {
// Utility class, don't initialize.
}
}
I would recommend an Enum, or you could just have sort of like a utility class with just static final strings. All depends on what you want do i guess, i don't see anything bad. if the class is going to be shared by many classes, that's fine.

Starting a new project, how to structure it? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
I have a very simple task in Java, and I am not sure which structure to give to my project.
I want to create a little project in Java, that makes some statistical calculations. For example, I will need to create a method that gets an array, and returns the mean, another method gets an array, and returns a standard deviation, I will also need a method that gets two arrays, and returns the correlation coefficient.
What I want to know, is how to do this now that I have opened a new project in Eclipse ?
Should it all be in one class ? Should I have a separate class for each method, making it a static method ? At the end, I want to give this code for someone else to integrate it in his project. I need to do it as simple and efficient as possible.
Can you please guide me on how to do it ? One class, several classes ? Public / private ? I am not familiar with these things, but I can program the methods themselves.
Thank you in advance
All your methods have the following attributes:
That they don't possibly have another implementation as long as your give them specific enough names. After all mathematical doesn't change. This means you don't possibly need structure like interfaces or subclasses.
That when people use them they have tendency to use several of them or group by functionality. That means you should group your methods by usage e.g. statistical methods; signal processing methods; and so on.
That the methods don't keep internal status and all the output is returned without any side effect of other callers/threads. Thus your methods don't have to have class contain themselves or any statue variables.
That your methods essentially provider utility to the main program but the semantics of the methods doesn't vary due to the caller or calling context.
So as all the above shows, your methods should be inside 1 or several classes as grouped by their nature or usage. The methods should be static methods without any side effect. That's exactly what java.lang.Math does.
I want to create a little project in Java, that makes some statistical calculations. For example, I will need to create a method that gets an array, and returns the mean, another method gets an array, and returns a standard deviation, I will also need a method that gets two arrays, and returns the correlation coefficient.
Looks to me that you are interested in creating a utility class for statistical calculation. The scope of how to achieve is this quite broad but it is advised to follow common coding conventions and basic OOP concnepts.
Should it all be in one class ? Should I have a separate class for each method, making it a static method ?
Since each of the methods ( mean, standard deviation ...) are related to the same core background (i.e to perform some statistical calculation), it seems logical to have a single utility class with a separate static methods for each of the function that you need to create.
Of-course you will have to take care of the basic OOP concepts like (data hiding) keeping the fields private and exposing them properly public getter/setters. Also, it would be a good idea to keep your calculation methods private and just exposing a public method which calls your private functions. Something like
public class MyUtilityClass{
// A bunch of private fields
int field1; ...
private MyUtilityClass(){} // We don't want anyone to create an object of this class
// method exposed to user
public static float calcArithmeticMean(float[] arr1, float[] arr2){
return getMean(arr1, arr2);
}
// method for internal use
private float getMean(float[] f1, float[] f2){
//do your calculation here
}
// remember to expose only those fields that you want the user be able to access
// getter/setters here
}
At the end, I want to give this code for someone else to integrate it in his project.
If you follow proper OOP coding conventions, then your utility class will be portable and anyone will be able to understand and extend it in their application.
I would create a single class representing the array of numbers itself.
public class DataSet extends HashSet<Double> {
public double mean () {
// implementation
}
public double standardDeviation () {
// implementation
}
public double correlationCoefficient (DataSet other) {
// implementation
}
}
My first suggestion is to start your project using Maven. It gives you a solid project structure with a great tool to manage your jar file dependencies and build lifecycle. In addition, all major Java IDEs, including Eclipse, easily create, understand and use your Maven settings.
Secondly, for your application design, it is recommended to avoid using lots of static methods because they hurt testability of your code as for example explained here.
Regarding the number of classes and methods, it depends on your specific use case but the guideline is to try to aggregate similar methods, based on their responsibilities, in one class while separating classes if there are too many responsibilities being handled by a single class. Low coupling and high cohesion are your friends in this case.
Arrays may be slightly faster than collections but be careful with them because they are reifiable and do not mix well with generics. Generally, rely on Collections. Also, if you can use Java version 8, have a look at Streams API.
Last but not least, Java has tons of open source code out there. So, always look for a library before starting to write one. In case of Math, have a look at this and that.
Create one class with a different methods with public access for each calculation type(one method for each of mean, standard deviation and so on). These methods can internally refer to helper methods in another utility class(es) not publicly accessible, as per your convenience.
Put all these classes in a single package and export it for integrating in other projects.
Since it will be used by others as a library by others , make sure you document and comment it as much as possible.
I vote for single class. The methods should be static and the parameters that you don't want to show should be private.
It depends on many thing such as other part of project, future changes and extensions,...
I suggest to start with single-class/public-static and change it in demand when you expand the project.

What are the things to be kept in mind when aiming for a good class design? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this question
Yesterday I have attended interview in one Leading IT Service company. Technical interview was good, no issues, then I have moved to another set of round about Management, Design and Process. I have answered everything except the below question.
Question asked by interviewer:
Let say you are developing a class, which I am going to consume in my
class by extending that, what are the key points you keep in
mind? Ex, Class A, which has a method called "method A" returns a Collection,
let say "list". What are the precautions you will take?
My Answer: The following points I will consider, such as:
Class and method need to be public
Method 1 returns a list, then this needs to be generics. So we can avoid class cast exception
If this class will be accessed in a multi-threaded environment, the method needs to be synchronized.
But the interviewer wasn't convinced by my points. He was expecting a different answer from me but I am not able to get his thought process, what he was excepting.
So please provide your suggestions.
I would want you holding to design principles of Single Reaponsibility, Open/Close, and Dependency Injection. Keep it stateless, simple, and testable. Make sure it can be extended without needing to change.
But then, I wasn't interviewing you.
A few more points which haven't been mentioned yet would be:
Decent documentation for your class so that one doesn't have to dig too deep into your code to understand what functionality you offer and what are the gotchas.
Try extending your own class before handing it out to someone else. This way, you personally can feel the pain if you class is not well designed and thereby can improve it.
If you are returning a list or any collection, one important question you need to ask is, "can the caller modify the returned collection"? Or "is this returned list a direct representation of the internal state of your class?". In that case, you might want to return a copy to avoid callers messing up your internal state i.e. maintain proper encapsulation.
Plan about the visibility of methods. Draw an explicit line between public, protected, package private and private methods. Ensure that you don't expose any more than you actually want to. Removing features is hard. If something is missing from your well designed API, you can add it later. But you expose a slew of useless public methods, you really can't upgrade your API without deprecating methods since you never know who else is using it.
If you are returning a collection, the first thing you should think about is should I protect myself from the caller changing my internal state e.g.
List list = myObject.getList();
list.retainAll(list2);
Now I have all the elements in common between list1 and list2 The problem is that myObject may not expect you to destroy the contents of the list it returned.
Two common ways to fix this are to take a defensive copy or to wrap the collection with a Collections.unmodifiableXxxx() For extra paranoia, you might do both.
The way I prefer to get around this is to avoid returning the collection at all. You can return a count and a method to get the n-th value or for a Map return the keys and provide a getter, or you can allow a visitor to each element. This way you don't expose your collection or need a copy.
Question is very generic but i want to add few points:
Except the method which you want to expose make other methods and variable private. Whole point is keep visibility to minimum.
Where ever possible make it immutable, this will reduce overhead in mutithreaded environment.
You might want to evaluate if serializability is to be supported or not. If not then dont provide default constructor. And if serializable then do evaluate serialized proxy pattern.

Categories