MVC in Java - Static controller? - java

I have a number of different organisations, each of which is an instance of the Organisation class. This contains getters and setters for instance variables, the setters contain validation where appropriate. It also has a few other odds and ends - overwritten toString(), equals() and hashCode() for example.
I have OrganisationView extends JFrame which accepts an Organisation and displays it in the GUI, and includes listeners for the various functions.
I understand from this question how this should all fit together and work with OrganisationController. What I'm not clear on is how many, if any, instances of OrganisationController I need. Is it one per organisation, and storing the organisation it refers to as an instance variable? Because it seems easier just to declare OrganisationController as static and call its methods directly from OrganisationView giving OrganisationView a method something like:
private boolean deleteButtonPressed(){
return OrganisationController.deleteOrganisation(this.organisationDisplayed)
}
(and perhaps some other business logic, but that's by the by)
OrganisationView, by the way, is called each time that particular display is needed, and is passed the organisation to show.
My question is: If it is better to have a separate instance of OrganisationController for each Organisation then why? It seems like an unnecessary amount of objects differing only in one instance variable. Or are static controllers acceptable?

I would not make it static. Use a singular controller and separate your views into directories. Then you can organized each part accordingly. You don't want to statically call the controller from the view. You want each person who logs in to have their own instance. Its simply a matter of separating out your views, models etc into separate folders and directories. I'm actually working on a project right now where I do this. I prepend each section with a keyword so as to keep it separate.

You can use the Singleton pattern to make sure that you only create one Controller && also access your controller in a static way.
I suggest you go for the enum implementation of Singleton which would be something like this
public enum OrganisationController{
INSTANCE;
// you can have fields
private final example;
// and also methods
public boolean deleteOrganisation(Organization org){
// do whatever here
}
}
And you can invoke methods in a static-looking way
OrganisationController.INSTANCE.deleteOrganization(org);

Related

Only one class can instantiate all other clases

What is best practice to restrict instantiation of the classes to only one class? Something like this but in Java.
Let's say there is Main class, then there are User, Admin, View, Data, Client etc. classes. Only 'Main' class should be able to instantiate all other classes.
So if 'User' need to call 'getUser' method in 'Data' class, it can't instantiate 'Data' class and call method, but it has to call 'Main' class, and then 'Main' will instantiate 'Data' class and pass arguments to its 'getUser' method.
What I am thinking is using private constructor, Factory Pattern etc., but not sure if this will result in what I need. Due to the complexity I don't think inner classes would be good solution.
Any advice on this?
A distinct answer on the conceptual level (as there are already good answers on the technical "how to do it"):
Let's say there is Main class, then there are User, Admin, View, Data, Client etc. classes. Only 'Main' class should be able to instantiate all other classes.
I don't think this is a good starting point. Of course, when one follows Domain Driven Design, using factories is well established.
But there is one subtle point to add: you still want to cut your "boundaries" in reasonable ways. Meaning: don't force all objects into a single factory. Your objects should somehow resemble their domains, and be separated where needed.
Meaning: using factories is fine, but don't force yourself into the wrong corner by enforcing that there is exactly one factory that is supposed to handle all kinds of objects you deal with. Instead: try to reasonably partition your object model, and have as many factories as it makes conceptually sense to have.
Also note that you probably should distinguish between objects that mainly provide data/information, and "behavior" on the end. Thus it might be worth looking into the idea of having a service registry (for example what you do with the netflix Eureka framework, see here).
And finally, to quote an excellent comment given by tucuxi here: For small applications, factories are over-engineering. For larger applications, I find it questionable to have a single factory called "Main", instead of splitting responsibilities in a more orthodox way.
You can use a subclass with a private constructor:
With this, only InstantiatonClass can create InstantiatonClass.ArgClass and the constructor of ProtectedClass.
public class ProtectedClass{
//constructor that can only be invoked with an instance of ArgClass
public ProtectedClass(InstantiatonClass.ArgClass checkArg){}
}
public class InstantiatonClass{
public static class ArgClass{
//constructor that can only be invoked from InstantiatonClass
private ArgClass(){}
}
}
You should be able to get caller's class in a Class's constructor:
How to get the name of the calling class in Java?
Then in the classes where you only want to be instantiated by Main, simply check the caller class is Main in its constructor, if not throw a RuntimeException.

What is the purpose of creating a class-level variable in Java?

I was writing a piece of code that goes like this,
public class Grades
{
public int marks; // what's the purpose of this?
...
...
}
Objects are data and methods encapsulated together into a single software component.
Classes are templates ("cookie cutters") from which you can create one or more instances in memory ("cookies"). Each one is independent; each can have its own state.
By declaring the variable outside of any methods you've made it an attribute of the class. This means that any method in the class can access it, and depending on its encapsulation (public/private/protected/package private) other classes can access it as well.
As for that specific variable's purpose in that specific class, that cannot be determined without seeing more code.

Is there a point to having a class with all non-static methods but no non-static fields? (or all static fields and methods along with a constructor)

I am looking at other peoples' code.
I see a class with no non-static fields but in which most of the methods are non-static, requiring you to make an object to access methods that effectively operate statically.
Is there a possible reason for this, that I am just not understanding?
EDIT
Someone asked for examples. Here is some more info.
For instance there is a file manager class. The only fields are static and are Comparators. There are some methods to do things like sort files in a list, count files, copy files, move files to an archive folder, delete files older than a certain time, or create files (basically take a base name as string, and return a File with given base name and date/time tacked on the end.)
9 non-static methods
5 static methods
I don't see a particular rhyme reason for the ones that are static vs non.
One particularly odd thing is that there are two methods for removing files. One that removes a file no matter what, and one that only removes it if it is empty. The former is a static method while the latter is not. They contain the same exact code except the later first checks if the file.length is 0.
Another odd one is a class that does encryption - all fields and methods are static but it has a constructor that does nothing. And an init() method that checks if a static variable contains an object of itself and if not instantiates an object of itself into that field that is then never actually used. (It seems this is done with a lot of classes - init methods that check for an object of itself in a static variable and if not instantiate itself)
private static File keyfile;
private static String KEYFILE = "enc.key";
private static Scrambler sc;
It has methods to encrypt and decrypt and some methods for dealing with key and file.
Does this make sense to anyone? Am I just not understanding the purpose for this stuff? Or does it seem weird?
Objects don't have to have state. It's a legitimate use case to create an instance of a class with only behaviour.
Why bother to create an instance ? So you can create one and pass it around e.g. imagine some form of calculator which adheres to a particular interface but each instance performs a calculation differently. Different implements of the interface would perform calculations differently.
I quite often create classes with non-static methods and no members. It allows me to encapsulate behaviour, and I can often add members later as the implementation may demand in the future (including non-functionality related stuff such as instrumentation) I don't normally make these methods static since that restricts my future flexibility.
You can certainly do it that way. You should look carefully at what the instance methods are doing. It's perfectly okay if they're all operating only on parameters passed in and static final static class constants.
If that's the case, it's possible to make all those methods static. That's just a choice. I don't know how the original developers would justify either one. Maybe you should ask them.
Let me rephrase this question a bit,
Even though methods are non-static why would one declare fields as static?
I have taken below quoting from Java Docs,
Sometimes, you want to have variables that are common to all objects. This is
accomplished with the static modifier. Fields that have the static modifier in their declaration are called static fields or class variables. They are associated with the class, rather than with any object. Every instance of the class shares a class variable, which is in one fixed location in memory. Any object can change the value of a class variable, but class variables can also be manipulated without creating an instance of the class.
For example, suppose you want to create a number of Bicycle objects and assign each a serial number, beginning with 1 for the first object. This ID number is unique to each object and is therefore an instance variable. At the same time, you need a field to keep track of how many Bicycle objects have been created so that you know what ID to assign to the next one. Such a field is not related to any individual object, but to the class as a whole.
For Bicycle example, kindly refer the Java Docs.
Making all methods non-static allows you to override them. This makes it a lot easier to use this class in testing, because instead of the actual implementation you can use a mock that behaves as you want it for the tests. Static methods are, in my book, a code smell and should be avoided unless there's a good reason (e.g. quite trivial utility methods).
Also, at some point in the future you might want to change the behaviour of the methods in some situation, e.g. in the form of a strategy.
In the case of your encryption class, you might want to hand your class an instance of the encryption class to handle encrypting/decrypting, but be able to configure the details in some other place. That would allow you to change the algorithm and much more easily test your own code without also having to test the encryption.

How would i access Object properties an object method?

What is the "correct" way to access an object's properties from within an object method that is not a getter/setter method?
Getter/Setter is the recommended way of accessing properties of an object. Otherwise you to have to use public properties, but public properties are not recommended.
If a classes' properties don't have getters and they are not visible (e.g. not public), that means that the class is designed so that you can't access them. In that case, there is no proper way to access them.
Flipping this around, if you are designing a class and you intend that other classes can access its attributes, you ought to provide getters. You could alternatively declare the attributes to be public, protected or package private, but that makes your abstraction leaky and has a number of undesirable consequences.
If you are asking how one of an object's methods should access its own attributes, the simple answer is whichever way is most convenient. If the class has getters, you could call them. Alternatively, you could just access the attributes directly. The problems of leaky abstraction don't apply in this case because the method accessing the state is inside the abstraction boundary.
This is mostly a matter of preference.
I personally prefer not to use the getters and setters in my object. This increases readability, allows me to change my getters and settings to return copies (of lists mostly) without it changing my own object. If you do something special in your getter then you can make a helper method that is used by both your getter and your other functions. This will go wrong if your classes get too large though (so don't make large classes). I don't like how using a getter setter hides the side effects inside the object (unlike for external users, they should be hidden from any side effects inside the object), when you want to have the side effects, give the private method a clear name indiciting it has them.
First off I'll answer the question as is:
What is the "correct" way to access an object's properties from within an object method that is not a getter/setter method?
When you are within an object, you can reference the properties directly where the method is part of the object. For example:
public class testClass() {
public int x;
private someMethod() {
x = 4;
}
}
To answer the comment:
I think the question can be reformulated: Should I use getters and setters when implementing my object methods? Or should I access member variables directly?
You should always hide the internal data and other implementation details within a class as much as possible; seperating the API from the implementation (a.k.a encapsulation). Encapsulation decouples the modules thereby allowing them to be developed, tested and modified in isolation.
Generally, you should use the lowest access modifier possible (e.g. private, protected, package-private) whilst maintaining functionality for the application you're writing. The benefits of designing and devloping this way is that you can change implementation details without breaking code that uses the modules. If you make everything public, and other people are using your classes, you are forced to support it forever maintaining compatibility - or until they change their implementation that is using your modules.
Instance fields should never be public as you give up the ability to limit the values that can be stored in the field, and if it is a mutable object, you open your object up for misuse (see here). It is important to note too that classes with public mutable fields are not thread-safe. It is also important to note that instance fields that are declared public static final but are mutable objects can also be modified and can be a security risk.
Basically, in public classes - always use accessor methods, not public fields. It allows you to protect your mutable objects from modification outside of the class (be it intentionally or unintentionally) and allows you to change implementation detail later without harming your clients.

struts2 best practice - where do I put helper methods? Static classes OK?

I have some repetitive code that is used by a few of my actions in Struts 2.
Needless to say I want to have this code only exist in one place, so I will collect it up into a method and put it ... where?
What is the best practice? Do I create a helper class for each type of helper method? One big helper method? One big static class? A few static classes?
I'm using MVC.
I've read other answers on stackoverflow and none seem to quite answer my question.
Many thanks for your help.
EDIT update with examples, as requested:
For instance:
I have a couple of lines of code that adds an arraylist to the session, which stores when a certain object has been 'rated' (for that session). Its called in a few actions across the application.
Also, I have a view component that is included on multiple JSP pages, and needs to be loaded with some data from the model. I would need to copy/paste the code into each action (obviously want to avoid this).
Hope that clarifies. Please let me know if it does not.
My general rule is that if the methods are computational, in other words if they just perform a function (like math), I will create a class with static methods and use it all over the place.
I have a utility package that I include in a lot of my projects as a jar with string manipulation and validation functions for instance because they rarely change.
String validation is a good example. I have a Validation class that I use a lot to check for null or empty strings and return a boolean. I just call it from my action classes like:
if(Validation.string(value)){
// do magic - huzzah
}
I try to group utility methods into classes especially if I use then all over the place. It tends to save me from re-typing, searching through classes for a good idea I had whenever, and provides a single instance of the code in case I need to update, modify, overload, or override.
For view components included in multiple JSP pages and objects saved to session, I've created a base action class and sub-action classes to avoid repetitive code.
public class BaseAction extends ActionSupport implements SessionAware {
protected Map session;
protected ResourceBundle rb;
// common getters for shared view components and common setters
...
}
--
public class SubAction extends BaseAction {
...

Categories