Quick Java Question: Instantiating a given class only from another? - java

My problem is thus: I need a way to ensure only one given class can instantiate another. I don't want to have to make the other a nested inner class or something dumb like that. How do I do this? I forget offhand.

A private static inner class is exactly what you want. Nothing dumb about it.
public class Creator {
private static class Created {
}
}
Otherwise you can only protect instantiation on the package level.
public class Created {
Created() {
}
}
Which gives only classes from the same package access to the constructor.

Make the constructor private. Create a static factory method that takes an instance of the class that is allowed access. Have the factory method create a suitable object and use a settor on the object that is allowed access to the created object to give that class the created copy.
public class AllowedAccess
{
private SecureClass secure;
public setSecureClass( SecureClass secure )
{
this.secure = secure;
}
...
}
public class SecureClass
{
private SecureClass() {}
public static void Create( AllowedAccess allowed )
{
allowed.setSecureClass( new SecureClass() );
}
...
}
BTW, I'm suspicious of this design. Seems too highly coupled to me.

You could make the class that is to be protected from instantiation package private.

I agree with tvanfosson's answer and also with his comment about too high coupling. Why don't you retain more control of you class creation process by adopting an Inversion of Control framework like Spring or Guice?
IMHO creating classes with the "new" statement is to be considered a bit... obsolete, factories are to be preferred and IoC frameworks even more.
Regards

Related

Java Application return super class when initialized

Nowadays we are on writing some core application that is all other application will be relying on. Without further due let me explain the logic with some codes,
We used to have a single java file that was 1000+ lines long and each application was having it as class inside, so when there was a change, each application had to edit the java file inside of it or simply fix one and copy to all. This is hard to implement as much as it is hard to maintain. Then we end-up with creating this as a separate application that is divided to smaller part, which is easy to maintain and also a core maybe a dependency to other application so we fix in one place and all other code applications are fixed too.
I've been thinking for a some great structure for this for a while want to use a builder patter for this as below
TheCore theCore = new TheCore().Builder()
.setSomething("params")
.setSomethingElse(true)
.build();
The problem arises now. Like so, I initialized the object but now I'm having access to that objects public class only. This application actually will have many small classes that has public functions that I don't want them to be static methods that can be called everytime. Instead I want those methods to be called only if TheCore class is initilized like;
// doSomething() will be from another class
theCore.doSomething()
There are some ideas I produced like
someOtherClass.doSomething(theCore)
which is injecting the main object as a parameter but still someOtherClass needs to be initialized or even a static method which doesn't make me feel comfortable and right way to that.
Actually I do not care if initializing TheCore would bring me a super object that includes all other classes inside initialized and ready to be accessed after I initialized TheCore. All I want in this structure to have a maintainable separate app and methods avaiable if only the main object which is TheCore is this circumstances is initialized.
What is to right way to achive it? I see that Java does not allow extending multiple classes even it if does, I'm not sure it that is right way...
Thanks.
After spending significant amount of time of thought I ended up that
// doSomething() will be from another class
theCore.doSomething()
is not suitable since many java classes could possibly have identical method names. So...
// doSomething() will be from another class
theCore.someOtherClass.doSomething()
would be a better approach.
To make it easier to understand I'll have to follow a complex path to explain it which is starting from the package classes first.
Think that I have a package named Tools and a class inside SomeFancyTool
main
└─java
└─com
└─<domainName>
├─Tools
| └─SomeFancyTool.java
└─TheCore.java
Now this SomeFancyTool.java must have a default access level which is actually package level access, because I don't want this classes to be accessed directly;
SomeFancyTool.java
package com.<domainName>.Tools
class SomeFancyTool{
public String someStringMethod(){
return "Some string!";
}
public int someIntMethod(){
return 123;
}
public boolean someBooleanMethod(){
return true;
}
}
So now we have the SomeFancyTool.java class but TheCore.java cannot access it since it is accesible through its Tools package only. At this point I think of an Initializer class that is gonna be in the same package, initialize these private classes and return them with a function when called. So initiliazer class would look like this;
ToolsInitializer.java
package com.<domainName>.Tools
public class ToolsInitializer{
private SomeFancyTool someFancyTool = new SomeFancyTool();
public SomeFancyTool getSomeFancyTool(){
return someFancyTool;
}
}
Since ToolsInitializer.java can initialize all functional private classes inside in Tools package and also can return them as objects to outside of the package scope, still we are not able to use these methods as we cannot import com.<domainName>.SomeFancyTool from TheCore.java because it is package wide accessible. I think here we can benefit from implementation of the java interface. A class that is not functional alone, so no problem even if it is accessed since it's methods will be nothing but declarations.
At this point I'll rename SomeFancyTool.java to SomeFancyToolImplementation.java which it will be implementing the interface and call SomeFancyTool.java to the interface itself.
SomeFancyTool.java (now as an interface)
package com.<domainName>.Tools
public interface SomeFancyTool{
public String someStringMethod();
public int someIntMethod();
public boolean someBooleanMethod();
}
and lets rename prior SomeFancyTool.java and implement the interface
SomeFancyToolImplementation.java (renamed)
package com.<domainName>.Tools
class SomeFancyToolImplementation implements SomeFancyTool{
#override
public String someStringMethod(){
return "Some string!";
}
#override
public int someIntMethod(){
return 123;
}
#override
public boolean someBooleanMethod(){
return true;
}
}
Now our structure has become like this with the final edits;
main
└─java
└─com
└─<domainName>
├─Tools
| ├─SomeFancyTool.java
| ├─SomeFancyToolImplementation.java
| └─ToolsInitializer.java
└─TheCore.java
Finally we can use our TheCore.java class to call all initializer classes with their methods to receive all these private classes inside as an object. This will allow external apps to call and initialize TheCore first to be able to access other methods.
TheCore.java
public class TheCore{
private SomeFancyToolImplementation someFancyTool;
public static class Builder{
private SomeFancyToolImplementation someFancyTool;
public Builder(){
ToolsInitializer toolsInitializer = new ToolsInitializer();
someFancyTool = toolsInitializer.getSomeFancyTool();
}
public Builder setSomeValues(){
//some values that is needed.
return this;
}
public Builder setSomeMoreValues(){
//some values that is needed.
return this;
}
public TheCore build(){
TheCore theCore = new TheCore();
theCore.someFancyTool = someFancyTool;
return theCore;
}
}
}
All Done and it is ready to use. Now the functional package classes and its methods that it relying on if TheCore is initialized or not, cannot be accessed with out TheCore. And simple usage of this Library from a 3rd Party app would simply be;
3rd Party App
TheCore theCore = new TheCore.Builder()
.setSomeValues("Some Values")
.setMoreSomeValues("Some More Values")
.build();
theCore.someFancyTool.someStringMethod();
Note: Note that a the ToolsInitializer.java is still accessible and could be used the get private method without first calling TheCore but we can always set a checker inside getSomeFancyTool() method to throw error if some prerequisites are not satisfied.
I do not still know if this is a functional structural pattern to use or its just some hard thoughts of mine. And don't know if some pattern is already exist that I just could not see yet but this is the solution I end up with.

What is a good way of telling low level objects which factories to use?

I've been learning a lot about Design Patterns lately, specifically Dependency Injection. I'm pretty sure that abstract factorys are a good way of instantiating objects that have dependencies. However I'm not sure how to tell lower level objects what factories they are supposed to use.
Consider following simplified example:
I have a class MainProgram (I just made this to represent that there is other code in my program..)
At some point during runtime I want to instantiate a IGeneticAlgorithm with an abstract factory:
public class MainProgram{
private AbstractGeneticAlgorithm geneticAlgorithm;
private IGeneticAlgorithmFactory geneticAlgorithmFactory;
public MainProgram(IGeneticAlgorithmFactory geneticAlgorithmFactory){
this.geneticAlgorithmFactory = geneticAlgorithmFactory;
}
private void makeGeneticAlgorithm(){
geneticAlgorithm = geneticAlgorithmFactory.getInstance();
}
public static void main(String[] args){
MainProgram mainProgramm = new MainProgram(new FastGeneticAlgorithmFactory());
//...
}
}
public interface IGeneticAlgorithmFactory{
public IGeneticAlgorithm getInstance();
}
public class FastGeneticAlgorithmFactory implements IGeneticAlgorithmFactory{
public IGeneticAlgorithm getInstance(){
return new FastGeneticAlgorithm();
}
}
public abstract class AbstractGeneticAlgorithm{
private IIndividual individual;
private IIndividualFactory individualFactory;
private void makeIndividual(){
individual = individualFactory.getInstance();
}
//...
}
At some point during runtime I want to instantiate an IIndividual in my GeneticAlgorithm. The IIndividual can't be instantiated at startup. The need to be able to instantiate the IIndividual during runtime comes from the way Genetic Algorithms work, where basically after each Step of Selection-Recombination-Mutation new Individuals have to be instantiated. (For more information see https://en.wikipedia.org/wiki/Genetic_algorithm). I chose to give the AbstractGeneticAlgorithm here only one IIndividual to keep this example simple.
public class FastGeneticAlgorithm implements AbstractGeneticAlgorithm{
private IIndividual individual;
private IIndividualFactory individualFactory;
}
public interface IIndividualFactory{
public IIndividual getInstance();
}
public class SmallIndividualFactory implements IIndividualFactory{
public IIndividual getInstance(){
return new SmallIndividual();
}
//...
}
public interface IIndividual{
//...
}
public class SmallIndividual implements IIndividual{
//...
}
Making the SmallIndividualFactory a static variable in the FastGeneticAlgorithm doesn't seem to me like good practice. And passing the SmallIndividualFactory to Main, so that Main can pass it down to FastGeneticAlgorithm also doesn't seem right.
My question is how to solve this? Thank you.
When it comes to using Dependency Injection, the Abstract Factory pattern is often over-used. This doesn't mean that it's a bad pattern per se, but in many cases there are more suitable alternatives for the Abstract Factory pattern. This is described in detail in Dependency Injection Principles, Practices, and Patterns (paragraph 6.2) where is described that:
Abstract Factories should not be used to create short-lived, stateful dependencies, since a consumer of a dependency should be oblivious to its lifetime; from perspective of the consumer, there should conceptually be only one instance of a service.
Abstract Factories are often Dependency Inversion Principle (DIP) violations, because their design often doesn't suit the consumer, while the DIP states: "the abstracts are owned by the upper/policy layers", meaning that consumer of the abstraction should dictate its shape and define the abstraction in a way that suits its needs the most. Letting the consumer depend on both a factory dependency and the dependency it produces complicates the consumer.
This means that:
Abstract Factories with a parameterless create method should be prevented, because it implies the dependency is short-lived and its lifetime is controlled by the consumer. Instead, Abstract Factories should be created for dependencies that conceptually require runtime data (provided by the consumer) to be created.
But even in case a factory method contains parameters, care must be taken to make sure that the Abstract Factory is really required. The Proxy pattern is often (but not always) better suited, because it allows the consumer to have a single dependency, instead of depending on both the factory and its product.
Dependency Injection promotes composition of classes in the start-up path of the application, a concept the book refers to as the Composition Root. The Composition Root is a location close to that application's entry point (your Main method) and it knows about every other module in the system.
Because the Composition Root takes a dependency on all other modules in the system, it typically makes little sense consume Abstract Factories within the Composition Root. For instance, in case you defined an IXFactory abstraction to produce IX dependencies, but the Composition Root is the sole consumer of the IXFactory abstraction, you are decoupling something that doesn't require decoupling: The Composition Root intrinsically knows about every other part of the system any way.
This seems to be the case with your IGeneticAlgorithmFactory abstraction. Its sole consumer seems to be your Composition Root. If this is true, this abstraction and its implementation can simply be removed and the code within its getInstance method can simply be moved into the MainProgram class (which functions as your Composition Root).
It's hard for me to understand whether or not your IIndividual implementations require a factory (it has been at least 14 years ago since I implemented a genetic algorithm at the University), but they seem more like runtime data rather than 'real' dependencies. So a factory might make sense here, although do verify whether their creation and implementation must be hidden behind an abstraction. I could imagine the application to be sufficiently loosely coupled when the FastGeneticAlgorithm creates SmallIndividual instances directly. This, however, is just a wild guess.
On top of that, best practice is to apply Constructor Injection. This prevents Temporal Coupling. Furthermore, refrain specifying the implementations dependencies in the defined abstractions, as your AbstractGeneticAlgorithm does. This makes the abstraction a Leaky Abstraction (which is a DIP violation). Instead, declare the dependencies by declaring them as constructor arguments on the implementation (FastGeneticAlgorithm in your case).
But even with the existence of the IIndividualFactory, your code can be simplified by following best practices as follows:
// Use interfaces rather than base classes. Prefer Composition over Inheritance.
public interface IGeneticAlgorithm { ... }
public interface IIndividual { ... }
public interface IIndividualFactory {
public IIndividual getInstance();
}
// Implementations
public class FastGeneticAlgorithm implements IGeneticAlgorithm {
private IIndividualFactory individualFactory;
// Use constructor injection to declare the implementation's dependencies
public FastGeneticAlgorithm(IIndividualFactory individualFactory) {
this.individualFactory = individualFactory;
}
}
public class SmallIndividual implements IIndividual { }
public class SmallIndividualFactory implements IIndividualFactory {
public IIndividual getInstance() {
return new SmallIndividual();
}
}
public static class Program {
public static void main(String[] args){
AbstractGeneticAlgorithm algoritm = CreateAlgorithm();
algoritm.makeIndividual();
}
private AbstractGeneticAlgorithm CreateAlgorithm() {
// Build complete object graph inside the Composition Root
return new FastGeneticAlgorithm(new SmallIndividualFactory());
}
}

Java polymorphism through injection at runtime

I hear that in Java I can achieve polymorphism through injection at runtime. Can someone please show a simple example of how that is done? I search online but I can't find anything: maybe I am searching wrong. So I know about polymorphism through interface and and extension such as
class MyClass extends Parent implements Naming
in such case I am achieving polymorphism twice: MyClass is at once of type Parent and Naming. But I don't get how injection works. The idea is that I would not be using the #Override keyword during injection. I hope the question is clear. Thanks.
So the end result here, per my understanding, is to change the behavior of a method through injection instead of by #Override it during development.
So I know about polymorphism through interface and and extension such as
class MyClass extends Parent implements Naming
This is known as inhertiance and not polymorphism. MyClassis a Parent and MyClass is also a Naming. That being said, inheritance allows you to achive polymorphism.
Consider a class other thanMyClass that also implements Naming :
class SomeOtherClass implements Naming {
#Override
public void someMethodDefinedInTheInterface() {
}
}
Now consider a method that takes a Naming argument somewhere in your code base :
public void doSomething(Naming naming) {
naming.someMethodDefinedInTheInterface();
}
The doSomething method can be passed an instance of any class that implements Naming. So both the following calls are valid :
doSomething(new MyClass());//1
doSomething(new SomeOtherClass());//2
Observe how you can call doSomething with different parameters. At runtime, the first call will call someMethodDefinedInTheInterface from MyClass and the second call will call someMethodDefinedInTheInterface from SomeOtherClass. This is known as runtime-polymorphism which can be achieved through inheritance.
But I don't get how injection works. The idea is that I would not be using the #Override keyword during injection
That's true in the broader sense. To inject something into a class, the class should ideally favor composition over inheritance. See this answer that does a good job in explaining the reason for favoring composition over inheritance.
To extend the above example from my answer, let's modify the doSomething method as follows :
public class ClassHasANaming {
private Naming naming;
public ClassHasANaming(Naming naming) {
this.naming = naming;
}
public void doSomething() {
naming.someMethodDefinedInTheInterface();
}
}
Observe how ClassHasANaming now has-a Naming dependency that can be injected from the outside world :
ClassHasANaming callMyClass = new ClassHasANaming(new MyClass());
callMyClass.doSomething();
If you use the Factory pattern, you can actually chose which subclass gets instantiated at runtime.
Do you think we could have done what we did above using inheritance?
public class ClassIsANaming implements Naming {
public void doSomething() {
someMethodDefinedInTheInterface();
}
#Override
public void someMethodDefinedInTheInterface() {
//....
}
}
The answer is No. ClassIsANaming is bound to a single implementation of the someMethodDefinedInTheInterface method at compile time itself.
`
Taking a contrived example. You have a class Store that stores things:
class Store {
private List l
void store(Object o) {
l.add(o);
}
void setStoreProvider(List l) {
this.l = l
}
}
You can inject the actual List used as the backing storage using setStoreProvider which could be a linked list, array backed list, whatever.
Hence, depending on the injected type your Store class would have the features of the injected type (with regards to memory usage, speed, etc).
This is a kind of polymorphism without the class implementing an interface.

Doing an API, constructor for system private use only and another official, javadoc'ed and public to use. Advise on fix / pattern approach

I guess this is a bad pattern, whats the best approach to fix it?
I mean I would like everybody using a constructor with 2 arguments,but I need to leave default constructor because its implementing a listener which classloads it without args. I would like to hide default constructor to anyone else but the listener handler which uses it, and make the other the unique point to instantiate.
Is there any kind of annotation? any privacy modifier for certain classes (system caller one is not in the same package)?
This seems fine to me. You would do the same thing if you want to instantiate a class differently during unit testing.
Oh, I see you need a constructor that has more access than protected but less than public. Unfortunately that's not possible.
You could put both your class MyClass and the listener MyListener that needs to use the empty constructor in the same package. Then, set the access of the empty constructor to package-level:
package com.stackoverflow.foo;
public class MyClass {
MyClass () { // package-private (no explicit access modifier)
}
public MyClass(int a, int b) { // public
}
}
package com.stackoverflow.foo;
public class MyListener {
private MyClass ref = new MyClass(); // MyListener is on the same package as MyClass, so this is valid
}
This way, you ensure that only classes that are on the same package as MyClass can use the default constructor.

Design decisions: Why and when to make an interface private?

Are private interfaces ever used in design decisions ? If so, what are the reasons and when do you know the need for a private interface?
A top-level interface cannot be private. It can only have public or package access. From the Java Language Specification, section 9.1.1: "Interface Modifiers":
The access modifiers protected and private pertain only to member interfaces whose declarations are directly enclosed by a class declaration (§8.5.1).
A nested interface can be private whenever it and its subclasses, if any, are an implementation detail of its top-level class.
For example, the nested interface CLibrary below is used as an implementation detail of the top-level class. It's used purely to define an API for JNA, communicated by the interface's Class.
public class ProcessController {
private interface CLibrary extends Library {
CLibrary INSTANCE = (CLibrary) Native.loadLibrary( "c", CLibrary.class );
int getpid();
}
public static int getPid() {
return CLibrary.INSTANCE.getpid();
}
}
As another example, this private interface defines an API used by private nested classes implementing custom formatting symbols.
public class FooFormatter {
private interface IFormatPart {
/** Formats a part of Foo, or text.
* #param foo Non-null foo object, which may be used as input.
*/
void write( Foo foo ) throws IOException;
}
private class FormatSymbol implements IFormatPart { ... }
private class FormatText implements IFormatPart { ... }
...
}
IMHO You cannot usefully make an interface private.
However I often have two interfaces, one for public use and one for internal use. The internal use interface I make package local if possible e.g.
public interface MyInterface {
public void publicMethod();
}
interface DirectMyInterface extends MyInterface {
public void internalUseOnlyMethod();
}
The internal use methods expose methods I don't want other developers to use and/or I want to be able to change easily. The reason I have the interface at all is that I have several implementations which I want to use internally via an interface.
It has to be package protected if the interface if for internal use.
In general if the interface hasn't any interest outside it's ambit it's a good api design decision to hide it because there's less complexity for the users of the interface and also allows you to refactor it more easily, because when the interface is public and in the API you loss the liberty to change it.
A private interface method is a method that is only accessible within the class or object in which it is defined.
This allows for better organization and maintainability of code, as well as increased security by preventing external access to sensitive data or functionality.

Categories

Resources