abstract class, all derived concrete classes should be singletons - java

I'm looking for best practices for the following design: I have an abstract class and every concrete class extending that abstract class should be a singleton.
Background: The concrete classes are collectors that compile and log statistics about the operation of a complex legacy system. Collectors are accessible via a static registry, so there's no need to pass dependencies. The abstract class provides the interface to the registry.
I'm aware that there's no perfect solution that gives guarantees, properties have to be maintained by conventions. Nevertheless, there might be best practices for this case.

Technically you cannot prevent the concrete class to allow the creation of more than one instance of it.
But you have ways to try to conceptually enforce it :
document clearly the interface
set a constraint that require that these subclasses be beans managed by a dependency injection container

There is a solution to implement this, it is based on the following:
The constructors of the abstract class must have private visibility, so that it could be instantiated from inside only and to prevent it from being extended elsewhere.
The implementing singleton classes must be nested within the abstract class and must not be extendable.
The instances of the implementing nested classes are static members of the abstract class.
The drawback of this approach is that it can quickly become messy, due to nesting, especially if there are many implementations for singletons.
This might look as follows:
public abstract class AbstractEntity {
public static final AbstractEntity SINGLETON1 = new EntityImpl1(); // might be also instantiated lazily
/**
* Private accessor will not allow this class to be extended from outside.
*/
private AbstractEntity() {
}
static final class EntityImpl1 extends AbstractEntity {
private EntityImpl1() {
}
}
// other implementations...
}

Here is my current solution
singleton property is managed by the registry. JavaDoc clearly states the correct and intended use
a concrete instance is registered by a static register(Instance.class, Instance::new) method that has the class object and a supplier of instances of that class as arguments
the registry maintains a map of String to instance objects, with the toString() result of the class object as key
Advantages
instances can be private and can be placed close to the classes that using them (i.e., in the same package)
instances are created once at first registry
Disadvantages
instances are created by a constructor with empty parameter list
the registry method needs two arguments

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.

Does a class without fields have a special name?

What is a class without fields called? I'm a beginner in programming Java and I'm trying to understand and learn about classes, so i have the following class "DalUser" that doesn't have fields, only methods, like validateSession in a folder called Dal:
import com.app.Be.BeUser;
public class DalUser{
public BeUser validateSession(String user, String password)
{
...
}
I have a class BeUser that has the fields user and password and is located in another folder or package called Be. is this a particular type of class or is a common class despite not having any fields?
What is a class without fields called?
There is no universally applicable name for this1:
Classes with no fields have no explicit state, but strictly speaking, every Java object has state associated its mutex. Hence calling them "stateless classes" is a bit of a stretch.
Classes with no fields may be "helper classes", but the absence of fields is neither a necessary or sufficient precondition.
An instance that has no state is also immutable, so you could call Classes with no fields an "immutable classes" ... though the locking use-case applies here too.
Another distinction between helper classes and stateless classes is whether the class is designed to be instantiated. A helper class (in normal usage) consists of static methods, and is not instantiated. (An instance serves no purpose). A stateless class is often designed to be instantiated, and passed around to other classes which will actually make method calls on the instance; e.g. as a "policy object".
Then there is a sub-case of the "base class" use-case where there are no fields in the base class. (In that case, calling the class "stateless" is misleading, since there is typically state in the child classes.)
In short, you need to examine the class and how it is actually being used to determine which label (or labels) best apply to it.
In your specific example, the code is best described as a stateless class. That is because it is designed to be instantiated and passed around in different contexts, but the functionality does not depend on any state of the object itself.
Here are some other examples to illustrate why there is no simple answer to this.
1) This is a helper class, but it has a (static) field.
public class Plumbing {
private static nosTapsFixed;
private Plumbing() { }
public class fixTap(Tap t) {
// fix 't'
}
}
2) This is a base class. It has no fields, but it is clearly not intended as a helper class.
public abstract class Tradesman {
// no fields
public abstract Invoice issueInvoice();
}
3) Here is a use of a class with no fields (java.lang.Object) in a way that is clearly not a "helper".
final Object myLock = new Object();
...
synchronized (myLock) {
...
}
4) And here is another example of a class that has no fields but is and not a helper.
public enum Agreement {
YES, NO
}
1 - But if you really want a name, how about a "villein class". Villeins didn't own any fields ....
These are called helper classes or utility classes, although the methods are usually declared static. Examples include java.util.Arrays and java.util.stream.StreamSupport. Often, they might have a pluralized name (for example, a helper class that works with Widget objects might be called Widgets.
Classes without any internal fields are stateless. A class that derives from a class with internal state (fields) would still have fields in the super class. So such a class would not be considered stateless.
Classes will often have more specific names depending on what they are used for. Your example above appears to be a validator class.

Initialize member of abstract class without subclasses having write access

I have an abstract class:
public abstract class AbstractCommand {
private static State state;
}
Intention
An object of class State is provided by some "controlling classes", providing data that is needed by each AbstractCommand subclass
Each subclass needs read access to it
The subclasses are not allowd to change the field
Current approach
The field state should be initialized by the "controlling classes" of the program so that subclasses (that define commands) can use it (read-only). The subclasses are defined internally and should be used as an interface for the user. This user should not have write access to state.
The problem
Adding a public setState() method in AbstractCommand would make it accessible to all subclasses and with that to the user
Making the field final would force the creating of the object to take place in the abstract class and the "controlling classes" would have to use this object, furthermore it would not be replacable
How do you handle something like this?
Another try
Because some answers suggested solutions using package visibility I wonder if this would do a good job:
Have a class in the same package that provides the required information by delegating a call from the "controlling classes" (from outside the package) to the abstract class.
Sounds a little fuzzy, too but what do you think?
If I understand you correctly, you are looking for the protected keyword.
In java this keyword allows for subclass and package field access, but does not make the field public. This allows for the public read-only behavior you're looking for without sacrificing the public protection of the field. The only classes that can access a protected field directly will be anything in the same package or a direct subclass (which may be in a different package).
Source: http://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html
You could put the AbstractCommand into the same package with the "controlling classes" and specific implementations to another package. Then you could provide a package-private setter and protected getter. This would allow the controlling classes set the value and implementations would only have access to the getter.
Howevery, this would mess your package structure. If you do not want this to happen - try to use a Factory. You culd build the following package structure:
command
impl
CommandImpl1 //extends AbstractCommand
CommandImpl2 //extends AbstractCommand
AbstractCommand
CommandFactory
The idea is that a Factory is used to create instances of an AbstractCommand. So you will pass the parameter to the Factory in any other package and it would select an implementation you need and return you a new object. In this case you could use the previous idea to grant proper access to the getters and setters. However here you would be able to set the field once and forever.
If you need to modify it many times, you could create an assessor. This is the CommandAccessor class in the same package as your AbstractCommand and it should provide the static methos like:
public static void setState(State newState, AbstractCommand command);
Nothing would prevent you from using it in the implementation classes, however you could just set an informal rule that it should no be used.
I can only offer fuzzy solutions.
Some solutions first:
Either do
private static final State state = Controller.initState();
Or use inversion of controll, dependency injection, #Inject. That would allow unit tests too. There certainly are open source DI containers out there in the web (Spring, or is Pico container still around?). Or requesting beans from some DI container.
If both are too early, go for lazy evaluation (partly the initialisation of statics is already lazy). Sometimes one will see an inner class:
private static class Singleton {
private static final State state = Controller.initState();
}
Possibly with a getInstance.
My choice:
Somehow no statics, but getters to singletons. A bean frame work with controllers.
Singletons instead of statics.
Statics (static functions) where abundantly used in the prior eclipse 3 rich client, like
IPreferenceStore store = IDEWorkbenchPlugin.getDefault().getPreferenceStore();
boolean autoPrint = store.getBoolean(AUTO_PRINT);
Now alternatively with dependency injection by the OSGi container and annotations:
#Inject #Preference(AUTO_PRINT)
boolean autoPrint;
From: Eclipse 4, Rich Clients by M. Teufel and J. Helming
Besides being shorter, there is less coupling between classes, and unit tests can more easily be written, as we can fill in autoPrint like we like, and do not need to meddle with the filling class.
If one hesitates adding the overhead of such a container, the easiest way is to have alternatives to several statics is having one global application context, where you can lookup java objects, POJO beans. Maybe backed by an XML file:
State state = ApplicationContext.lookup(State.class, "state");
<bean name="state" class="org.anic.State" value="sleepy" depends="firstThis"/>
<bean name="firstThis .../>
Mind, there no longer is a need to have a static state.
The Spring framework has such an XML approach.
The advantage being a centralized initialisation, where sequence and different factory / creation methods are thinkable.
(Sorry for the messy answer.)
Pass it in as the constructor of your abstract class
public abstract class AbstractCommand {
private static State state;
protected AbstractCommand(State state){
this.state = state;
}
public State getState(){
return state;
}
}
In your extending classes...
public class Command1 extends AbstractCommand{
public Command1(){
super([some state]);
}
}
The extending class can set the state once during initialization, but has read-only access thereafter.
So I see you want the behavior as mentioned by Magus as "So you want that subclasses of AbstractCommand can't set the state value, but an other class can do it ?"
Here is my suggestion:
Create an Interface with some rules. That you want to apply in all your subclasses
Now Let AbstractCommand implement that Interface and it should also contain state variable, by doing this you can maintain a set of rule at lower level
In second leg of Interface define in step 1 have your other class that you want not to have access to AbstractCommand class variable
By doing this you can maintain your package structure. Hope this helps.
Here is what I was trying:
Create Interface as:
public interface RuleInterface {
//Define rules here
void method1();
}
Now implement this in your AbstractCommand class
public abstract class AbstractCommand implements RuleInterface{
private static String state;
}
Have other class, this class can modify state varibale
public class SubClassAbstractCommand extends AbstractCommand{
#Override
public void method1() {
}
}
Create one more leg for Interface as:
public class AnotherLeg implements RuleInterface{
#Override
public void method1() {
}
}
Now AnotherLeg class can't access state variable but still you can enforce the rules via interface RuleInterface
public abstract class AbstractCommand {
private static State state;
static {
state = Controller.getState();
}
protected AbstractCommand(){
}
public State getState(){
return state;
}
}

why interface cannot be final?

JLS 2.13.1 Interface Modifiers
An interface cannot be final, because the implementation of such a class could never be completed.
If I can write create static inner classes in interface I can provide implementation in it so why is such restriction
interface Type {
// Normal
class Value {
private Value() {
}
public void print() {
System.out.println("Test");
}
}
public final Value value = new Value();
}
Well in Interfaces you cannot provide any form of implementation at all: Not even static methods. It doesn't make sense to make any method final because they're yet to be implemented.
Code Examples:
If let say I have an interface named IExample and its concrete implementation Example:
interface IExample{
public final void run();
}
class Example implements IExample{
// wait! I can't override because it's final! but it's yet to be implemented?!
public void run(){
}
}
BTW: nested classes were not available when this restriction was first defined, so really the question might be why this restriction was not lifted.
A final class cannot have any sub-classes. It is considered best practice to only use interfaces for defining method(s) of sub-classes, so the two are contradictory.
You can use interfaces for other things
annotations
javadocs
constants
defining nested classes only.
but these are incidental to the purpose of an interface.
"When the final keyword appears in a class declaration, it means that the class may never be subclassed or overridden. This prevents over-specialization of a particular class. In some sense, the person who created the class considered any further changes to be tangential to its primary purpose."
Reference: Final
Interface represent behaviour, rather than implementation, therefore it makes no sense for it to be final.
If I can write create static inner classes in interface I can provide implementation in it so why is such restriction
Yes, you can declare an inner class there, but point remains that a final interface would be an interface that it is impossible to implement. Any class that implemented it would be violating the final restriction. The Java designers concluded that this didn't make much sense, and since there are no convincing use-cases for final interfaces with nested classes*, there is no justification for relaxing this restriction.
* - I won't claim that one could not invent a use-case. However, I've never heard of people writing interfaces with inner classes, with the intention was that the interface should not be implemented.

Advice needed: static methods in JAVA interface

I have a class that is handling printing the various messages into the console, lets call this class ConsoleMessages.java. This class is public and abstract and all its methods are public and static.
I want to make an interface to this class (lets call it PrintMessages). I mean so, that ConsoleMessages.java will implement PrintMessages.
The thing is, JAVA doesn't support static methods in an interface.
What would you advise me to do?
Create the PrintMessages interface with the methods you desire.
Make ConsoleMessages a class that implements that interface. Change all methods from static to non static.
Enforce ConsoleMessages instantiation as a singleton. This can be achieved in many ways, either doing it yourself or using a Dependency Injection framework.
There is really no strong arguement against static methods in interface. Nothing bad would happen.
An interface can have static fields and static member classes though, therefore static methods can be attached through them, albeit with one extra indirection.
interface MyService
static public class Factory
static public MyService get(...)
return ...;
MyService service = MyService.Factory.get(args);
If you find yourself needing to define interfaces on a utility class then it may be time to revisit your design choices. Your ConsoleMessages class seems to have outgrown its initial use as a dumping ground for 'common utility functions'.
Short answer? Refactoring time.
Interfaces are there to specify methods for objects (which will then be implemented by some class). You have no objects here, thus you need no interface.
Static methods can only be called using the exact class name (or alternatively the name of some subclass), there is no point in using an interface to do this.
So, you have two options:
Throw your interface away and stay with the static methods.
Make all methods (or at least these which should be in the interface) non-static, and your implementing class non-abstract. To call them one then would need an object of the class (implementing this interface).

Categories