You have the right idea. Perhaps this will help you. I recommend that you follow two rules for all of your significance classes, where “significance” means that if you don't follow the steps, it will be harder to test, reuse, or maintain the class. Here are the rules:
- never create or acquire addiction on your own
- always works with interfaces
You have a beginning in rule number 1. You have modified your Info class so that you no longer create its dependencies. By “dependency” I mean other classes, configuration data loaded from property files, or something else, etc. When you depend on how something is created, you associate your class with it and make it difficult to test, reuse, and maintain it. Thus, even if a dependency is created using factory or singleton, do not create its class. Ask for something else to call create() or getInstance() or something else and pass it.
So you chose “something else” as the class that your class uses and realized that it has a bad smell. The tool is to instead have your entry point into your application instantiate all the dependencies. In a traditional java application, this is your main() method. if you think about it, creating classes and connecting them to each other or wiring them is a special kind of logic: the logic is “building applications”. Is it better to spread this logic throughout the code or put it in one place to make it easier to maintain? The answer is that collecting it in one place is better - not only for maintenance, but also for this, all your significance classes turn into more useful and flexible components.
In your main() or the equivalent of main() you must create all the objects you need by passing them to each other's setters and constructors in order to "bind" them together. Then your unit tests will pass them differently, passing layouts or similar things. All this is done as an “dependency injection”. After I say, you will probably have a big ugly main() method. This is where a dependency injection tool can help you and actually make your code infinitely more flexible. A tool that I would suggest when you get to this point, like others, suggested another, Spring.
The less important rule # 2 is to always program on interfaces, it is still very important, since it eliminates all implementation dependencies, simplifies reuse, not to mention the use of other tools, such as mock object frameworks, ORM structures, etc. OK.
Single shot
source share