Let's say I have a Java class A, which requires a helper class B. That helper class is only used in A, and has no other purpose. Also, B doesn't need to use A in any way (don't call methods or access fields).
So, the question is: where to put B?
There are the following options:
Static nested class. In my opinion, it just makes code less clear (much more indentation and such).
public class A {
...
private static class B { ... }
}
Non-public class in the same source. I like this option.
public class A {
...
}
class B {
...
}
Non-public class in the separate source. Looks like this option has a little overhead, though.
// A.java
public class A {
...
}
// B.java
class B {
...
}
For now, I prefer the 2nd option. What are your thoughts on it? What is the best practice?
Are there any authoritative sources on it?
I strongly vote for option (1). The idea is, that class B is only needed by class A and option (1) is the only alternative that clearly expresses that intention: class B is part of class A.
You can use a static nested class within A.Better encapsulation since a nested class a way of logically grouping classes that are only used in just one place. does your helper class just contain fields?
was it helpful?
There are no serious disadvantages, but one can certainly figure out at least few including:
Difficult to understand - especially for non-experiences programmers, who may find it difficult to code, enhance, and maintain.
More number of classes - it certainly increases the total number of classes being used by the application. For every class loaded into the memory, JVM creates an object of type Class for it. There may be some other routine tasks, which JVM might be required to do for all the extra classes. This may result in a slightly slower performance if the application is using several nested/inner classes (may be due to a poor design).
Limited support by the Tools/IDE - Nested classes don't enjoy the same support as the top-level classes get in most of the tools and IDEs. This may irritate the developer at times.
Related
There are some different opinions about simple inner classes, so I was wondering if there is a general consensus on what is good, and when to use private inner classes.
Here's an example that I found, and for which I think it's unnecessary to create an inner class. How good/bad practice is this?
private static class InternalCounter {
int count;
public InternalTabManager() {
count = 0;
}
public int increment() {
return count++;
}
}
Mind you that in this particular case, one instance is kept in the surrounding class to keep track of a count.
Yeah, in this case it does seem very unnecessary but if you have a case where there is some significant functionality and you know that no other class will ever need your inner class and it makes no sense to create a class more globally available then do use an inner class.
It depends on the context. If this class could've been replaced with only a single static int, then I see no need to create an inner class.
On the other hand, this code would allow the parent class objects to share a reference to mutable int (using java.lang.Integer wouldn't be possible because is immutable).
The general advice/practice/pattern in this case are Keep It Simple and You Ain't Gonna Need it - if you don't need particular behaviour, don't make your code more complex than absolutely necessary.
So, if the question is: "Is it good practice to create an inner class for simple functionality, when it could have been solved in a simpler way" then the answer is NO.
When encountered with such situations, we normally ask the developers to question themselves -
How stateful is this object going to be? Is this functionality coupled with the containing class?
Can this be a stand alone object? (purpose and reason for the existence)
Most importantly, is it cleaner?
Listeners, Presenters (UI model) are functional aspects; and deserve separate existence and are rarely modeled as static inner classes
Auditing entries, initialization constructs are non-functional/code-organization aspects; and don't give a definite answer, and IMO it is ok to use static inner classes
A definitive example for using such, would be a state transition model for a small application.
I've also used inner classes in this way but nowaday I tend more to make those classes package-private.
You get all the benefits of the inner class, while those two classes are much better to maintain (being in two separate files).
Yes, it is still possible that a class in the same package uses the class accidentally but it is VERY unlikely to happen.
When you want to inherit(extends) more than one class in one java class you can use inner class concept.here you can extend one class by outer class and another by inner class.
My rule of thumb is to use static inner classes if within a single class you have refactored to a handful of private methods that each take a similar (or the same) parameters each time. In this case I like to group those parameters together into a single inner class such that I have a type that succicently describes why those parameters are grouped together.
So I consider myself a junior java/android developer
I've always come across these but never really liked them and concidered them as dirty code
class herp{
private class derp extends OnclickListener{
...
}
private class gerp AsyncTask{
...
}
}
so should I try to avoid these? or even make sure I never use these?
What is and isn't dirty code is highly subjective.
What can be said is that nested classes can be very useful. Often times they don't need to be nested like that, as they could just as easily be anonymous classes in all likelihood.
The idea is that: you want as few other classes as necessary to access your little class there. You wouldn't want to make your own package, because you really belong in the package you're already in. Instead, you make a private class. Now only you can use it, which is good because it's tailored just for your class.
Now, how many derp instances will you have? Chances are you'd have one. So instead of doing that, I would do this:
OnClickListener derp = new OnClickListener() {
// fill in methods to override here
}
It does basically the same thing, but I can't reuse the class for anything, which is good - no one should be reusing the one-shot class!
What is and isn't clean code is often times personal preference based upon experience. Nesting classes isn't messes per say, however you should be certain that it is an appropriate situation.
If you desperately need some specific functionality for a class which extends something like the OnClickListener in your question, then it is a question of how many times do you need this class? If the answer is once, then an anonymous class would be a cleaner solution. If the answer is in every single method in the class, then a nested class clearly makes more sense.
More or less every feature in Java has a time and place in which it is considered appropriate. Private nested classes such as the ones you have in your question should be reserved in my mind for cases where you satisfy two conditions:
a) you absolutely have to have a separate class that will only be used in this class and no where else
AND
b) you will need to use that class in multiple locations within the class.
At the end of the day, nested private classes are not inherently dirty or hard to maintain, but as with any other feature of an programming language, make sure you need them.
There is no fixed answer on this question. It mainly comes down to your own coding style, preferences, and your team's coding conventions.
Private inner classes are useful for many reasons. You can use them to provide an implementation of an interface (e.g. a List implementation might define its own Iterator implementation as a private inner class) without making the concrete class visible. It protects the implementation, and allows you to provide just enough details to a user of your API/class so he can use it correctly, without cluttering your documentation with useless details (your concrete class).
You can also use private inner classes as a implementation for listeners, even though some might disagree with this philosophy. I do prefer using private inner classes to anonymous classes when the listener has some complex logic.
You might want to use them also to separate code logic into separate classes, but don't wish to expose those classes outsite your outer class.
Keep in mind that every solution using a private inner class can also be implemented without using them. And as with many things in life, using private inner classes isn't a bad practice per se, but abuse is a bad practice.
It's fine. You may consider making them static inner classes, otherwise you'll need an instance of herp to create one (although that might be what you want):
class herp {
private static class derp extends OnclickListener{
...
}
private static class gerp AsyncTask{
...
}
}
The difference demonstrated is:
public static void main(String[] args) {
// With static:
new derp();
// Without static:
new herp().new derp();
}
I was wondering if the compiler (ECJ, javac, or you can name your favourite compiler) optimizes anonymous classes which do not add or override methods of it's base class.
For example, for code that looks like this:
Snippet A:
Human h = new Human("John", 30);
h.setX(12.5);
h.setY(15.3);
//..
Eat(h);
I'd always prefer the syntax:
Snippet B:
Eat(new Human("John", 30){
{
setX(12.5);
setY(15.3);
//..
}
});
However I understand that unlike the WITH keyword we have in vb.net, this is not just syntax sugar. What we are telling the compiler to do is to create an anonymous subclass of Human whose constructor consists of the code within the bracers (which is also why we can't use this syntax-sugar for final classes).
The problem now is that I use this syntax-sugar all the time (like for example overriding onclick in UI listeners etc), it's like one of my coding style/habits.
Hence the question:
Does the compiler optimizes this kind of syntax? (i.e. it realised that no anonymous classes needs to be generated, and the performance of Snippet B would be the same as Snippet A)
If the answer to (1) is "no", I was wondering is it (the more-than-expected abundance of anonymous classes due to this coding style) a noticeable impact such that it is highly recommended that for future projects (coding applications for the average mobile device) we should always adhere to the style in Snippet A ?
Yes, it will (always) generate an anonymous class (called Human$1). You can see this by examining the class files that are output. You should have a Human.class and Human$1.class as output.
As for performance implications, there will be two classes (bigger, more work for the VM), references from one to the other (because the anonymous inner class will have a link to the outer class). This may have a effect on performance, I suppose, but only minor. You'd have to test it.
However, it's not particularly idiomatic java to do it this way. The idiomatic way would be to have another constructor.
The compiler will create a separate binary class.
For instance if you have
class Foo{
}
class Bar{
Foo otherFoo = new Foo(){
}
}
In your bin/target directory you will have three classes
Bar.class
Bar$1.class
Foo.class
Here the anonymous subclass is Bar$1.class
I know this topic has been discussed and killed over and over again, but I still had one doubt which I was hoping someone could help me with or guide me to a pre-existing post on SO.
In traditional C, static variables are stored in data segments and local variables are stored in the stack. Which I would assume will make static variables more expensive to store and maintain when compared to local variables. Right?
When trying to understand in terms of Java or C#, would this be dis-advantage for static classes when compared to singleton class? Since the entire class is loaded into memory before class initialization, I don't see how it can be an advantage unless we have small inline-able functions.
I love Singleton classes, and would hate to see it become an anti-pattern, I am still looking for all the advantages that come with it...and then loose to the argument of thread-safety among others.
-Ivar
Different from C, the static keyword in Java class definition merely means, This is just a normal class like any other class, but it just happens to be declared inside another class to organize the code. In other words, there is no behavioral difference whatsoever between the following 2 way of declaration*:
a)
class SomeOtherClass {
static class Me {
// If you "upgrade" me to a top-level class....
}
}
b)
class Me {
// I won't behave any different....
}
Class definitions are loaded to memory when the class is used for the first time, and this is true for both "static" and "non-static" classes. There are no difference in how memory will be used, either. In older JVMs, objects were always stored in heap. Modern JVMs do allocate objects on stack when that is possible and beneficial, but this optimization is transparent to the coder (it is not possible to influence this behavior via code), and use of the static keyword does not have any effect on this behavior.
Now, back to your original question, as we have seen we really can't compare static classes and Singleton in Java as they are completely different concept in Java (I'm also not sure how static classes would compare with Singleton, but I will focus on Java in this answer). The static keyword in Java is overloaded and has many meanings, so it can be confusing.
Is Singleton automatically an "anti-pattern"? I don't think so. Abuse of Singleton is, but the Singleton pattern itself can have many good uses. It just happens to be abused a lot. If you have legitimate reason to use the Singleton pattern, there is nothing wrong in using it.
*Note: Why write static at all, you might ask. It turns out "non-static" nested classes have their own somewhat complicated memory management implication, and its use is generally discouraged unless you have a good reason (pls refer to other questions for more info).
class SomeOtherClass {
Stuff stuff;
class Me {
void method(){
// I can access the instance variables of the outer instance
// like this:
System.out.println(SomeOtherClass.this.stuff);
// Just avoid using a non-static nested class unless you
// understand what its use is!
}
}
}
Singleton class is essentially a regular top-level class with a private constructor, to guarantee its singleness. Singleton class itself provides a way to grab its instance. Singleton classes are not very easy to test, therefore we tend to stick with the idea of Just Create Once.
static class is essentially a nested class. A nested class is essentially a outer level class which is nested in another class just for packaging convenience. A top-level class can not be declared as static, in Java at least -- you should try it yourself.
would this be dis-advantage for static
classes when compared to singleton
class?
Your this question became somewhat invalid now, according to the above explanation. Furthermore, a static class (of course nested) can also be a singleton.
Further reading:
Inner class in interface vs in class
The differences between one and the other is the memory management, if your app will have to instantiate a lot of things, that will burn the memory like a charm becoming a memory problem, performance and other things...
this could help...
http://butunclebob.com/ArticleS.UncleBob.SingletonVsJustCreateOne
http://www.objectmentor.com/resources/articles/SingletonAndMonostate.pdf
I'm afraid it is an anti-pattern:
http://thetechcandy.wordpress.com/2009/12/02/singletons-is-anti-pattern/
In some of my projects and in some books was said to not use inner class (anonymous or not, static or not) - except in some restricted conditions, like EventListeners or Runnables - is a best practice. They even were 'forbiden' in my first industry project.
Is this really a best practice? Why?
(I have to say that I'm using them a lot...)
-- EDIT ---
I can't pick a right answer in all these responses: there's part of rightness on mostly all of them: I'll still use inner classes, but I'll try to use them less often !
In my view, 90% of inner classes in Java code are either entities that are associated with a single class and were thus "shoved in" as inner classes, or anonymous inner classes that exist because Java does not support Lambdas.
I personally don't like seeing complex inner classes. They add complexity to the source file, they make it bigger, they're ugly to deal with in terms of debugging and profiling, etc. I like separating my project into many packages, in which case I can make most entities top-level classes that are restricted to the package.
That leaves me with necessary inner classes - such as action listeners, fake "functional" programming, etc. These are often anonymous and while I'm not a fan (would have preferred a Lambda in many cases), I live with them but don't like them.
I haven't done any C# in years, but I'm wondering if the prevalence of inner classes or whatever the C# equivalent is dropped when they introduced Lambdas.
Cleanliness. It's easier to comprehend code if it's broken into logical pieces, not all mushed into the same file.
That said, I do not consider the judicious use of inner classes to be inappropriate. Sometimes these inner classes only exist for one purpose, so I would then have no problem with their being in the only file in which they are used. However, this does not happen that much in my experience.
Anonymous classes are good to use when doing event based programming especially in swing.
Yes, forbidding inner classes is a useful practice, in that finding out a place forbids them is a good way to warn me off working there, hence preserving my future sanity. :)
As gicappa points out, anonymous inner classes are the closest Java has to closures, and are extremely appropriate for use in situations where passing behaviour into a method is suitable, if nothing else.
As some others said, many times, when you use an anonymous inner class, it is also used on some other places too...
Thus you may easily duplicate inner class code to many places...
This seems not a problem when you are using very simple inner classes to filter/sort collections, using predicates, comparator or anything like that...
But you must know that when you use 3 times an anonymous innerclass that does exactly the same thing (for exemple removing the "" of a Collection), you are actually creating 3 new classes on the java PermGen.
So if everyone use inner classes everywhere, this may lead to an application having a bigger permgen. According to the application this may be a problem... If you are working on the industry, you may program embedded applications that have a limited memory, that should be optimized...
Note this is also why the double curly brace syntax (anonymous innerclass with non-static initialization block) is sometimes considered as an antipattern:
new ArrayList<String>() {{
add("java");
add("jsp");
add("servlets");
}}
You should ask to people who forbids you to use them...
IMHO it all depends on the context...
Anonymous inner classes has benefits in being able to see the fields and variables around the "new" statement. This can make for some very clean design and is a quite nice (but a bit wordy) approach to "how can we make a simple version of lambda statements".
Named inner classes has the benefit of having a name, hopefully telling, which can be documented in the usual way, but which is tied together to the surrounding class. A very nice example is the Builder pattern, where the inner class is responsible for providing state for the initialization process instead of having numerous constructors. Such builders cannot be reused between classes, so it makes perfect sense to have the Builder tied closely to the parent class.
I suggest being cautious when using it if it needs a method parameter. I just found a memory leak related to that. It involves HttpServlet using GrizzlyContinuation.
In short here is the buggy code:
public void doGet(HttpServletRequest request, final HttpServletResponse response){
createSubscription(..., new SubscriptionListener(){
public void subscriptionCreated(final CallController controller) {
response.setStatus(200);
...
controller.resume();
}
public void subscriptionFailed(){
...
}
public void subscriptionTimeout(){
...
}});
}
So since the listener is kept by the subscription the HttpServletResponse is also kept in case the listener needs it (not obvious). Then the HttpServletResponse instance will be release only if the subscription is deleted. If you use an inner class that gets the response in it constructor it can be set to null once the call was resume releasing memory.
Use them but be careful!
Martin
One item that is not mentioned here is that a (non-static) inner class carries a reference to it's enclosing class. More importantly, the inner class has access to private members of it's enclosing class. It could, potentially, break encapsulation.
Don't use an inner-class if you have an option.
Code without inner classes is more maintainable and readable. When you access private data members of the outer class from inner class, JDK compiler creates package-access member functions in the outer class for the inner class to access the private members. This leaves a security hole. In
general we should avoid using inner classes.
Use inner class only when an inner class is only relevant in the
context of the outer class and/or inner class can be made private so that only outer class can access it. Inner classes are used primarily to implement helper classes like Iterators, Comparators etc which are used in the
context of an outer class.
Certain frameworks, like Wicket, really require anonymous inner classes.
Saying never is silly. Never say never! An example of good use might be a situation where you have some legacy code that was written by someone where many classes operate directly on a Collection field, and for whatever reason, you cannot change those other classes, but need to conditionally mirror operations to another Collection. The easiest thing to do is to add this behavior via an anonymous inner class.
bagOfStuff = new HashSet(){
#Override
public boolean add(Object o) {
boolean returnValue = super.add(o);
if(returnValue && o instanceof Job)
{
Job job = ((Job)o);
if(job.fooBar())
otherBagOfStuff.add(job);
}
return returnValue;
}
}
That said, they can definitely be used like a poor man's closures.
Inner classes are appropriate when trying to emulate multiple inheritance. It is similar to what happens under the hood with C++: when you have multiple inheritance in C++, the object layout in memory is actually a concatenation of several object instances; the compiler then works out how the "this" pointer shall be adjusted when a method is invoked. In Java, there is no multiple inheritance, but an inner class can be used to provide a "view" of a given instance under another type.
Most of the time, it is possible to stick to single inheritance, but occasionally multiple inheritance would be the right tool to use, and this is the time to use an inner class.
This means that inner classes are somehow more complex than usual classes, in the same way that multiple inheritance is more complex than single inheritance: many programmers have some trouble wrapping their mind around that concept. Hence the "best practice": avoid inner classes because it confuses your coworkers. In my view, this is not a good argument, and at my workplace we are quite happy to use inner classes when we deem it appropriate.
(A minor drawback of inner classes is that they add one extra level of indentation in the source code. This is a bit irksome at times, when one wants to keep the code within 79 columns.)
Anonymous inner classes are often used when we need to implement interface with one method, like Runnable, ActionListener and some other.
One more great appliance of anonymous inner classes is when you don't want to make a subclass of some class but you need to override one (or two) of its methods.
Named inner classes can be used when you want achieve tight coherence between two classes. They aren't so useful as anonymous inner classes and I can't be sure that it's a good practice to use them ever.
Java also has nested (or inner static) classes. They can be used when you want to provide some special access and standard public or default access levels aren't enough.
Inner classes are often used to "pass a behavior" as a parameter of a method. This capability is supported in an elegant way by other languages with closures.
Using inner classes produces some not elegant code (IMHO) because of a language limitation but it's useful and widely used to handle events and blocks in general with inner classes.
So I would say that inner classes are very useful.
yes it is good to use them, when you are trying to keep a class cohesive, and the classes should never be instantiated from outside their context of the outer class, make the constructors private and you have really nice cohesive encapsulation. Anyone that says you should NEVER use them doesn't know what they are talking about. For event handlers and other things that anonymous inner classes excel at they are way better than the alternative of cluttering up your package namespace with lots of event handlers that only apply to a specific class.
I tend to avoid non-static inner classes for the reasons given by other posters. However I have a particularly favourite pattern where a non-static inner class works very effectively: Lazy loading stateful classes.
A typical lazy loading stateful class is constructed with an entity ID and then on demand can lazily load additional entity information. Typically to lazily load the additional information we will require dependencies. But dependencies + state == anti pattern!
Non-static inner classes provide a way to avoid this anti-pattern. Hopefully the following simple example illustrates this better than words can:
/*
* Stateless outer class holding dependencies
*/
public class DataAssembler {
private final LoadingService loadingService;
#Inject
DataAssembler(LoadingService loadingService) {
this.loadingService = loadingService;
}
public LazyData assemble(long id) {
return new LazyData(id);
}
/*
* Stateful non-static inner class that has access to the outer
* class' dependencies in order to lazily load data.
*/
public class LazyData {
private final long id;
private LazyData(long id) {
this.id = id;
}
public long id() {
return id;
}
public String expensiveData() {
return loadingService.buildExpensiveDate(id);
}
}
}
Worth noting that there are many other patterns beyond the above example where inner classes are useful; inner classes are like any other Java feature - there are appropriate times where they can be used and inappropriate times!
When use or avoid inner class in Java?
The inner class has the following characters.
Anyway the .class file is separated as OuterClassName$InnerClassName.class
The class name and the class file name of the inner class always contain the outer class name.
The above characters disclose this fact. The outer class name is the mandatory information for the inner class.
We can derive this result from the fact. The inner class is good to be defined when the outer class is mandatory information of the inner class.
The characters of the inner class make developers sometimes annoying to debug. Because it forces the developer to know the outer class name with the inner class.
Suggestion
It can be a design principle to avoid defining the inner class except when the outer class name is the mandatory information of the inner class for the above two reasons.