What is best practice to restrict instantiation of the classes to only one class? Something like this but in Java.
Let's say there is Main class, then there are User, Admin, View, Data, Client etc. classes. Only 'Main' class should be able to instantiate all other classes.
So if 'User' need to call 'getUser' method in 'Data' class, it can't instantiate 'Data' class and call method, but it has to call 'Main' class, and then 'Main' will instantiate 'Data' class and pass arguments to its 'getUser' method.
What I am thinking is using private constructor, Factory Pattern etc., but not sure if this will result in what I need. Due to the complexity I don't think inner classes would be good solution.
Any advice on this?
A distinct answer on the conceptual level (as there are already good answers on the technical "how to do it"):
Let's say there is Main class, then there are User, Admin, View, Data, Client etc. classes. Only 'Main' class should be able to instantiate all other classes.
I don't think this is a good starting point. Of course, when one follows Domain Driven Design, using factories is well established.
But there is one subtle point to add: you still want to cut your "boundaries" in reasonable ways. Meaning: don't force all objects into a single factory. Your objects should somehow resemble their domains, and be separated where needed.
Meaning: using factories is fine, but don't force yourself into the wrong corner by enforcing that there is exactly one factory that is supposed to handle all kinds of objects you deal with. Instead: try to reasonably partition your object model, and have as many factories as it makes conceptually sense to have.
Also note that you probably should distinguish between objects that mainly provide data/information, and "behavior" on the end. Thus it might be worth looking into the idea of having a service registry (for example what you do with the netflix Eureka framework, see here).
And finally, to quote an excellent comment given by tucuxi here: For small applications, factories are over-engineering. For larger applications, I find it questionable to have a single factory called "Main", instead of splitting responsibilities in a more orthodox way.
You can use a subclass with a private constructor:
With this, only InstantiatonClass can create InstantiatonClass.ArgClass and the constructor of ProtectedClass.
public class ProtectedClass{
//constructor that can only be invoked with an instance of ArgClass
public ProtectedClass(InstantiatonClass.ArgClass checkArg){}
}
public class InstantiatonClass{
public static class ArgClass{
//constructor that can only be invoked from InstantiatonClass
private ArgClass(){}
}
}
You should be able to get caller's class in a Class's constructor:
How to get the name of the calling class in Java?
Then in the classes where you only want to be instantiated by Main, simply check the caller class is Main in its constructor, if not throw a RuntimeException.
Related
I have seen the use of passing class types as parameters more and more. I am wondering what are the reasons why someone would design an application to use a class type over an interface or an object.
Simply why:
someFunction(someclass.class);
Over:
someFunction(new someclass());
where some class is a concrete object implementing someInterface.
I'll take an example from the comments: why SpringApplication.run(Application.class, args); instead of SpringApplication.run(this, args);?
I haven't actually used Spring so I'm not certain this is a correct description of how Spring invokes dependency injection, but it should serve to answer the question regardless.
To start with, this method is typically called from main. More to the point, from public static void main. That's a static method, and this doesn't exist in those. So it would have to be SpringApplication.run(new Application(), args); instead.
But what if the constructor of Application looks like public Application(Something dependency1, AnotherThing dependency2, SomethingElse dependency3)? You'd have to make each of those dependency objects first, and they might have their own dependencies too. You'd end up with this giant sequence of dozens of lines of creating new objects and passing them to the constructors of more new objects.
SpringApplication.run(Application.class, args); is a single short line no matter what the Application constructor looks like, and it is specifically designed to figure out and make all those dozens of required objects for you. It looks at Application's constructor and sees that list of three arguments, looks at those classes, finds their constructors, looks at those constructors' arguments lists, etc., until it has enough information to put the whole big mess together for you. All from one short method call. Requiring that you pass an already-made instance of Application rather than the class would negate the point of this, and the class is all it actually needs.
There are a great many other things that can be done with a class where using an instance instead would be unnecessary or even actually break the desired functionality, this is just one example of that.
As I develop my software, I tend to find myself creating a whole ton of ThingyHelper.java, FooHelper.java, BarHelper.java etc. I counted, and in the current project that I am working on, there are something like over 40 classes that look something like this:
public final class FoobarHelper {
// Prevent instantiation
private FoobarHelper() {throw new AssertionError();}
public static void doSomething() {}
public static int foobar() {}
// And many more
}
My question is this: Is it a good idea to merge all these classes into a huge Helper.java class? Looking around, there seems to be nothing written on this topic. My view is:
I should do it, because:
I don't have to remember which helper class is it in. (Was it FooHelper, or BarHelper?)
Just convenience. I don't have to decide if the new helper method deserves its own helper class, or if it fits into one of the existing 40 helper classes.
If I make a new helper method, and decided it deserves its own helper class, I will probably spend the rest of my day "hey, won't foobar() be better off in this new class?"
If #3 is true, other programmers would be like "where on earth did foobar() go? Its not in FoobarHelper!"
Is there a convention for helper classes, or if not, would it be a terrible idea?
I argue that your problem is not the fact that you have too many of those classes, it is that you need these classes altogether.
It is the core idea of object-orientation to merge functionality and data into objects which then represent your program flow. Without knowing your application, your utility classes suggest that you use inanimate bean classes which are then handled by a layer of service functions. This is a sign of procedural programming and nothing you want to implement with Java.
Besides that, there is no reason to merge your utility methods. So I would answer no to your question. There are some legitimate uses of utility classes such as Java's Math, Collections classes (those would also suite better as object methods but the language limits / limited this sort of definition) and you might just have encountered one of them. Note how Java decided to group such utility methods by their semantics. It makes sense to define utility methods in one name space such that your IDE can help you to pick a function when you only type the class (which does not represent a true class but rather a function namespace in this context). In the end, it is about finding a balance. If you have a single utility method per class, it is difficult for others to locate these methods as they need to know about the class's name. If there is only one utility class, it might be problematic to locate a function of all those offered. Think about the utility class as a form of navigation helper (name space) and decide after what you find intuitive.
If both classes are at same level (Both are child class), how to use instance of one class into another one.What is best way to use instance of one class into another class without passing into constructor? so manually require to pass null. How to make independent code?
Class PreviewPanel{
private PreviewPanel(Builder builder) {
this.previewMode=builder.previewMode;
formsPreview=new NTFormsPreview(previewMode);
formsPreview.setCanAddComment(builder.canAddComment);
ntPreviewTreePanel=new NTPreviewTreePanel(builder,formsPreview);
//This class have some event bus implemented.Sometime There, formsPreview instance is require.
}
public static class Builder {
private PreviewMode previewMode;
private Document document;
public Builder(PreviewMode previewMode,Document document) {
this.previewMode = previewMode;
this.document=document;
}
public PreviewPanel build() {
return new PreviewPanel(this);
}
}
}
If I pass that instance into constructor,I have to follow chain of inner class and pass same instance to reach specific class. I want to avoid it. This is big product. it is not easy to show how many classes inside it to reach actual handler implementation.
Code Structure:
private PreviewPanel(Builder builder)
->formsPreview=new NTFormsPreview(previewMode);
->NTPreviewTreePanel(builder,formsPreview);
->NTPreviewTree(document, bidDocuments, previewMode, canAddComment,canViewComment, previewFormTxnEncryptionDetails,formsPreview);
->NTTreeNode(formsPreview)
private void fireReportItemClicked(Document document,esenderCSReport){
eventBus.fireEventFromSource(formPreviewEvent, formsPreview);
}
is there any way to use instance of one class into another class without passing instance into constructor?
There are other ways.
Pass the instance of the second class to the first class using a setter method.
Pass the instance of the second class to the first class by assigning to a instance variable in the first class.
Create the instance of the second class in the first class.
If you an answer that is more relevant to your example, you will need to explain more clearly what you are trying to do here, and why you think that your current solution is unsatisfactory.
Re this attempted explanation:
I have to follow chain of inner class and pass same instance to reach specific class. I want to avoid it.
I have no idea what you are trying to say. I suspect that other readers has the same problem.
I suspect that the real problem here is with the design of your existing code. It looks like you / someone has gone a bit crazy with nesting classes, and that you are suffering the consequences. It could be that the only way to simplify things is to unpick the nesting or rethink the constructors. (Why does a private constructor require a "builder" argument?)
It is a fairly common phenomenon for complicated OO software to have inherently complicated initialization patterns. There tends to be no neat way to deal with this programatically, but you can often avoid this by using some kind of "Dependency Injection" (DI) mechanism. Another name for this is "Inversion of Control" (IoC).
For example, Spring DI works by adding annotations to your class, and getting Spring to create and assemble the instances in the required form. Or you can specify how the instances (beans) are assembled in XML.
This could be a solution for you ...
Your problem is unclear to me but I think you could do the following :
Create a new Class that will "Own both of your child class - composition"
Make it work a Mediator Pattern so that one can use and call stuff on the other one following the rule/logic you want.
No need to pass one of the child to the other one in any way.
Freely, redesign the interaction logic if it gets to change
No need to "change"" the structure you already have
FYI The builder, seems to be related to the Builder Pattern, you might wanna read on it and see if you can understand something out of your project.
I have always felt that in general the main work of a class should be done in its instance methods, while the constructor should only get the instance into a usable inital state.
But I find that in practice there are situations where it seems to make more sense to put essentially all the actual work into the constructor.
One example: I need to retrieve some DBMS-specific information from the database. The most natural way to me seemed to have a class DBMSSpecInfo, with a constructor:
public DBMSSpecInfo(java.sql.Connection conn) throws SQLException{
// ... retrieve info from DBMS
}
/** #returns max size of table in kiB */
public int getMaxTableSize() {//...}
/** #returns max size of index in kiB */
public int getMaxIndexSize() {//...}
/** #returns name of default schema */
public String getDefaultSchema() {//...}
You would construct the class once, the constructor would fetch all data, then you could use various getters to retrieve the info you need.
Of course I could put the method somewhere else, and only use DBMSSpecInfo for the return value (essentially using DBMSSpecInfo only as a value holder), but it feels ugly to create a class just for returning values from a single function.
So what do you think? Are there problems with performing the main work in the constructor? Is it "un-idiomatic" in Java? Or is it an acceptable (though possibly uncommon) practice?
The main practical problem is unit-testing - you won't be able to instantiate the object without doing actual work. (Or you'd have to mock all the classes that participate in this work).
Related talk: OO Design for testability. It gives examples of why doing work in constructors is bad for unit-testing.
I would prefer separating the creation code from the class itself in such cases. It could be put into a static factory method, or a separate factory class (which can also be a public static inner class). The choice depends on the complexity of the code and the design context (which we don't know in this case).
This would also allow you to do optimizations, like caching and reusing the class instance(s).
I'm big on pragmatism. If it works, do it! But in the name of purity and goodness, I'd like to make a design suggestion:
This class muddles up the data content with the mechanism for retrieving it. The object you end up using elsewhere is interesting only for the data it contains. So the "clean" thing to do would be to have a different class for digging out the information and then creating instances of this properties object.
That other class could have a longer lifetime, as you'd typically be calling a method to do the work, not the constructor. The constructor of DBMSSpecInfo might end up assigning a bunch of properties but not doing a lot of error-capable DB access work.
In your example I would make a static method GetDBMSSpecInfo(java.sql.Connection conn) that will return an instance of DBMSSpecInfo object or null if something goes wrong (in case you don't want to throw exceptions).
The DBMSSpecInfo object for me should not contain nothing more than get properties: MaxIndexSize, MaxTableSize, DefaultSchema, etc.
And I would make the constructor of this object private so that instances can only be created from the static method.
I don't think it is a good idea to do the main work in a constructor, since it doesn't have a return value. So it makes error processing more complicated IMO, since it forces you to use exceptions.
A disadvantage of doing the work in the constructor is that constructors can not be overridden (nor should they delegate to overridable methods).
Another is that a constructor is all-or-nothing. If the object contains data whose initializations exhibit indepedent failures, you deprive yourself of the capability to use what data could be procured successfully. Similarly, that you have to initialize the entire object, even if you just need part of it, might adversely affect performance.
On the other hand, doing it in the constructor allows initialization state (here: the connection to the database) to be shared, and released earlier.
As always, different approaches are preferable in different circumstances.
Doing all the work in the constructor can lead to "overload hell". You keep wanting to add more features and instead of just adding a new method, like you would in normal Object-Oriented development, you find yourself adding more and more overloaded constructors. Eventually, the constructors can grow so many overloads and parameters that it becomes unwieldy.
Just be careful that the object is not cloned/deserialised. Instances created this way do not use the constructor.
In my opinion the constructor should be lightweighted and should not throw exceptions.
I'd implement some kind of Load() method to retreive data from the database, or implement lazy loading.
No problem. JDK has a lot of classes that does network IO in constructors.
I have never found good answers to these simple questions about helper/utility classes:
Why would I create a singleton (stateless) instead of using static methods?
Why would an object instance be needed if an object has no state?
Often, singletons are used to introduce some kind of global state to an application. (More often than really necessary, to be honest, but that's a topic for another time.)
However, there are a few corner cases where even a stateless singleton can be useful:
You expect to extend it with state in the foreseeable future.
You need an object instance for some particular technical reason. Example: Synchonization objects for the C# lock or the Java synchronized statement.
You need inheritance, i.e., you want to be able to easily replace your singleton with another one using the same interface but a different implementation.Example: The Toolkit.getDefaultToolkit() method in Java will return a singleton whose exact type is system dependent.
You want reference equality for a sentinel value.Example: DBNull.Value in C#.
I could see a case for a stateless singleton being used instead of a static methods class, namely for Dependency Injection.
If you have a helper class of utility functions that you're using directly, it creates a hidden dependency; you have no control over who can use it, or where. Injecting that same helper class via a stateless singleton instance lets you control where and how it's being used, and replace it / mock it / etc. when you need to.
Making it a singleton instance simply ensures that you're not allocating any more objects of the type than necessary (since you only ever need one).
Actually i've found another answer not mentionned here: static methods are harder to test.
It seems most test frameworks work great for mocking instance methods but many of them no not handle in a decent way the mock of static methods.
In most programming languages classes elude a lot of the type system. While a class, with its static methods and variables is an object, it very often cannot implement an interface or extend other classes. For that reason, it cannot be used in a polymorphic manner, since it cannot be the subtype of another type. For example, if you have an interface IFooable, that is required by several method signatures of other classes, the class object StaticFoo cannot be used in place of IFooable, whereas FooSingleton.getInstance() can (assuming, FooSingleton implements IFooable).
Please note, that, as I commented on Heinzi's answer, a singleton is a pattern to control instantiation. It replaces new Class() with Class.getInstance(), which gives the author of Class more control over instances, which he can use to prevent the creation of unneccessary instances. The singleton is just a very special case of the factory pattern and should be treated as such. Common use makes it rather the special case of global registries, which often ends up bad, because global registries should not be used just willy-nilly.
If you plan to provide global helper functions, then static methods will work just fine. The class will not act as class, but rather just as a namespace. I suggest, you preserve high cohesion, or you might end up with weirdest coupling issues.
greetz
back2dos
There is a trade-off between using which one. Singletons may or may not have state and they refer to objects. If they are not keeping state and only used for global access, then static is better as these methods will be faster. But if you want to utilize objects and OOP concepts (Inheritance polymorphism), then singleton is better.
Consider an example: java.lang.Runtime is a singleton class in java. This class allows different implementations for each JVM. The implementation is single per JVM. If this class would have been static, we cannot pass different implementations based on JVM.
I found this link really helpful: http://javarevisited.blogspot.com/2013/03/difference-between-singleton-pattern-vs-static-class-java.html?
Hope it helps!!
Singleton is not stateless, it holds the global state.
Some reasons which I can think of using Singleton are:
To avoid memory leaks
To provide the same state for all modules in an application e.g database connection
For me "Want Object State use Singleton, Want Function use static method"
It depends on what you want. Whenever you want the object state (e.g. Polymorphism like Null state instead of null, or default state), singleton is the appropriate choice for you whereas the static method use when you need function (Receive inputs then return an output).
I recommend for the singleton case, it should be always the same state after it is instantiated. It should neither be clonable, nor receive any value to set into (except static configuration from the file e.g. properties file in java).
P.S. The performance between these 2 are different in milliseconds, so focus on Architecture first.
According to GoF’s book Design Patterns, chapter ‘Singleton’, class operations have the following drawbacks compared to singletons (bold emphasis mine):
More flexible than class operations. Another way to package singleton’s functionality is to use class operations (that is, static member functions in C++ or class methods in Smalltalk). But both of these language techniques make it hard to change a design to allow more than one instance of a class. Moreover, static member functions in C++ are never virtual, so subclasses can’t override them polymorphically.