I'm new to Java
I want to write util classes for my own purposes such as FileUtil,DBUtil,...
But some people write all methods in util classes as static methods
class FileUtil{
public static File openFile(String path){
...
}
public static File readFile(String path){
...
}
...
}
and some write util class as singleton classes and write methods as public
class FileUtil{
private FileUtil(){}
public FileUtil getInstance(){
...
}
public File openFile(String path){
...
}
public File readFile(String path){
...
}
...
}
I want to know which is better way of doing it when it comes to memory allocation
Thanks in advance
Never write a singleton. If you really want static fields (don't) then write static. For (single implementation) utility methods there's no point in forcing an extra object on the client.
Look at the mess created by Runtime vs System despite being essentially the same thing.
Traditionally utility classes are written as classes with static methods. A private constructor that throws an exception can be added to prevent the default constructor being added, but adds extra mess to the code (though reduces documentation). Also adding an unnecessary final is common.
Single-element enums were popular for singletons (don't write singletons). Using the same arguments utility classes should be no-element enums, though that isn't popular for no obvious reason. Both single and no element enums add nonsense methods to the class.
If you really want concise code, use interfaces. You avoid having to write public every time and constants can elide the public static. This is apparently not very popular because it is possible for clients to ruin their own code by implementing the interface. See Swing.
Utilities:
Utility classes are classes that do not need any instance. They provide methods that help you to do things.
Singletons:
Singletons are instances that require to have one and only one instance. The reason for having singletons are various, maybe you need a single coordinator that should not be interferred...
FileUtil:
well the name points it out already, this class provides methods for a simplified file access...
FileManager:
this object is responsible to keep track of the integrity of the file System. Noone else is allowed to create/delete files but only the FileManger, hence FileManager would be a singleton. (Your Questions doesn't ask for a File Manager, but to make a difference to FileUtils i think it would be helpful)
Memory Usage / Clean Code
why this answer: you think you might optimize for memory but clean code points out that you should not optimize
Summary:
don't use a Singleton if you really don't have to do it. Use a plain utility class (it's by the way the thing you wanted to do).
Related
I am not very familiar with java. I created a jersey web server. There is different functions such as startRodio(), stopRadio(), setRadioIp()... I created one RequestHandler class to handle the http requests and one other Radio class that implement them. All the properties and methods of the Radio class are static. it looks like
Radio
class Radio{
public static boolean radionOn;
public static String radioIpadress;
public static boolean startRadio(){
radioOn = true;
// some other operation
}
...
RequestHandler
classe RequestHandler {
#path(/startRodio)
.....
if (!Rodio.radioOn)
Radio.startRadio();
Is it a good architecture for my programm? is it a good practice to make all the properties and method static in this way?
I would say, that making properties static in default as you have made above is not good practice at all.
If you have only one instance of such object as Radio is, then use singleton pattern and private properties with proper getters and setters. This is generally best approach, because you separate public interface from private implementation and change in the implementation (e.g. renaming variable) would cause problems in other parts of application and need of refactoring.
Static variables should serve just for some common properties for defined type/class. You can for example count existing instances of class in static variable.
Better avoid using static variables. This is not a good practice. Static variables have global scopes which leaves you testing so hard. Also anything can be able to modify the static variables. more over, using static is not thread safety. Also you don't have control over the static variable i terms of their creation and destruction. SO its not advisable to use statics.
Just don't use static variables. It directly couples several of
your classes.
You can use singletons in place of static if you're sure that you
need only one object.
Simply spoken: don't use static.
static is an abnormality in good OO design. It leads to direct coupling between your classes. It makes it hard to later replace "implementation"; and it makes it hard to write reasonable unit tests.
Meaning: by default, you do not use static. There might be situations when it is fine to use; but the example code you are showing does not at all look like you should be using static.
Instead, you should be defining an interface that denotes the functionality of your Radio; allowing for different implementations behind that interfaces.
It depends on what are you looking for.
Lets say you are creating 4 objects of Radio.
radioOne....,radioFour...
Now if you want all Radios to start at same time, you should go for static variable because static properties are characteristics of all objects of a class. They are not exclusive to any particular object and in practice they should be assessed using class like :
Radio.radionOn=true;
and not radioOne.radioOn=true;
So, I would suggest you to make only those properties static which will be common to all objects. If all the properties will fall under that ambit,
then it would mean you want only one object for the class because all your objects would behave the same .So better to have one object . In that case go for singleton pattern for object creation.
package com.companyxyz.api.person;
public class Man {
public var1;
public var2;
...
private static void createAuth() {
...
}
// public methods go here
...
}
I want to create a new public method that accesses the private method, createAuth, but in a different file. Is there a way to create this new method without writing it or accessing it via an extended class?
Thank you.
No. You can't access a private method from an other class. Because it's ... private.
A private method is not accessible to any external classes, (this includes subclasses).
A workaround might be to use reflection, however this isn't a generally recommended approach for a number of reasons (brittleness, performance problems, breaking encapsulation, etc).
There is no clean and recommended general way to do this in Java. private is private.
But you did not state why you want to do this and what the specific constraints are. Therefore I throw two options into the mix:
You can decompile the class file for Man, set everything you want to protected or public and recompile (and repackage into a jar file). Perhaps there is no need to decompile, perhaps some bit manipulation on the class file can do the job, too.
You can write a custom ClassLoader with a bytecode manipulation library to modify the bytecode of the class at runtime. Then you can also add additional access paths to the stuff you want. Note however that this is extremely advanced/complicated stuff.
Both ways are nothing you can use / should use for normal applications or the usual framework.
I'm 14 and have been learning java for about 4/5 months. I'm coding a game now called super mario winshine and i wanted to know if it is good practice to have a class that is mostly static variables.
The class is the one that holds all the information for the game's level/world. Since I only need one version of this class, and lots of other classes will be using it, I choose to make all the variables static. Is this good practice?
I have considered the fact that i could keep the variables "non-static" and just clone the main object i use for that class, but I thought i would rather sacrifice "O-O" for memory in this case.
As soon as you want to have two or more worlds this will fail. Say, when your first release is a runaway success and you want to add the "parallel universe" expansion set.
In my experience, 90% of the time when marketing says "oh, don't worry, there will only be one Application/Window/Database/User" they are wrong.
ADDED
I would also avoid using a true Singleton pattern with World.getInstance() etc. Those are for the rare cases where it really is an essential requirement that there only be one of something. In your case, you are using it as a convenience, not a requirement.
There is no perfect fix, YMMV, but I'd consider a single static method, something like
World World.getWorld(String name)
and then you call real (non-static) methods on the World that is returned. For V1 of your program, allow null to mean "the default world".
Some might put that method into a class named WorldManager, or, perhaps showing my age, a more clever name like Amber. :-)
It all depends upon what your methods and classes are. There is no problem in defining utility methods as static methods in a class. There is no need to make it a singleton as others are suggesting. Look at the Math class from java.lang package. It has lot of utility methods but it isn't a singleton.
Also check out static imports functionality. Using this you doesn't need to qualify method calls with the class name.
Well, what you are doing is definitely an option. Or you could use a singleton pattern:
public class World {
private static World instance = new World();
private World() {
}
public static World getInstance() {
return instance;
}
}
Now just use World.getInstance() everywhere to have a unique object of this type per application.
I would say it's definitely not a good practice.
I've not seen your code, but having several static variables in a class that other classes access freely seems to indicate that you're not really using object orientation/classes but more just writing procedural code in Java. Classes should generally encapsulate/hide all their variables - static or not - from access from other classes so that other classes don't depend on how the class is implemented.
The static part also causes problems with making threads work (global variables are hard to lock in a good way so that nothing deadlocks) and with unit testing (mocking is all but impossible)
I also agree with the other posters, if you need "global variables", at least make them singletons. That allows you to change strategy easier later and does not lock you to one world.
Edit: I'm definitely not advocating singletons as a good pattern here if someone read it like that, but it does solve some problems with static variables, esp. regarding testing/mocking compared to just statics so I'd say it's a ever so slightly lighter shade of gray :) It is also a pattern that is easier to gradually replace with better patterns by for example using a IoC container.
I think it is fine as long as you don't need anything more sophisticated, in other words, static fields are OK as long as different objects (including subclasses if there will be any) do not need different values.
You code by yourself, refactoring is easy with modern tools, me says don't fix it until it is broken, and focus on the algorithmic aspects of your project.
Perhaps you may think to encapsulate all those static fields within a different static class, as it is a good principle to "keep what changes seperate from what does not". Chances are one day you will want to initiate that static class with different values, for example want to read the initial values from an XML file and/or registry, add behaviour, etc. so instead of a static class you will implement it with a Singleton pattern.
But clearly that is not the concern of today. Till then, enjoy!
You may wish to look into implementing this class as a singleton, while there is nothing particularly wrong with your approach it may lead to some inflexibility further down the road.
Also you should take in to consideration the purpose of static members which is to be a member of the class and 'act' on/with the class not an instance of it. For example the static method in a singleton returns either a new instance of the class if one doesn't already exist or returns the instance, and because the method is static you do not instantiate a new one. This is probably worth a read because it can be somewhat confusing when determining the appropriate use of static members
I'm not sure what you are really talking about from your short description, so I'll try this:
public class Level {
static List<Mushroom> mushrooms;
static List<Coin> coins;
...
}
Is that you were describing?
You asked if this is "good practice" and I can tell you that this looks very odd, so, no, it's not.
You gain absolutely nothing by doing this. You make it impossible to have more than one Level, which brings no advantage, but it could cause trouble in the future.
I didn't understand your last paragraph where you say you made most things static to save memory. You would usually create one Level and it would be passed around (without cloning) to the various classes/methods that read from it or modify it.
This is a very simple example where accessing directly could be dangerous
class Something{
public static final int MAX=123;
private int prop;
final void riskyMethod()
{
this.prop=800; //this is wrong
}
final void safeSetProp(int x)
{
if(x<MAX)
{
prop=x;
}
}
}
I know it could be done encapsulating "prop" in another class,
and defining it there as private, but that's a lot of useless code overhead!
Is there a way to force the use of methods to access same class properties?
a keyword? any trick?
I confess I have done things like this to avoid accidental access by the same class
private int IKWIDprop; //IKWID = I Know What I am Doing
I am sure you could know a better approach =)
Regards!
This is your class, come on! You always know what you are doing. If you don't, write tests. I understand you want to force the usage of getter instead of raw field in case at some point in the future the getter will be equipped with some extra logic. But because this is your class, you are fully responsible and capable of maintaining this code.
Bizzare Hungarian notation only clutters the code. Unit test your class to make sure nobody damages your work (including yourself). Nobody reads documentation and Javadocs, not to mention nobody will understand TIASCWIAFDPUGIage (thisIsASpecialCaseWhenIAccessFieldDirectlyPleaseUseGetterInstead_Age), including you after a while.
BTW if you force the usage of encapsulating getter inside your class, how does the getter itself access the field? So go back to earth and be reasonable. Having a strong suite of unit tests is much more helpful, reliable and provides better documentation.
UPDATE: Actually, there is a (sort of) clean way. You can use AspectJ, with few clever pointcuts, will catch raw private field access excluding some special cases. It can be executed at compile time to fail the build or at runtime. The pointcut would say something like: "each private field access from a method that is not annotated with #ThisIsASetter should generate compile time error. Maybe somebody more fluent with AspectJ can write this?
no, there is no such keyword. I advice you to write good documentaton, comments and to promis to beat those, who will use direct assigning of the value
One "trick" that comes to mind is to put any fields like this into an abstract class which provides the necessary getter/setter methods. Then, derive your "real" class from the abstract class, and now any writing to those private fields need to be done via the "safe" setter methods.
Of course, this is a ton of extra overhead, and it still doesn't prevent you from writing incorrect values in the abstract parent class anyway.
The point of private is to ensure that internal class invariants aren't disturbed incorrectly by code that consumes the class. As you note, it does not prevent the class itself from messing with them, because presumably the class knows what it's doing! If you want to ensure that certain invariants are correct prior to relying on them, you can always use assert statements. If they fire, you can look through your code and see what you've done that's caused the problem.
In general, your best bet is to just be careful with your code, rather than trying any "tricks".
I am wondering about programming decision - which I think is matter of style.
I need to have single instance of class which has only methods and no attributes.
To obtain that in java I have two options:
create an abstract class with static methods within, thus it will not be possible to create any instance of the class and that is fine,
use a singleton pattern with public methods.
I tend to go for second approach although met with 1. Which and why is better of those, or there is third option.
Would it make sense for that singleton to implement an interface, allowing you to mock out those methods for test purposes?
I know it goes against testing dogma these days, but in certain situations I think a static method is fine. If it's the kind of behaviour which you're never going to want to fake for test purposes, and which is never going to be polymorphic with other implementations, I don't see much point in making a singleton. (Singletons are also generally the enemy of testability, although if you only directly refer to them in the injection part of your code, they can implement appropriate interfaces so their singletoneity never becomes a problem.)
It's worth mentioning that C# has "static classes" for this kind of situation - not only do they prohibit other code from deriving from or instantiating the class, but you can't even use it as a parameter. Basically it signals the intent very clearly.
I would definitely suggest at least having a private constructor to prevent instantiation by the outside world.
My personal view is that the class should contain a private constructor and NOT be abstract. Abstract suggest to a reader that there is a concrete version of the class somewhere, and they may waste time searching for it. I would also make sure you comment your code effectively.
public class myClass {
/** This class should never be instantiated. */
private myClass() {
}
public static void myMethod() {
}
...
//etc
...
}
For option #1, it may not even be that important to restrict instantiation of your static utility class. Since all it has is static methods and no state, there is no point - but neither harm - instantiating it. Similarly, static methods can't be overridden so it does not make sense - nor difference - if it is subclassed.
If it had any state, though - or if there is a chance that it will get stateful one day - it may be better to implement it as a normal class. Still I would prefer not to use it as a Singleton, rather to pass its sole instance around via dependency injection. This makes unit testing so much easier in the long run.
If it holds a state I would use the singleton pattern with private constructors so you can only instantiate from within the class. If it does not hold a state, like the apache commons utility classes, I would use the static methods.
I've never seen the problem with static methods. You can think of static methods as somehow breaking OO, but they make perfect sense if you think of static as a marker that something is stateless. You find this in the java apis in places like java.Math. If you're worried about subclassing you can always make it final.
There is a danger in that a class like that can end up as a "utility method garbage can", but as long as the functionality doesn't diverge too much then there's nothing wrong with it.
It's also clearer, as there's no need to manage an object lifecycle like you would with a singleton (and since there's no state, what's the point of that anyway?).
For a single instance, I suggest you have an enum, with one instance.
However, for a class with no attributes, you don't have to have an instance. You can use a utility class. You can use an enum, with no instances and only static methods. Note: this cannot be easily mocked out.
You can still implement an interface if you ever need to mock out the implementation in testing.