Related
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.
After comming from Ruby world, I'm having little problems doing TDD in Java. The biggest issue is when I have application that is just communicating with external API.
Say I want to just fetch some data from Google Calendar, or 5 tweets from some Twitter user and display it.
In Ruby, I don't have any problems, because I can monkey-patch the API library in tests directly, but I have no such option in Java.
If I think about this in terms of MVC, my model objects are directly accessing the API through some library. The question is, is this bad design? Should I always wrap any API library in some interface, so I can mock/stub it in Java?
Because when I think about this, the only purpose of that interface would be to simulate (please don't kill me for saying this) the monkey-patch. Meaning that any time I use any external resource, I have to wrap each layer in interface that can be stubbed out.
# do I have to abstract everything just to do this in Java?
Twitter.stub!(:search)
Now you might say that I should always abstract away the interface, so I can change the underlying layer to anything else. But if I'm writing twitter app, I'm not going to change it to RSS reader.
Yes, I can add for example Facebook and then it would make sense to have interface. But when there is no other resource that can be substituted for the one I'm using, than I still have to wrap everything in interfaces to make it testable.
Am I missing something, or is this just a way to test in the Java world?
Using interfaces is just generally good practice in Java. Some languages have multiple inheritance, others have duck typing, Java has interfaces. It's a key feature of the language, it lets me use
different aspects of a class in different contexts and
different implementations of the same contract without changing client code.
So interfaces are a concept you should embrace in general, and then you would reap the benefits in situations like this where you could substitute your services by mock objects.
One of the most important books about Java best practices is Effective Java by Joshua Bloch. I would highly suggest you to read it. In this context the most important part is Item 52: Refer to objects by their interfaces. Quote:
More generally, you should favor the use of interfaces rather than
classes to refer to objects. If appropriate interface types exist, then parameters, return values, variables, and fields should all be declared using interface
types. The only time you really need to refer to an object’s class is when you’re
creating it with a constructor.
And if you take things even further (e.g. when using dependency injection), you aren't even calling the constructor.
One of the key problems of switching languages is that you have to switch the way of thinking too. You can't program language x effectively while thinking in language y. You can't program C effectively without using pointers, Ruby not without duck typing and Java not without Interfaces.
Wrapping the external API is the way I would do this.
So, as you already said, you would have an interface and two classes: the real one and the dummy implementation.
Yes, it may seem unreasonable from the perspective of some services indeed being specific, like Twitter. But, this way your build process doesn't depend on external resources. Depending on external libraries isn't all that bad, but having your tests depend on actual data present or not present out there on the web can mess up the build process.
The easiest way is to wrap the API service with your interface/class pair and use that throughout your code.
I understand that what you want are Mock objects.
As you described it, one of the ways one can generate "test versions" of objects is by implementing a common interface and using it.
However, what you are missing is to simply extend the class (provided that it is not declared final) and override the methods that you want to mock. (NB: the possibility of doing that is the reason why it is considered bad form for a library to declare its classes final - it can make testing considerably harder.)
There is a number of Java libraries that aim in facilitating the use of Mock objects - you can look at Mockito or EasyMock.
Mockito is more handy and like your ruby mocks.
You can "monkey-patch" an API in Java. The Java language itself does not provide specific means to do it, but the JVM and the standard libraries do. In Ruby, developers can use the Mocha library for that. In Java, you can use the JMockit library (which I created because of limitations in older mocking tools).
Here is an example JMockit test, equivalent to the test_should_calculate_value_of_unshipped_orders test available in Mocha documentation:
#Test
public void shouldCalculateValueOfUnshippedOrders()
{
final Order anOrder = new Order();
final List<Order> orders = asList(anOrder, new Order(), new Order());
new NonStrictExpectations(Order.class)
{{
Order.findAll(); result = orders;
anOrder.getTotalCost(); result = 10;
}};
assertEquals(30, Order.unshippedValue());
}
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.
My application stores files, and you have the option of storing the files on your own server or using S3.
I defined an interface:
interface FileStorage {
}
Then I have 2 implementations, S3FileStorage and LocalFileStorage.
In the control panel, the administrator chooses which FileStorage method they want, and this value is stored in a SiteConfiguration object.
Since the FileStorage setting can be changed while the application is already running, would you still use spring's DI to do this?
Or would you just do this in your code:
FileStorage fs = null;
switch(siteConfig.FileStorageMethod)
case FileStorageMethod.S3:
fs = new S3FileStorage();
case FileStorageMethod.Local:
fs = new LocalFileStorage();
Which one makes more sense?
I believe you can use DI with spring during runtime, but I haven't read about it much at this point.
I would inject a factory, and let clients request the actual services from it at runtime. This will decouple your clients from the actual factory implementation, so you can have several factory implementations as well, for example, for testing.
You can also use some kind of a proxy object with several strategies behind it instead of the factory, but it can cause problems, if sequence of calls (like open, write, close for file storage) from one client cannot be served by different implementations.
I would still use Dependency Injection here. If it can be changed at runtime, you should inject it using setter injection, rather than constructor injection. The benefit of using any dependency injection is that you can easily add new implementations of the interface without changing the actual code.
DI without question. Or would you prefer to enhance your factory code when you create/update/delete an implementation? IMO, If you're programming to an interface, then you shouldn't bootstrap your implementations, however many layers deep it actually occurs.
Also, DI isn't synonymous to Spring, et al. It's as simple as containing a constructor with the abstracted interface as an argument, i.e. public FileApp(FileStorage fs) { }.
FYI, another possibility is a proxy.
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.