I am designing an application where a class named Rights is used. This class contains information about what the user can /can’t do and also contains other classes like DocumentFilters.
The issue here is that I have a lot of different parts of the application getting an instance of that class through their constructor or get method, in order to be able to verify a user action before allowing it. It seems like this is bad practice (I might be wrong). Are there ways to improve this?
The way it works is having the main class of the application creating the Rights class and then creating different components and passing it to those. The components don’t have instance of the main class ether.
Example code. This is repeated over several Modules.
public class ModuleA{
private Rights rights;
public ModuleA(Rights rights){
this.rights=rights;
}
private boolean verifyRights(ActionEvent e){
if(e.getSource("copyButton"){
if(rights.allowedToCopy){
return true;
}
return false;
}
}
That is a valid design and it is called Inversion of control and more specificly Dependency Injection. You can try to use an IoC container for java if you don’t want to inject your dependencies manually.
It is also possible to separate the security code into aspects by using AOP. This is a more advanced option, but doing so you can separate the code that checks the security from the real business code.
If the method you showed is duplicated exactly in your Module classes, you should extract the method into a base class. This base class should then be used for all your Module classes.