A NinjectBootstrapper class has been created in a Service project(responsible for getting products).
This is my code
public static class NinjectBootstrapper
{
private static readonly object _thislock = new object();
//flag to prevent bootstrap for executing multiple times
private static bool _done;
public static void Bootstrap()
{
lock(_thislock)
{
if(_done)
{
return;
}
_done = true;
// services
NinjectContainer.Kernel.Bind<IProductService>().To<ProductService>();
// repositories
NinjectContainer.Kernel.Bind<IProductRepository>().To<ProductRepository>();
}
}
}
Now, while this works, I would really like to know if there are better ways to refactor my code. For instance I've read a lot of stuff about using a singleton instead of the static class.
I'd like to really set a good base here to make it easy and flexible for future developers to extend functionality. What are some good pointers and tips I can take into consideration?
I've read a lot of stuff about using a singleton instead of the static class.
When applying DI we typically prefer instance classes over static classes, because we can't practice Constructor Injection in static classes. This doesn't mean however, that static classes are a bad practice. When classes have no dependencies and no state, static is fine.
This holds as well for code in the startup path, such as your NinjectBootstrapper. You can make it an instance class, but since this class is started directly at startup, no dependencies need to be injected (obviously, because it is the thing that wires the DI container), it would typically be useless to make this an instance class.
Related
I am trying to test my Service class below
#Service
#RequiredArgsConstructor(onConstructor = #__(#Autowired))
public class TaskTemplateService {
#NonNull
TaskTemplateRepository taskTemplateRepository;
public void doStuff() {
List<MyObject> list;
doOtherStuff(list)
}
private void doOtherStuff(List <MyObject>) {
//do stuff
}
}
When I am testing the real TaskTemplate, how can I capture what is passed to doOtherStuff?
You cannot and why would you?
Good testing means to specify the behaviour of a unit's public interface. Private methods ought to be covered via testing this way indirectly. If this is not possible then either you have dead, unreachable code or a design problem and should refactor.
BTW, the technical reason that you cannot mock/stub private methods is that most mocking tools, also the built-in feature of Spock, use dynamic proxies (DP) in order to implement mocking. DP technically are subclasses, but private methods can never be extended or even seen by subclasses or being called by them or from other classes, hence the term "private". Consequently, a mock subclass cannot check interactions with private methods.
How exactly you ought to redesign your class in order to make it testable really depends on why you want to "capture" the method argument, as you say. Do you need to replace it by a mock? Do you need to modify or verify the content of the original object?
If the object has a central meaning and you need to replace or verify it, why not make it injectable instead of creating it as a local variable, hermetically sealing it off from the outside world and making it untestable?
Or maybe in your case you could make the private method protected or package-scoped in order to make it testable. Then at least a mock could be created for it and you could capture the argument or stub the result.
I am mostly speculating here because the answer really depends on what is behind //do stuff, i.e. the very information you are hiding in your sample code.
I process messages from a queue. I use data from the incoming message to determine which class to use to process the message; for example origin and type. I would use the combination of origin and type to look up a FQCN and use reflection to instantiate an object to process the message. At the moment these processing objects are all simple POJOs that implement a common interface. Hence I am using a strategy pattern.
The problem I am having is that all my external resources (mostly databases accessed via JPA) are injected (#Inject) and when I create the processing object as described above all these injected objects are null. The only way I know to populate these injected resources is to make each implementation of the interface a managed bean by adding #stateless. This alone does not solve the problem because the injected members are only populated if the class implementing the interface is itself injected (i.e. container managed) as opposed to being created by me.
Here is a made up example (sensitive details changed)
public interface MessageProcessor
{
public void processMessage(String xml);
}
#Stateless
public VisaCreateClient implements MessageProcessor
{
#Inject private DAL db;
…
}
public MasterCardCreateClient implements MessageProcessor…
In the database there is an entry "visa.createclient" = "fqcn.VisaCreateClient", so if the message origin is "Visa" and the type is "Create Client" I can look up the appropriate processing class. If I use reflection to create VisaCreateClient the db variable is always null. Even if I add the #Stateless and use reflection the db variable remains null. It's only when I inject VisaCreateClient will the db variable get populated. Like so:
#Stateless
public QueueReader
{
#Inject VisaCreateClient visaCreateClient;
#Inject MasterCardCreateClient masterCardCreateClient;
#Inject … many more times
private Map<String, MessageProcessor> processors...
private void init()
{
processors.put("visa.createclient", visaCreateClient);
processors.put("mastercard.createclient", masterCardCreateClient);
… many more times
}
}
Now I have dozens of message processors and if I have to inject each implementation then register it in the map I'll end up with dozens of injections. Also, should I add more processors I have to modify the QueueReader class to add the new injections and restart the server; with my old code I merely had to add an entry into the database and deploy the new processor on the class path - didn't even have to restart the server!
I have thought of two ways to resolve this:
Add an init(DAL db, OtherResource or, ...) method to the interface that gets called right after the message processor is created with reflection and pass the required resource. The resource itself was injected into the QueueReader.
Add an argument to the processMessage(String xml, Context context) where Context is just a map of resources that were injected into the QueueReader.
But does this approach mean that I will be using the same instance of the DAL object for every message processor? I believe it would and as long as there is no state involved I believe it is OK - any and all transactions will be started outside of the DAL class.
So my question is will my approach work? What are the risks of doing it that way? Is there a better way to use a strategy pattern to dynamically select an implementation where the implementation needs access to container managed resources?
Thanks for your time.
In a similar problem statement I used an extension to the processor interface to decide which type of data object it can handle. Then you can inject all variants of the handler via instance and simply use a loop:
public interface MessageProcessor
{
public boolean canHandle(String xml);
public void processMessage(String xml);
}
And in your queueReader:
#Inject
private Instance<MessageProcessor> allProcessors;
public void handleMessage(String xml) {
MessageProcessor processor = StreamSupport.stream(allProcessors.spliterator(), false)
.filter(proc -> proc.canHandle(xml))
.findFirst()
.orElseThrow(...);
processor.processMessage(xml);
}
This does not work on a running server, but to add a new processor simply implement and deploy.
I'm trying to figure out which is the best way to design my game's structure.
Currently I store class instances everywhere but I would prefer to use a straight up static access.
For example I have a class called "GameSaveSystem.cs"
This class handled obtaining a StorageDevice and all storage related information for all current players.
So my current strategy is the following
----------------MainClass.cs
public static void Main(string[] args) {
new Main();
}
----------------Main.cs
public Main() {
GameSaveSystem save_system = new GameSaveSystem();
singlePlayer = new SinglePlayer(save_system);
multiPlayer = new MultiPlayer(save_system);
}
----------------SinglePlayer.cs
SinglePlayer(GameSaveSystem save_system) {
this.save_system = save_system;
}
----------------MultiPlayer.cs
MultiPlayer(GameSaveSystem save_system) {
this.save_system = save_system;
}
The reason I do it like this is because in Java i could create a new .Java file and have it call "MainClass.main(args);"
So then Inside that extra class I can gain access to any Static class members or public static instances which are stored throughout the class files.
so what i'm wondering is would it be safer to use instances or for this type of situation should i just go with static classes? I want the game to have some kind of security against this types of issues.
So below are the 3 ways I've seen for grabbing access to a class
Static access - were the person can access this class at anytime from anywhere (This is my preferred strategy for ease of use).
ClassB.DoSomething();
Instances stored everywhere - Each every class will have the created instance of a class stored so they have access to it at anytime. Classes have all the instances they will need stored and nothing else.
public class A(ClassB classB) {
this.classB = classB;
}
classB.DoSomething();
Instance stored in one class - 1 Class creates a single instance of all the classes which would normally have only 1 instance created. Then you create an instance of this class and store it into all the classes which require access to the previously created instances. Only the classes which stored the main instance will have access to the other instances.
public class A(Main main) {
this.main = main;
}
main.getInstanceB().DoSomething();
It looks to me like you would benefit from reading a little bit on this.
Essentially which one you go with is more of a personal choice. There are, of course, performance considerations for each, but semantics are also important. It's up to you, as the software engineer, to decide what's best.
To communicate between views and objects persistant information, for example the username and choice of font size for display, is it considered good form to put these onto the Application object, or is it more efficient to put them into static singletons?
For example:
public class Application
{
static void Main (string[] args)
{
UIApplication.Main (args);
}
public static Username {get;set;}
}
I don't think there's any difference performance-wise between putting static objects into the Application vs singletons vs static classes.
For things like Colors and fonts, I usually prefer to create static classes to hold each type of object, so for example I usually write this:
public static class Colors {
public static Color ToolbarColor = Color.Black;
..
}
This makes it easier to change colors around the entire app without having to be searching around everywhere. I do the same thing for fonts, images, etc.
I want to be able to support multiple versions of Java ME without having to have multiple builds. I already know how to detect the profile/configuration/supported JSRs. My problem is that knowing whether the JSR is supported at run time doesn't allow me to use all the features as Java-ME does not provide support for reflection.
For if I call a function added in a later version anywhere in the code - even a location that will never be run, then this could cause an error during resolution on some JVMs. Is there any way round this?
Related Questions
Handling optional APIs in J2ME
If you only need to access the class C through an interface which you know you will have access to, then it is simple enough:
MyInterface provider=null;
try{
Class myClass= Class.forName("sysPackage.C");
provider = (MyInterface)(myClass.newInstance());
}catch(Exception ex){
}
if(provide!=null){
//Use provider
}
If C does not have an interface that can be used, then we can instead create a wrapper class S that will be a member of the interface instead.
class S implements MyInterface{
static {
try {
Class.forName("sysPackage.C");
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
public static void forceExceptionIfUnavailable() {}
//TODO: Methods that use C. Class C will only be used within this class
}
S has a static block so that an exception is thrown during class resolution if C is unavailable. Immediately after loading the class, we call forceExceptionIfUnavailable to make sure that the static block is run immediately. If it doesn't crash, then we can use the methods in S to indirectly use class C.
Alternatively, we can use the method here:
Basically, you create a new package P, with a public abstract class A and a concrete subclass S private to the package. A has a static method getS that returns an instance of S or null if an exception is thrown during instantiation. Each instance of S has an instance of C so it will fail to instantiate when C is unavailable - otherwise it will succeed. This method seems to be a bit safer as S (and hence all the C APIs) are package private.