Java 7 - simple object to hold static values and shared methods - java

You have some object that just contains static data and static methods. Lets call it DataHoldingClass. You want this because the data is then easily accessible in code by writing object.VALUE and object.method(). It's all just for laziness and simplicity. And we all agree that this is important.
But some of the static method()s are common in your code, so you want to share them among DataHoldingClasses. The OOP approach is to define some abstract class BaseClass, put common methods there and then let the DataHoldingClass extends BaseClass.
But it's not possible, because each DataHoldingClass has different values and you cannot reach that values from abstract class. If you define public static final String VALUE in abstract, all subclasses would have only one shared VALUE and if you define separate VALUE in each DataHoldingClasses, you cannot create static String method() { return NAME; } in abstract class, because NAME isn't defined in abstract yet.
The only way to make it work is create values and methods non-static. Then the methods will be inherited from abstract class BaseClass and will work with DataHoldingClass specific values. But now you have to create new class instance every time you want access the data. Hmm, we've advanced from splash to mud.
But we can solve it, right? Just create some object to hold instances or make the DataHoldingClass a singleton. But this does not seem to be much better.
Another way might be to pass values to static methods by parameter, but calling some object method with the same object values as parameter seem weird and remember, we do this because of laziness, so we don't want to write object name two times.
Whats your way to storing such data objects? Currently, I'm using singletons, but I feel there must be some better way. Any idea?
Edit
example of usage:
Lets create such DataHoldingClass for each table in our database. Each table has own constants like COLUMN_ID = "_id" and TABLE_NAME = "evilTable" and every table have methods like insert() or update(). The methods are same for every table but can be overriden for some tables. The Constants are different. And I want define it as constants, because it is then easily accessible like Table.TABLE_NAME etc.

Related

Should I make 'count' as static in derived class, how to access it

I have a class, lets say CargoShip, which is a derived class of 'Starcraft', which implements the interface IStarcraft.
This is the function that should return the count (number of instances) of every ship:
public static void printInstanceNumberPerClass (ArrayList<ISpacecraft> fleet){}
There's a solution which I thought of and I'm sure it will work, declaring 'getCount()' in ISpacecraft, then overriding it in each SpaceCraft ship (I have 4 ships), and just iterating through everyone of them, polymorphism.
Fine, I got that. but because the function is static (yes, I know we dont need to create an object to use it) I thought it might tell me something different. What do I mean by that? Is it possible to create 'static count = 0' instead, in every ship, and somehow access it?
The question is then, how can I access that static field when I get an arraylist of ISpacecraft objects?
Polymorphism doesn't work with static methods, method resolution is very different. For virtual methods on an instance the code may be referring to the object with a variable typed as a superclass or interface, and calling a method is resolved at runtime without your application code needing to know the exact concrete type. For static methods you call it on a specific class and if the method isn't found then it's called on a superclass. Your code has to start with some subclass and resolution works up the hierarchy from there. For static methods you can't not know a low-level class to call the method on, the way you can with instance methods on objects. You can't have the level of abstraction you take for granted with objects.
The comment by markspace provides a much better alternative. Use static methods for stateless functions like java.lang.Math.

MVC in Java - Static controller?

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);

Should I use static methods for a menu class in a employee payroll console system?

My program is a small program that has an employee class and another Menu class that is used to manipulate an array of employees in the console program. Should the methods of the Menu class be declared static?
Some examples of the methods are addEmployee, updateEmployee and showEmployees. Every employee object is stored in an Employees array, which will be used by many other methods, such as to show all employees by passing in the array.
If the methods are declared static, then all I have to do is to pass in the array into the static methods is such as
Employee[] employees = new Employee[50];
Menu.showEmployees(Employees);
//other example methods that manipulate the array
Menu.methodX(Employees);
Menu.methodY(Employees);
Menu.methodZ(Employees);
However, if not static, I have in mind to have a constructor for the Menu class that would take in an employees array, after which the menu object can manipulate the array directly as its member:
Employee[] employees = new Employee[50];
Menu menu1 = new Menu(Employees);
menu1.showEmployees();
//other example methods that manipulate the array
menu1.methodX();
menu1.methodY();
menu1.methodZ();
I am aware that static methods should only be used as utility methods, but sometimes static methods can be used if convenient and if the system is not going to expand. Which is the better practice in this case?
A static method is useful for invoking functions on a class that don't require state. The most venerable example of this is Integer.parseInt; we don't require an instance of an Integer to parse a String into an int.
If you find yourself passing the state repeatedly to static functions, it's a wiser move to use an instance as opposed to all-static functions/variables. Specifically in this case, since your operations absolutely do depend on state, then having static functions makes little sense.
...some examples of the methods are addEmployee, updateEmployee and
showEmployees. Every employee object is stored in an Employees array,
which will be used by many other methods, such as to show all
employees by passing in the array.
Here is a general rule:
Avoid global state.
Global state makes your programs fragile, insecure, and difficult to maintain. Global state is the anti-thesis of encapsulation (which describes the principle in which data is hidden inside modular, decoupled units).
Global state is primarily made up of the static instance fields of a class. Observing the rule above, the answer to your question depends on how your data model is defined:
Employee data stored in static instance fields. In this case, your static employee methods will be able to directly access and modify the static employee data. You should not do this, however. It is bad design. Any code that has access to your class can access and alter employee data causing security problems, consistency problems, and maintenance problems.
Employee data stored in non-static instance fields. In this case, your static methods cannot directly access the non-static employee data. To solve this, you can pass a reference to the instance you wish to modify as an argument to the method. There will still be possible concurrency problems and these will need to be considered in a multithreaded design. This design has better encapsulation, should be less fragile, and more secure.
The best design would be to carefully construct a domain object model. Your goal should be to have each module encapsulate all of the state and the behavior that operates on that state. In this way, you should find that your goals can be accomplished without as many static methods. As a benefit, your program will contain modules that are decoupled, can evolve independently, are easier to maintain, and are more secure.
The fact that you have a Menu class suggests that your design may be suboptimal. A Menu has no obvious relationship to an Employee; it does not make intuituitive sense that a Menu -has an- Employee. Your classes are probably not as decoupled as they could be.
I think ,dear ,u should use static...bcz if u specify any method static ...u need not to create an object of the class to call the method .. U can directly call it by using (class_name.method_name) ...it saves memory that was being waste into creating an object. Both method are right.......but I have to tell another thing that in java Menu class is a static class. ...so u have to use static keyword to methods

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.

Getting data from a subclass without instantiation

I have an abstract superclass and various subclasses. Each subclass contains a value that I would like to use statically but it is not possible to create an abstract static method. I want to get a value from them dynamically without having to create instances. What do I do?
Another question would be: How would I loop through subclasses? Is it it even possible?
One attempt involved mapping class names (Subclass.class) to the value and trying to use the newInstance on them so I could use a method to get the value but this doesn't work.
Where am I going wrong in my approach?
Why not go about it the other way? Put the data someplace statically accessible and have the subclasses get it from there?
Of course, the feasibility of this depends on the nature of the data but when you find yourself hitting this sort of barrier it often helps to step back and reexamine your assumptions.
-- MarkusQ
You can reference static members/methods via reflection, but there is not automatic way to find all subclasses of a class.
Consider providing the subclasses/instance factories/metadata classes via some other mechanism, such as ServiceLoader services or some other plugin framework.
Maybe you are looking for enums?
public enum Planet
{
MERCURY (2.4397e6),
VENUS (6.0518e6),
EARTH (6.37814e6);
private final double radius;
Planet(double radius)
{
this.radius = radius;
}
public double radius()
{
return radius;
}
}
You don't have to create enum instances yourself. Enums can have values, e.g. radius() in the example. You can add behaviour to them so they can act like normal classes, by defining abstract methods on them, e.g.
public enum Planet
{
...
abstract double weightOnSurface(double weight);
...
}
You can loop through enums, like this:
for (Planet p : Planet.values())
{
System.out.println(p.radius());
}
So they seem to meet all your criteria.
Creating a second class for each of your subclasses which represents the type of that subclass might work.
For example, create a factory class for each subclass (a class that is responsible for creating instances of that subclass). There only needs to be one instance of each factory class.
Each factory class can then be responsible for knowing the subclass-specific data you describe. You then just need to loop over a fixed set of factory classes.
If you have a fixed set of subclasses then you can put the data in the superclass. If you subclasses can be added, then there is no way to list them all. You might get subclasses let the superclass know of their existence from the static initialiser (or use an agent!).
Generally superclasses should not be aware of their subclasses. However you might want to think (or better refactor) your superclass into a supertype and some other class responsible for your subclasses.
You will need to to scan package(s) and clasess to find ones that extend your superclass - unfortunately, this cannot be done with the Reflection API, but must be done through URLs (file system classes, jar files etc). Annotation use is probably better in this case, and lots of open source products use this method (Hibernate etc).
Then you can have a static method in each (either consistent naming or annotated) which you should be able to invoke with as method.invoke(MyObject.class, arguments)
The other option is to put a registry map in the abstract class - if you need to mandate it, the abstract constructor takes the static value (or just stores the subclass if calculations are needed). If you're controlling all subclasses, just make sure you have a static block in each one to add it to the registry.
Mapping subclasses... you can do it via reflection (but it won't be fun).
newInstance() (likely) won't work unless:
the class is public
the constructor is public
the constructor takes no arguments
The last one is mandatory, the other two depend on what package you are doing things from (I think, been a while since I cared). Using the Constructor class is better.
Can you give a short code example of what it is you are thinking of doing? Based on that I (and others) might be able to give you better answers. If you do need to do the mapping subclass thing I can dig up some code that does it...

Categories