I have a class that consists only of static member variables and static methods. Essentially, it is serving as a general-purpose utility class.
Is it bad practice for a class to contain only static member variables and static methods?
No, I don't think so at all. It is worse practice to have a class full of instance methods which don't actually depend on a particular instance. Making them static tells the user exactly how they are intended to be used. Additionally, you avoid unnecessary instantiations this way.
EDIT: As an afterthought, in general I think its nice to avoid using language features "just because", or because you think that that is the "Java way to do it". I recall my first job where I had a class full of static utility methods and one of the senior programmers told me that I wasn't fully harnessing the OO power of Java by making all of my methods "global". She was not on the team 6 months later.
As long as the class has no internal state and is essentially what is known as a leaf class (utility classes fall into this category), in other words it is independent of other classes. It is fine.
The Math class being a prime example.
Sounds reasonable.
Note: Classes that do this often have a private no-arg constructor just so that the compiler yields an error if a programmer tries to create an instance of the static class.
Static methods don't worry me much (except for testing).
In general, static members are a concern. For example, what if your app is clustered? What about start-up time -- what kind of initialization is taking place? For a consideration of these issues and more, check out this article by Gilad Bracha.
It's perfectly reasonable. In fact, in C# you can define a class with the static keyword specifically for this purpose.
Just don't get carried away with it. Notice that the java.lang.Math class is only about math functions. You might also have a StringUtilities class which contains common string-handling functions which aren't in the standard API, for example. But if your class is named Utilities, for example, that's a hint that you might want to split it up.
Note also that Java specifically introduced the static import: (http://en.wikipedia.org/wiki/Static_import)
Static import is a feature introduced
in the Java programming language that
members (fields and methods) defined
in a class as public static to be used
in Java code without specifying the
class in which the field is defined.
This feature was introduced into the
language in version 5.0.
The feature provides a typesafe
mechanism to include constants into
code without having to reference the
class that originally defined the
field. It also helps to deprecate the
practice of creating a constant
interface: an interface that only
defines constants then writing a class
implementing that interface, which is
considered an inappropriate use of
interfaces[1].
The mechanism can be used to reference
individual members of a class:
import static java.lang.Math.PI;
import static java.lang.Math.pow;
or all the static members of a class:
import static java.lang.Math.*;
While I agree with the sentiment that it sounds like a reasonable solution (as others have already stated), one thing you may want to consider is, from a design standpoint, why do you have a class just for "utility" purposes. Are those functionals truly general across the entire system, or are they really related to some specific class of objects within your architecture.
As long as you have thought about that, I see no problem with your solution.
The Collections class in Java SDK has static members only.
So, there you go, as long as you have proper justification -- its not a bad design
Utility methods are often placed in classes with only static methods (like StringUtils.) Global constants are also placed in their own class so that they can be imported by the rest of the code (public final static attributes.)
Both uses are quite common and have private default constructors to prevent them from being instantiated. Declaring the class final prevents the mistake of trying to override static methods.
If by static member variables you did not mean global constants, you might want to place the methods accessing those variables in a class of their own. In that case, could you eleborate on what those variables do in your code?
This is typically how utility classes are designed and there is nothing wrong about it. Famous examples include o.a.c.l.StringUtils, o.a.c.d.DbUtils, o.s.w.b.ServletRequestUtils, etc.
According to a rigid interpretation of Object Oriented Design, a utility class is something to be avoided.
The problem is that if you follow a rigid interpretation then you would need to force your class into some sort object in order to accomplish many things.
Even the Java designers make utility classes (java.lang.Math comes to mind)
Your options are:
double distance = Math.sqrt(x*x + y*y); //using static utility class
vs:
RootCalculator mySquareRooter = new SquareRootCalculator();
mySquareRooter.setValueToRoot(x*x + y*y);
double distance;
try{
distance = mySquareRooter.getRoot();
}
catch InvalidParameterException ......yadda yadda yadda.
Even if we were to avoid the verbose method, we could still end up with:
Mathemetician myMathD00d = new Mathemetician()
double distance = myMathD00d.sqrt(...);
in this instance, .sqrt() is still static, so what would the point be in creating the object in the first place?
The answer is, create utility classes when your other option would be to create some sort of artificial "Worker" class that has no or little use for instance variables.
This link http://java.dzone.com/articles/why-static-bad-and-how-avoid seems to go against most of the answers here. Even if it contains no member variables (i.e. no state), a static class can still be a bad idea because it cannot be mocked or extended (subclassed), so it is defeating some of the principles of OO
I wouldn't be concerned over a utility class containing static methods.
However, static members are essentially global data and should be avoided. They may be acceptable if they are used for caching results of the static methods and such, but if they are used as "real" data that may lead to all kinds of problems, such as hidden dependencies and difficulties to set up tests.
From TSLint’s docs:
Users who come from a Java-style OO language may wrap their utility functions in an extra class, instead of putting them at the top level.
The best way is to use a constant, like this:
export const Util = {
print (data: string): void {
console.log(data)
}
}
Examples of incorrect code for this rule:
class EmptyClass {}
class ConstructorOnly {
constructor() {
foo();
}
}
// Use an object instead:
class StaticOnly {
static version = 42;
static hello() {
console.log('Hello, world!');
}
}
Examples of correct code for this rule:
class EmptyClass extends SuperClass {}
class ParameterProperties {
constructor(public name: string) {}
}
const StaticOnly = {
version: 42,
hello() {
console.log('Hello, world!');
},
};
Is there any best practice regarding whether or not nested packages and classes is a good idea?
A) nested packages
i.e. Is it a good idea to have
utils
XXX.java
xxxx
XXX.java
XXX.java
model
view
activity
fragment
dialog (dialogfragment)
errors
sth
B) nested class
i.e. Is it a good idea to have
class Const {
class static HOST {
public final static String STAGING = "";
public final static String PRODUCTION = "";
}
class static Foo {
}
}
I would suggest you to take a look at this GitHub https://github.com/googlesamples/android-architecture made by Google developers. It provides samples to build Android apps using different architectural concepts and tools. Hope it helps.
A) There is no specific rule about package but a simple rule of thumb is that you should try to minimize package dependency cycling.
That means one package can depend on an other (or multiple other)
package and use their classes but the required package should minimize
the dependency to the first package. so the dependeny calls should
only go into one direction.
The more common packages are usually Activities, Fragments, Services, Receivers, Adapters, Models, Utilities and Helper Classes, Network and Database Packages.
B) Usually it's not a good practice to define inner classes especially for libraries that parse classes Dynamically like GSON. But if you are defining a Class that is Only used by a Specific Class you can encapsulate First class into the Second one for the sake of re-usability.
I've been using Eclipse as my IDE. I also use it to export my application into a JAR file. When I look at my classes in the JAR file, a few of my classes contain the name of that class, a dollar sign, then a number. For example:
Find$1.class
Find$2.class
Find$3.class
Find.class
I've noticed it does this on bigger classes. Is this because the classes get so big, it compiles it into multiple classes? I've googled and looked on multiple forums, and search the Java documentation but have not found anything even related to it. Could someone explain?
Inner classes, if any present in your class, will be compiled and the class file will be ClassName$InnerClassName. In case of Anonymous inner classes, it will appear as numbers. Size of the Class (Java Code) doesn't lead to generation of multiple classes.
E.g. given this piece of code:
public class TestInnerOuterClass {
class TestInnerChild{
}
Serializable annoymousTest = new Serializable() {
};
}
Classes which will be generated will be:
TestInnerOuterClass.class
TestInnerOuterClass$TestInnerChild.class
TestInnerOuterCasss$1.class
Update:
Using anonymous class is not considered a bad practice ,it just depends on the usage.
Check this discussion on SO
This is because you have anonymous classes within this larger class. They get compiled using this naming convention.
See The Anonymous Class Conundrum
In addition to the above cases presented by #mprabhat, the other cases could be:
if you class contain a enum variable a separate class would be generated for that too. The name of the .class generated would be ClassName$Name_of_enum.
If your class X is inheriting i.e. extending another class Y, then there would be a .class generated with the name ClassName$1.class or ClassName$1$1.class
If your class X is implementing an interface Y, then there would be a .class generated with the name ClassName$1.class or ClassName$1$1.class.
These cases are derivations of my inspection on .class files in jar.
To answer your comment about are anonymous classes bad. They are most definately not.
Consider this to assign an action listener to a JButton:
JButton button = new JButton(...);
button.addActionListener(new ActionListener() { ... });
or this to do a case insensitive sort by the "name" property
Collections.sort( array, new Comparator<Foo>() {
public int compare(Foo f1, Foo f2) {
return f1.getName().toLowerCase().compareTo(f2.getName().toLowerCase());
}
});
You'll also see a lot of Runnable and Callable done as anonymous classes.
I noticed myself constantly typing:
someVar = getResources().getString(R.string.someString);
I have several XML files that I am parsing and building and in order to make sure that the files stay consistent, I have placed the tag names in the res/values/strings.xml file. The same handles are used throughout several activities, and some of those activities extend ListActivity while others do not so creating a simple super class which houses these variables ( ex:
public class thisClass extends thatClass
{...}
public class thatClass
{
package String someTag = "this";
package String otherTag = "that";
}
I would assume that all of these calls to getResources() could get pretty taxing and was wondering if it is beneficial to instead create an R-type file where I can store these types of commonly used variables statically ex:
public final class globalVars
{
public static final class XML_TAGS
{
static final String someTag = "this";
static final String otherTag = "that";
}
}
and to reference these variables like such:
serializer.startTag("", globalVars.XML_TAGS.someTag);
instead of
serializer.startTag("", getResources().getString(R.string.someTag));
Thanks for the input!
OK, after looking into the source code of android.content.res.resources and some other classes, it is evident that using Resources and getting resources through getResources() is costly compared to a static class.
Indeed, the instance of Resources returned is not a static container but rather an object that gets resources by executing a couple of statements (whether a string or drawable or any other form).
However, using getResources() has its advantages:
It helps you externalize your resources.
For any type of resource, you can specify default and multiple alternative resources depending maybe on Locale, Screen Depth/Resolution...
A static container might provide a less costly alternative than using resources but remember: any later attempt at localization would be relatively extremely costly.
What's the difference between file, class and activity in android?
File - It is a block of arbitrary information, or resource for storing information. It can be of any type
Class - Its a compiled form of .Java file . Android finally used this .class files to produce an executable apk
Activity - An activity is the equivalent of a Frame/Window in GUI toolkits. It is not a file or a file type it is just a class that can be extended in Android for loading UI elements on view
Class -
A class is a combination of methods, variables and data types. Every Java or Android project must have at least one class.
Example:
public class shape{
public void circle()
{
int A,B,radias;
}
}
Activity -
An Activity is an android class. If we want to use an activity class, we must use extend Activity in your android project.
Example:
public class shape extends Activity{
public void circle()
{
int A,B,radias;
}
}
File is a file on the filesystem. Class is a Java class. Activity is a specific java class commonly used in Android.
1) Class is Blueprint of object and you will create as many object you want from same class. You can create new object by “new” keyword. In example below “ArrayList” is class and “obj” is object.
ArrayList<String> obj=new ArrayList<String>
2) Activity :- Every program has some starting point. In android Activity is starting point of any application you made. It is basically a GUI of the app. In android app every activity have to inherent directly or indirectly from Activity Class which is predefined in the android system. So activity is also a class but a special one. So you can say that “Every activity is a class but every class is not Activity”.
3) File :- file is used to store data so you can reuse again when you app start.
An activity is actually a class (click) and if you want to make your own activity you choose this one as parent class.
And the source code of classes is defined in files, actually every class should be described in its own file.
That's some basic knowledge of object oriented programming - you might want to have a look here to find more information