Trouble with static private classes in java - java

If I have a java class SpecificDialog and inside that class I have a public static class Builder used to build an object of a SpecificDialog then the reason why the Builder is inside SpecificDialog is because it logically belongs there as it can only be used to build SpecifcDialogs. Is this the main reason?
But then if Builder is inside SpecificDialog then my SpecificDialog has access to every private field/member of the Builder. This may be undesirable because I can inadvertently modify some such private Builder's field from the outside SpecificDialog.
Is it there nothing can be done about that and, if not, shall I understand that this is not a big concern?

Whatever design you might choose, you'll always be able to inadvertently do something that shouldn't be done. Making a builder a static inner class of the class it builds is a common idiom that is used precisely because the outer class can access the private fields of the builder. Consider the builder as an integral part of the outer class, just like a private field or method, and make sure the class and its builder behave as they should.

The main reason for declaring inner classes is to structurally separate and reorganize complex code, and provide ways to deal with Java's shortcomings with callbacks (e.g. as an equivalent to closures, which will at last be available in Java 8).
Since inherently, the inner class is a structural part of the outer class, full access to all members is not only okay, but desirable - it is what actually makes this a useful tool! Without this feature, inner classes would behave exactly in the same way any class does - and therefore provide no advantage.

Related

Final class with private constructor, what is the design principle

I was recently going through one of the Netflix open source project
There I found use of both final class along with private constructor. I fully aware that
final is to avoid inheritance
private is to disallow instantiation
But m just curious to know why they are both used together. Although methods are static, so we can use them without instantiation but still eager to know design principle behind it.
With this code you will have this features
Not allow anyone subclass (extends) your class
Not allow instantiating your class
Making a variables or classes final increase the performance (not much, but it does and used as common practice in big projects will make a difference)
In this case I can't see a singleton pattern to get an instance, so, IMHO, you're looking to a helper/util class in the Netflix API, where the developer team used some standard practices to ensure users use their classes in the correct way:
StaticFinalClassExample.methodYouWantToCall();
Also, looking at the class you linked:
/**
* This class consists exclusively of static methods that help verify the compliance of OP1A-conformant....
*/
And:
//to prevent instantiation
private IMFConstraints()
{}
ADD ON:
If you want further info, take a look at Item 4 from Joshua Bloch's Effective Java (2nd Edition):
Item 4: Enforce noninstantiability with a private constructor
Occasionally you’ll want to write a class that is just a grouping of static methods and static fields. Such classes have acquired a bad reputation because some people abuse them to avoid thinking in terms of objects, but they do have valid uses.
They can be used to group related methods on primitive values or arrays, in the manner of java.lang.Math or java.util.Arrays.
They can also be used to group static methods, including factory methods (Item 1), for objects that implement a particular interface, in the manner of java.util.Collections.
Lastly, they can be used to group methods on a final class, instead of extending the class.
Such utility classes were not designed to be instantiated: an instance would be nonsensical. In the absence of explicit constructors, however, the compiler provides a public, parameterless default constructor. To a user, this constructor is indistinguishable from any other. It is not uncommon to see unintentionally instantiable classes in published APIs.
Attempting to enforce noninstantiability by making a class abstract does
not work. The class can be subclassed and the subclass instantiated. Furthermore, it misleads the user into thinking the class was designed for inheritance (Item 17).
There is, however, a simple idiom to ensure noninstantiability. A default constructor is generated only if a class contains no explicit constructors, so a class can be made noninstantiable by including a private constructor.
That class consists of static so called "utility" methods, and therefore you don't need an instance of it, and further, it's WRONG to try to get an instance of it. The class is final so that a client developer doesn't have the option of coming along and extending the class, because that would be against the intention of the original class.
There are basically 2 uses for private constructors: to tightly control instantiation in the case of a class that you want to restrict creation of (for example, if it requires a ton of resources). In this first case, you have to provide static factory methods that create an object for the client.
ie:
public static IMFConstraints getInstance()
The other case is if it's never valid to make an instance. In that case, you provide static methods, which are called on the class itself. ie:
public static void checkIMFCompliance(List<PartitionPack> partitionPacks)
You would call the above method like so:
// your cool client code here...
IMFConstraints.checkIMFCompliance(myPartitionPacks);
// more of your awesome code...
The class you linked is the latter case.

Is it possible to generate an inner class of a class to compile with an annotation processor?

I am wondering if it would be possible to generate a class, via an annotation processor, that would be an inner class of a class to be compiled.
For instance, while compiling class A, generate class A$Foo. I wonder if there is a trick that could be used or not. I got the feeling that it might be possible to generate some source that will be compiled in the same byte code as an inner class would. And, at compile/runtime, the JVM would take it for an inner class, and allow accessing outer class private fields.
The idea behind that question, which is not a noobie question, though it may look more or less technical, is to be able to use the private visibility modifier for annotated fields like Dagger, ButterKnife, etc. The private modifier allowing to detect unused fields more easily, whereas package private protection hides them.
Or is there any workaround, any way to get the best of both words ?
Given your use case, no.
An inner class is a normal Java class, living in a different .class file. When compiled, a hidden constructor param is added to the inner class constructor. Private fields in the outer class are made accessible by adding hidden accessor methods in the outer class. All of this happens at compile time.
The JVM has nothing to do with that. If you generate a class that "looks like an inner class of another class", that won't make the outer class fields accessible.
Private visibility is really just a hint to compiler. There is no problem to access those fields at the runtime at all (like I do in my small dependency injector: https://github.com/ko5tik/andject)
And non-static inner classes on android are generally a bad idea as it used to have performance penalty.
At the compile time you could use source generation tool like xdoclet (though it became technically obsolete years ago, but still occasionally used) and generate all the sources you need in advance before compiling them.

Is it good practice to create an inner class for simple functionality?

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.

Accessing methods/fields in public class from private class

Is it bad practice or "dumb" to access methods/fields that are private in the public class from private classes in the same file. In my case I have a method that add components in my GUI to panels(GridBagLayout) so I have made a method for this. However I have three panels so instead of making a addComponent-method in each private class I have the private method addComponent in the public class.
This is a overview of my class:
RegisterQuestionGUI (public)
This class has many methods, one of them is a private method named addComponent.
I also have three private classes that extend JPanel, and all of these classes use the addComponent in exactly the same way.
So back to my question, is this a good/bad way of doing it?
Thanks in advance.
A private inner class is part of the public "outer" class. Therefore, accessing the private members of the outer class is perfectly acceptable.
In general, I don't see an issue with it. Private inner classes are part of the implementation of the outer class, so encapsulation is not broken. OTOH getting rid of duplication is a good thing.
AFAIK this idiom is used many times in the class library (it is there for a reason, after all :-), e.g. when implementing Iterators in the Collection Framework. Its typical usage tends to have the following common traits:
you need to implement a specific interface without publishing the concrete implementation class, however
the implementation is tightly bound to some public class (making the two in fact a component).
Implementing the interface in a private inner class nicely satisfies both constraints at once, making the logical codependency of the two classes explicit, and encapsulating the implementation class.
It is excellent.
You need private classes because (I guess) you have to implement certain interfaces (i.e. EventListener etc). You make them inner classes because they are irrelevant beyond outer class. But you re-use the code creating private utility in outer class. So, you are a good programmer.
It depends.
If the private classes are trivial helpers, it can be reasonable to think of them as part of the implementation of the main class.
However, you might want the private class to access only non-private methods of its containing class if:
It is a non-trivial nested class.
If you might someday want to move the nested class, for example, to become a top-level class.
I'd say that was perfectly acceptable - I've done similar things in the past. Accessing private variables from an inner class is allowed for a reason, in many situations (not just this one) it makes sense to do so.
In general this is fine. However, depending on what these JPanel classes are, it might make more sense to break them out a separate classes. Maybe even have them implement the same interface so that your RegisterQuestionGUI can interact with them the same way.

Java (anonymous or not) inner classes: is it good to use them?

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.

Categories