I am working in Java on a fairly large project. My question is about how to best structure the set of Properties for my application.
Approach 1: Have some static Properties object that's accessible by every class. (Disadvantages: then, some classes lose their generality should they be taken out of the context of the application; they also require explicit calls to some static object that is located in a different class and may in the future disappear; it just doesn't feel right, am I wrong?)
Approach 2: Have the Properties be instantiated by the main class and handed down to the other application classes. (Disadvantages: you end up passing a pointer to the Properties object to almost every class and it seems to become very redundant and cumbersome; I don't like it.)
Any suggestions?
I like using Spring dependency injection for many of the properties. You can treat your application like building blocks and inject the properties directly into the component that needs them. This preserves (encourages) encapsulation. Then, you assemble your components together and create the "main class".
A nice side effect of the dependency injection is that your code should be more easily testable.
Actually, approach 2 works really well.
I tried using a Singleton properties object on a recent project. Then, when it came time to add features, I need to revise the Singleton, and regretted having to locate every place where I used MySingleton.getInstance().
Approach 2 of passing a global information object through your various constructors is easier to control.
Using an explicit setter helps, too.
class MyConfig extends Properties {...}
class SomeClass {
MyConfig theConfig;
public void setConfi( MyConfig c ) {
theConfig= c;
}
...
}
It works well, and you'll be happy that you tightly controlled precisely which classes actually need configuration information.
If the properties are needed by a lot of classes, I would go for approach 1. Or perhaps a variant in which you use the Singleton design pattern instead of all static methods. This means that you don't have to keep passing some properties object around. On the other hand, if only a few classes need these properties, you might choose approach 2, for the reasons you mentioned. You might also want to ask yourself how likely it is that the classes you write are actually going to be reused and if so, how much of a problem it is to also reuse the properties object. If reuse is not likely, don't bother with it now and choose the solution that is the simplest for the current situation.
Sounds like you need a configuration manager component. It would be found via some sort of service locator, which could be as simple as ConfigurationManagerClass.instance(). This would encapsulate all that fun. Or you could use a dependency injection framework like Spring.
Much depends on how components find each other in your architecture. If your other components are being passed around as references, do that. Just be consistent.
If you are looking for something quick you can use the System properties, they are available to all classes. You can store a String value or if you need to store a list of 'stuff' you can use the System.Properties() method. This returns a 'Properties' object which is a HashTable. You can then store what ever you want into the table. It's not pretty but it's a quick way to have global properties. YMMV
I usually go for a singleton object that resides in a common project and contains a hashtable of itself keyed on namespace, resulting in a properties class for each.
Dependency injection is also a nice way of doing it.
I feel more comfortable when I have a static pointer to my in-memory properties. some times you want to reload properties in runtime, or other functionality that is easier to implement with a static reference.
just remember that no class is an island. a reusable class can have a client class to keep the core free of the singletone reference.
you can also use interfaces, just try not to overdo it.
Approache 2 is defenetly better.
Anyway, you should not let other class search through config object. You should injet config taken in the config object ouside the object.
Take a look at apache commons configuration for help with configuration Impl.
So in the main() you could have
MyObject mobj = new MyObject();
mobj.setLookupDelay(appConfig.getMyObjectLookupDelay);
mobj.setTrackerName(appConfig.getMyObjectTrackerName);
Instead of
MyObject mobj = new MyObject();
mobj.setConfig(appConfig);
where appConfig is a wrapper around the apache configuration library that do all the lookup of the value base on the name of the value in a config file.
this way your object become very easily testable.
Haven't done Java for a while, but can't you just put your properties into the java.lang.System properties? This way you can access the values from everywhere and avoid having a "global" property class.
Related
Question/Problem
Given a plain Java class coming from a non-EMF-aware API such as
public class BankAccount {
String ownerName;
int accountNumber;
// ...
}
and also let's assume that I am not allowed to change or recompile this class (because it is from an API).
Is there any simple way to use this class as an ESuperType for an EClass in EMF? (And, of course, the single class is just an example. I'd need to wrap an API consisting of 30-50 classes ...).
Own thoughts
Personally, I think it is not possible out of the box.
I could only think of two ways, both with quite some effort and not easy to realize.
Create an Ecore model which reflects the original class (EBankAccount, having ownerName and accountNumber as EAttributes) and a utility method/mechanism that wraps the original object by copying its fields into the corresponding EStructuralFeatures and adds EAdapters which are responsible to synchonize both objects.
Hook into EMF.CodeGen and do some magic there which makes it possible to have the original class as super class in the generated code which at the same time still fulfilling the EMF contract (= implement the EObject interface etc.).
But maybe there's some hidden feature of EMF (or an existing extension) which does something along these lines, and I am not aware of it?
It's not clear to me what you real want, but I will try to describe the several options.
If you want just to extend the POJO (which is what the question text suggests), the answer is YES, you can simply add a new EClass to your model and refer to the POJO qualified name in the "Instance Type Name" attribute. Then you can create other classes that extend from this one, but its state won't be managed by EMF.
But if you want EMF to track that POJO state as if it was a real EMF object (so those properties are also EStructuralFeature), then I don't see another solution, you really need to model it completely in EMF.
In this second case, both options you described seem possible.
The first option you described (and I assume you mean you want to synchronize the 2 objects, and not the 2 classes) seems the easiest one, and I don't think it would take so much effort if you use some generic method via reflection.
This might be a good solution if you get the objects in very concrete locations, so you only need to wrap and unwrap in specific places. Otherwise you will need to convert be converting (wraping/unwrapping) the object all the time.
It may be also possible but it requires more effort for sure, since it's not easy to extend the Java JET templates
I'm not aware of any extension for this.
Maybe i missed it in the documentation but i'm wondering how i should handle "helper Objects"?
code example:
public Path dijkstra(Node startNode, Node endNode) {
Set<Node> nodesToInspect = new HashSet<Node>(); // should this Object be injected?
Path path = new Path(); // and this one?
while (!nodesToInspect.isEmpty()) {
// some logic like:
path.add(currentNode);
}
return path;
}
Should i inject everything or should i say at some point that the algorithm "knows" best what it needs?
Should i try to eliminate every "new"? or are some object creations fine, for example API classes like HashSet, ArrayList, etc.
Before you replace a simple new with dependency injection, you need to ask yourself "why am I doing this?" ... "what real benefit does it have?". If the answer is "I don't know" or "nothing", then you shouldn't.
In this case, I can see no real benefit in using DI in the first cases in your example code. There is no need for anything outside of that method to know about how the internal set is represented ... or even to know that it exists.
The other question you should ask is whether there is a simpler, more obvious way of achieving the goal. For example, the (most likely) purpose of using DI for the path variable is to allow the application to use a different Path class. But the simple way to do that is to pass a Path instance to the dijkstra method as an explicit parameter. You could even use overloading to make this more palatable; e.g.
public Path dijkstra(Node startNode, Node endNode) {
return dijkstra(startNode, endNode, new Path());
}
public Path dijkstra(Node startNode, Node endNode, Path path) {
...
}
The final thing to consider is that DI (in Java) involves reflection at some level, and is inevitably more expensive than the classical approaches of using new or factory objects / methods. If you don't need the extra flexibility of DI, you shouldn't pay for it.
I just noticed that the two variables you are referring to are local variables. I'm not aware of any DI framework that allows you to inject local variables ...
Remember the design principle: "Encapsulate what changes often" or "encapsulate what varies". As the engineer, you know best what is likely to change. You wouldn't want to hard-code the year 2012 into code that will live until next decade, but you also wouldn't want to make "Math.PI" a configuration setting either--that'd be extra overhead and configuration that you'd never need to touch.
That principle doesn't change with dependency injection.
Are you writing one algorithm and you know which implementation of Set you need, like in your Dijkstra example? Create your object yourself. But what if your co-worker is soon to deliver a fantastic new implementation of Set optimized for your use-case, or what if you are experimenting with different collection implementations for benchmarking? Maybe you'll want to inject a Provider until the dust settles. That's less likely for collections, but maybe it's more likely for similar disposable objects you might think of as "helper objects".
Suppose you're choosing between different types of CreditCardAuthService that may vary at runtime. Great case for injection. But what if you've signed a five-year contract and you know your code is going to be replaced long before then? Maybe hard-coding to one service makes more sense. But then you have to write some unit tests or integration tests and you really don't want to use a real credit card backend. Back to dependency injection.
Remember: code is malleable. Someday you may decide that you need to rip out your hard-coded HashSet and replace it with something else, which is fine. Or maybe you'll discover that you need your service to vary often enough that it should be Guice-controlled, and then you add a constructor parameter and a binding and call it a day. Don't worry about it too much. Just keep in mind that just because you have a hammer, not every problem is a Provider<WoodFasteningService>.
When working with DI, I prefer to avoid "new" whenever possible. Every instance you create outside the container (e.g. the guice injector) can not refactored to use injection (what if your "Path" instance should get a String "root" injected by configuration ... and you cannot use interceptors on those objects either.
So unless it is a pure Entity-Pojo, I use Provides/Inject all the time.
It's also part of the inversion of control (hollywood) pattern and testability ... what if you need to mock Path or Set in Junit? if you have them injected (in this case the Providers), you can easily switch concrete implementation afterwards.
I'm developing plugins in Eclipse which mandates the use of singleton pattern for the Plugin class in order to access the runtime plugin. The class holds references to objects such as Configuration and Resources.
In Eclipse 3.0 plug-in runtime objects
are not globally managed and so are
not generically accessible. Rather,
each plug-in is free to declare API
which exposes the plug-in runtime
object (e.g., MyPlugin.getInstance()
In order for the other components of my system to access these objects, I have to do the following:
MyPlugin.getInstance().getConfig().getValue(MyPlugin.CONFIGKEY_SOMEPARAMETER);
, which is overly verbose IMO.
Since MyPlugin provides global access, wouldn't it be easier for me to just provide global access to the objects it manages as well?
MyConfig.getValue(MyPlugin.CONFIGKEY_SOMEPARAMETER);
Any thoughts?
(I'm actually asking because I was reading about the whole "Global variable access and singletons are evil" debates)
Any thoughts?
Yes, for the current use-case you are examining, you could marginally simplify your example code by using statics.
But think of the potential disadvantages of using statics:
What if in a future version of Eclipse Plugin objects are globally managed?
What if you want to reuse your configuration classes in a related Plugin?
What if you want to use a mock version of your configuration class for unit testing?
Also, you can make the code less verbose by refactoring; e.g.
... = MyPlugin.getInstance().getConfig().getValue(MyPlugin.CONFIGKEY_P1);
... = MyPlugin.getInstance().getConfig().getValue(MyPlugin.CONFIGKEY_P2);
becomes
MyConfig config = MyPlugin.getInstance().getConfig();
... = config.getValue(MyPlugin.CONFIGKEY_P1);
... = config.getValue(MyPlugin.CONFIGKEY_P2);
You suggest that
MyPlugin.getInstance().getConfig().getValue(MyPlugin.CONFIGKEY_SOMEPARAMETER);
is too verbose and
MyConfig.getValue(MyPlugin.CONFIGKEY_SOMEPARAMETER);
might be better. By that logic, wouldn't:
getMyConfigValue(MyPlugin.CONFIGKEY_SOMEPARAMETER):
be better yet (Maybe not shorter, but simpler)? I'm suggesting you write a local helper method.
This gives you the advantage of readability without bypassing concepts that were crafted by people who have been through the effort of fixing code that was done the easy/short/simple way.
Generally globals are pretty nasty in any situation. Singletons are also an iffy concept, but they beat the hell out of public statics in a class.
Consider how you will mock out such a class. Mocking out public statics is amazingly annoying. Mocking out singletons is hard (You have to override your getter in every method that uses it). Dependency Injection is the next level, but it can be a touch call between DI and a few simple singletons.
I have an application that has several classes used for storing application-wide settings (locations of resources, user settings, and such). Right now these classes are just full of static fields and methods, but I never instantiate them.
Someone suggested I make them Singletons, What's the case for/against?
I consider the Singleton pattern to be the most inappropriately applied design pattern. In ~12 years of software development I'd say I've maybe seen 5 examples that were appropriate.
I worked on a project where we had a system monitoring service that modeled our system with a System class (not to be confused with Java's built-in System class) that contained a list of Subsystems each with a list of Components and so on. The designer made System a Singleton. I asked "Why is this a Singleton?" Answer: "Well, there is only one system." "I know, but, why did you make it a Singleton? Couldn't you just instantiate one instance of a normal class and pass it to the classes that need it?" "It was easier to just call getInstance() everywhere instead of passing it around." "Oh..."
This example is typical: Singletons are often misused as a convenient way to access a single instance of a class, rather than to enforce a unique instance for technical reasons. But this comes at a cost. When a class depends on getInstance(), it is forever bound to the Singleton implementation. This makes it less testable, reusable, and configurable. It violates a basic rule I follow and that probably has a common name in some design principles essay somewhere: classes should not know how to instantiate their dependencies. Why? Because it hardcodes classes together. When a class calls a constructor, it is bound to an implementation. getInstance() is no different. The better alternative is to pass an interface into the class, and something else can do the constructor/getInstance()/factory call. This is where dependency injection frameworks like Spring come in, though they are not necessary (just really nice to have).
So when is it appropriate to use a Singleton? In that rare case where instantiating more than one of something would literally ruin the application. I'm not talking about instantiating two Earths in a solar system app - that's just a bug. I mean where there is some underlying hardware or software resource that will blow up your app if you call/allocate/instantiate it more than once. Even in this case, classes that use the Singleton should not know it is a Singleton. There should be one and only one call to getInstance() that returns an interface that is then passed to constructors/setters of classes that need it. I guess another way of saying it is that you should use a Singleton for its "singleness" and not for its "globally accessibleness".
By the way, on that project I mentioned where System was a Singleton... Well System.getInstance() was laced throughout the code base, along with several other inappropriate Singletons. A year later some new requirements came down: "We are deploying our system to multiple sites and want the system monitoring service to be able to monitor each instance." Each instance... hmmm... getInstance() ain't gonna cut it :-)
Effective Java says:
Singletons typically represent some system component that is intrinsically
unique, such as a video display or file system.
So if your component warrants single instance accross the entire application and it has some state, it makes sense to make it a singleton
In your case, the settings of the application is a good candidate for singleton.
On the other hand, a class can only have static methods if you want to group certain functions together, such as utility classes, examples in jdk are java.util.Arrays java.util.Collections. These have several related methods that act on arrays or collections
Singleton will give you an object reference, that you can use all over your app...
you will use singleton if you want objects and/or polymorphism...
If you don't ever need to instantiate them, I don't see the point of singletons. Well, I should amend that - if these classes cannot be instantiated, then it doesn't make sense to compare them to singletons - the singleton pattern restricts instantiation to one object, and comparing that to something that cannot be instantiated doesn't make sense.
I find my main use of singletons generally involves a class that has static methods that, after maybe preparing an environment, instantiate an instance of themselves. By utilising private constructors and overriding Object.clone() to throw CloneNotSupportedException, no other classes can create a new instance of it, or if they're ever passed an instance of it, they cannot clone it.
I guess I'd say that if your application settings are part of a class that is never instantiated, it's not relevant to say "It should/shouldn't be a singleton."
I think you no need to create signleton class.
just make this class constructor private.
Like Math class in java.
public final class Math {
/**
* Don't let anyone instantiate this class.
*/
private Math() {}
//static fields and methods
}
Singletons often show up in situations like you're describing- you have some sort of global data that needs to live in some place, and you'll only ever need one, preferably you want to make sure that you can only have one.
The simplest thing you can do is a static variable:
public class Globals{
public static final int ACONSTANT=1;
This is fine, and ensures that you'll have only one, and you have no instantiation issues. The main downside, of course, is that it's often inconvenient to have your data baked in. It also runs into loading issue if, for example, your string is actually built, by, say, building something from an outside resource (there's also a gotcha with primitives - if your static final is an int, say, classes that depend on it compile it inline, which means that recompiling your constants may not replace the constants in the app - e.g., given public class B{ int i = Globals.ACONSTANT; } changing Globals.ACONSTANT and recompiling only Globals will leave B.i still =1.)
Building your own singleton is the next simplest thing to do, and is often fine (though look up discussions on problems inherent in singleton loading, e.g. double-checked locking).
These sorts of issues are a big reason why many apps are built using Spring, Guice, or some other framework that manages resource loading.
So basically:
Statics
Good: easy to code, code is clear and simple
bad: Not configurable- you've got to recompile to change your values, may not be workable if your global data requires complex initialization
Singletons fix some of this, Dependency Injection frameworks fix and simplify some of the issues involved in singleton loading.
Since your class is holding global settings, a pro for a singleton could be that you have more control about creation of the singleton. You could read a configuration file during object creation.
In other cases if methods are static there would be no benefit like in javas Math class which has only static members.
A more obvious need for singletons is when you implement factories as singletons, because you can interchange different implementations of this factory.
Sometimes what people think belong as Singleton objects really can be private members of a class. Other times they should be unique global variables. Depends on what the design needs them to be.
If there should be one, and exactly one instance of an object: use a Singleton. By that, I mean if the program should HALT if there's more than one object. A good example is if you're designing a video game that only supports rendering to a single output device, ever. Trying to opening the same device again (shame on you for hardcoding!) would be forbidden. IMHO a case like that often means you shouldn't be using classes in the first place. Even C allows you to trivially encapsulating such a problem without the complexity of making a Singleton class, and still maintain the elements of OO that apply to a singleton. When you're stuck in a language like Java/C# , the singleton pattern is what you've got to work with, unless purely static members will do the trick on their own. You can still simulate the other way through those.
If it's merely a case of interfacing objects, you probably should think more object oriented. Here's another example: let's say our game engines rendering code needs to interface resource and input managers, so it can do it's job. You could make those singletons and do sth like ResourceManager.getInstance().getResource(name). Or you could create an application class (e.g. GameEngine) that has ResourceManager and InputManager as private members. Then have the GameEngine pass these as necessary to methods of the rendering code. Such as r.render(resourcemanager);.
For singletons—can easily be accessed from anywhere, it's like a global variable, but there can only be one copy of it.
Against singletons—many uses of singletons can be solved by encapsulating it within in a parent object and passing a member object to another member objects methods.
Sometimes just using a stupid global variable is the right thing. Like using GOTO or a compounded (and/or) conditional statement instead of writing the same error handling code N times with copy and paste.
Code smarter, not harder.
You should use singletons for modularization.
Imagine the following entities in singleton:
Printer prt;
HTTPInfo httpInfo;
PageConfig pgCfg;
ConnectionPool cxPool;
Case 1.
Imagine if you did not do that, but a single class to hold all the static fields/methods.
Then you would have one big pool of static to deal with.
Case 2.
In your current case, you did segregate them into their appropriate classes but as static references. Then there would be too much noise, because every static property is now available to you. If you do not need the information, especially when there is a lot of static information, then you should restrict a current scope of the code from seeing unneeded information.
Prevention of data clutter helps in maintenance and ensure dependencies are restricted. Somehow having a sense of what is or is not available to me at my current scope of coding helps me code more effectively.
Case 3 Resource identity.
Singletons allow easy up-scaling of resources. Let us say you now have a single database to deal with and therefore, you place all its settings as static in the MyConnection class. What if a time came when you are required to connect to more than one database? If you had coded the connection info as a singleton, the code enhancement would comparative much simpler.
Case 4 Inheritance.
Singleton classes allow themselves to be extended. If you had a class of resources, they can share common code. Let's say you have a class BasicPrinter which is instantiable as singleton. Then you have a LaserPrinter which extends BasicPrinter.
If you had used static means, then your code would break because you would not be able to access BasicPrinter.isAlive as LaserPrinter.isAlive. Then your single piece of code would not be able to manage different types of printers, unless you place redundant code.
If you are coding in Java, you could still instantiate a totally static content class and use the instance reference to access its static properties. If someone should do that, why not just make that a singleton?
Of course, extending singleton classes have their issues beyond this discussion but there are simple ways to mitigate those issues.
Case 5 Avoid information grandstanding.
There are so few pieces of info that needs to be made globally available like the largest and smallest integers. Why should Printer.isAlive be allowed to make a grandstand? Only a very restricted set of information should be allowed to make a grandstand.
There is a saying: Think globally, act locally. Equivalently, a programmer should use singletons to think globally but act locally.
Effective Java says:
Singletons typically represent some system component that is intrinsically
unique, such as a video display or file system.
So if your component warrants single instance across the entire application and it has some state, it makes sense to make it a singleton.
(The above nakedly borrowed from naikus)
In many cases the above situation can be handled by a 'utility class' in which all the methods are static. But sometimes a Singleton is still preferred.
The main reason for advocating a Singleton over a Static Utility Class is when there is a non-negligible cost involved in setting it up. For example if your class represents the file system, it will take some initialization, which can be put in the constructor of a Singleton but for a Static Utility Class will have to be called in the Static Initializer. If some executions of your app might never access the file system then with a Static Utility Class you have still paid the cost of initializing it , even though you don't need it. With a Singleton if you never need to instantiate it you never call the initialization code.
Having said all that, Singleton is almost certainly the most-overused design pattern.
This is language agnostic, but I'm working with Java currently.
I have a class Odp that does stuff. It has two private helper methods, one of which determines the max value in an int[][], and the other returns the occurrences of a character in a String.
These aren't directly related to the task at hand, and seem like they could be reused in future projects. Where is the best place to put this code?
Make it public -- bad, because Odp's functionality is not directly related, and these private methods are an implementation detail that don't need to be in the public interface.
Move them to a different class -- but what would this class be called? MiscFunctionsWithNoOtherHome? There's no unifying theme to them.
Leave it private and copy/paste into other classes if necessary -- BAD
What else could I do?
Here's one solution:
Move the method that determines te max value in a two-dimensional int array to a public class called IntUtils and put the class to a util package.
Put the method that returns the occurrences of a character in a String to a puclic class called StringUtils and put the class to a util package.
There's nothing particularly bad about writing static helper classes in Java. But make sure that you don't reinvent the wheel; the methods that you just described might already be in some OS library, like Jakarta Commons.
Wait until you need it!
Your classes wil be better for it, as you have no idea for now how your exact future needs will be.
When you are ready, in Eclipse "Extract Method".
EDIT: I have found that test driven development give code that is easier to reuse because you think of the API up front.
A lot of people create a Utility class with a lot of such methods declared as static. Some people don't like this approach but I think it strikes a balance between design, code reuse, and practicality.
If it were me, I'd either:
create one or more Helper classes that contained the methods as static publics, naming them as precisely as possible, or
if these methods are all going to be used by classes of basically the same type, I'd create an abstract base class that includes these as protected methods.
Most of the time I end up going with 1, although the helper methods I write are usually a little more specific than the ones you've mentioned, so it's easier to come up with a class name.
I not know what the other languages do but I have the voice of experience in Java on this: Just move to the end-brace of your class and write what you need ( or nested class if you prefer as that is accepted canonical convention in Java )
Move the file scope class ( default access class right there in the file ) to it's own compilation unit ( public class in it's own file ) when the compiler moans about it.
See other's comments about nested classes of same name if differing classes have the same functionality in nested class of same name. What will happen on larger code bases is the two will diverge over time and create maintainability issues that yield to Java's Name of class as type of class typing convention that forces you to resolve the issue somehow.
What else could I do?
Be careful not to yield to beginner impulses on this. Your 1-2 punch nails it, resist temptation.
In my experience, most large projects will have some files for "general" functions, which are usually all sorts of helper functions like this one which don't have any builtin language library.
In your case, I'd create a new folder (new package for Java) called "General", then create a file to group together functions (for Java, this will just be a class with lots of static members).
For example, in your case, I'd have something like: General/ArrayUtils.java, and in that I'd throw your function and any other function you need.
Don't worry that for now this is making a new class (and package) for only one function. Like you said in the question, this will be something you'll use for the next project, and the next. Over time, this "General" package will start to grow all sorts of really great helper classes, like MathUtils, StringUtils, etc. which you can easily copy to every project you work on.
You should avoid helper classes if you can, since it creates redundant dependencies. Instead, if the classes using the helper methods are of the same type (as kbrasee wrote), create an abstract superclass containing the methods.
If you do choose to make a separate class do consider making it package local, or at least the methods, since it may not make sense for smaller projects. If your helper methods are something you will use between projects, then a library-like approach is the nicest to code in, as mentioned by Edan Maor.
You could make a separate project called utils or something, where you add the classes needed, and attach them as a library to the project you are working on. Then you can easily make inter-project library updates/fixes by one modification. You could make a package for these tools, even though they may not be that unified (java.util anyone?).
Option 2 is probably your best bet in Java, despite being unsatisfying. Java is unsatisfying, so no surprise there.
Another option might be to use the C Preprocessor as a part of your build process. You could put some private static functions into file with no class, and then include that file somewhere inside a class you want to use it in. This may have an effect on the size of your class files if you go overboard with it, of course.