The following code illustrates the situation:
class Human {
private String heart = "default heart";
public void control(Human h) {
h.heart = "$%^&*##!#^";
}
public String getHeart() {
return heart;
}
}
public class HumanTest {
public static void main(String[] args) {
Human deb = new Human();
Human kate = new Human();
System.out.println(deb.getHeart());
kate.control(deb);
System.out.println(deb.getHeart());
}
}
Here heart [private variable] of deb got modified unfortunately. :)
Java allows the code to run without any error.But is it justified to give a object the privilege to access private member of other object even if the code is in the same class ?
Shouldn't Java disallow this?
As I know, private means restricting access beyond the class source code. But the same concept is applied in the source code above. and the result is disastrous since a person's heart can't be modified by any random person .
If the result is disastrous, you shouldn't code the class so that it allows it. The "bug" is not caused by code external to the class, but by code of the class itself. So it's simply a bug in your code.
If Java did not allow it, you could only compare objects of the same class by their public attributes, for example, which would either break encapsulation (by exposing private stuff), and/or be very slow (by forcing to make defensive copies of the private attributes to make them available to other objects.
Some languages have encapsulation at the object level, others (Java, C++) at the class level. It sounds like you're used to (or have just read about) encapsulation at the object level. Frankly, I find the class level much more natural, but perhaps that's just because C++ provided my introduction to programming with classes. Class-level encapsulation makes some idioms (factory methods, copy constructors, comparison operators) much easier to write. With object-level encapsulation, you end up exposing more than you really want to just to be able to implement these features.
In any case, neither way is "correct" -- they're just different.
Look into defensive copy to avoid this situation. It is because java objects operate more like references. The 'pointer' doesn't change, but once you know it you can change the value it contains.
http://www.informit.com/articles/article.aspx?p=31551&seqNum=2
This isn't breaking object orientation - it's about encapsulation of elements internal to a class.
It may seem silly that you can do this with this example but it's actually not a bad thing at all as far as I see it. The point of encapsulating elements of a class is so that other classes can't modify them - they can only see the public interface of class Human for instance to make changes. This means more than one person can work on the same project, writing different classes (or you can work on the same project at different times writing different classes) and they don't need to know the inner workings of the code.
However, the only place (bar reflection) you can access a private field directly in Human is from Human. When you're writing the Human class, if you choose to make modifications to private fields of other Human objects, that's up to you - but it's all contained within that one class, which is your design. If you do this in a way that's not appropriate, then it's a flaw in your design and not with Java - there's some cases where it makes perfect sense to do this!
Well, the way I see it and this is just my interpretation of the private keyword, a private is private to the class and can be accessed inside the class. It is not restricted to instances of the class. Therefore you can't do kate.heart="xpto" in the "humantest" class because that would try to breach it's privacy, but using kate's code to alter deb's heart is allowed because it is being handled inside the class.
Java language strictly following the Object oriented concept. Here also that's correct..ritght? Using the object of your class you are modifying your class's variables. But its upto the programmer who can have control over his objects.
Human's heart is private inside Human's class. But using the control method you are giving access to it from outside. That's why it gets modified..What's the problem in that.?
Related
I would like to know if it safe and a good practice to keep common code in a separate class and make method static.
I have a class Car, that is constructed based on inputs from other classes. I need to apply some post construct processing after the Car object is created. Example below.
Class Travel uses Car and calls postConstructProcessing method.
CarProcessor is simillary used in other classes whenever car object is creates.
My question is should I make method process Static in CarProcessor.
Class car{
Type type;
Int model
Car(Type t, int m){
...
...
}
;
....
...}
Below class of code uses Car and calls postConstructProcessing method
public class Travel {
public void go(){
....
....
Car c = new Car(t,m);
new CarProcessor().process(c);
}
}
class CarProcessor{
public Car process(Car c){
If(c.type.value.equals("ABC"){
c.type.version=1.1;
}
if(c.model=5.7){
c.price=50k
}
}
}
My question is , is it safe and a good practice to make method process in CarProcessor static.
In general it's not great.
The most obvious problem is, if you are testing the go method, how do you replace/mock out CarProcessor::process?
The real problem is organizational though. When you are coding next time and looking for the functionality you'd expect to see in "Car" or "go", you type "car." or "go." into your IDE and hit ctrl-space, you'd expect to see all the interesting methods shown to you. How do you know to create a CarProcessor to proceed?
Some things are difficult to implement in OO though--in particular utilities. Look at the entire Math package in the java library. It's full of static methods that you just call. An oo fanatic would say these all belong in the Number class (maybe something like "Number.math.sqrt()?", but java didn't take that route--in fact they don't even have a good common number class (We have one, it's not good)--
But even when we have real classes like String, we lean towards "StringUtil" and such. This has led to a HUGE number of conflicting "Util" implementations of String. In this case part of the problem is that String is immutable and we can't really back-fill it with methods (probably a good thing). but in general, OO just isn't great for general-purpose utility methods.
Functions (which is what you are proposing) are not awesome, but are heavily used. If you have the ability to modify your business classes then that's almost always a better fit for this type of code.
Just to clarify: A Function is different from a Method--methods work on members (class variables), functions are stand-alone (Might as well be static).
Functions are a very old approach at organization. OO is a somewhat newer approach invented for when the sheer number of functions become too difficult to manage (conceptually).
I am new to OOP and I have some doubts regarding encapsulation.
What is mean by difference between "partial" and "weak" encapsulation? An example in java will help me.
Does encapsulation means only place data in capsule like a class, or does an access modifier have to be there?
I read that encapsulation means to hide and club together data.
In this example:
class A{
public int a;
public void foo(){}
}
Is above code is example of encapsulation? If yes, then there is nothing hidden from outer world as a and foo are public. Must a and foo be private for this example to be considered encapsulation?
Here is a good explanation https://mail.mozilla.org/pipermail/es-discuss/2010-December/012334.html
Basically if you were implementing a java library or API you would aim for strong encapsulation, so that users couldn't access things they aren't supposed to.
Strong encapsulation means that no one can access secret internal variables because you have a proper inheritance heirachy and all that stuff is hidden.
Your example is very weak encapsulation because the variable a is public. If your class was an API and a was actually credit_card_details you would be in big trouble.
For starters you would set those variables as private and use getters and setters to access them.
Overall though, you need something abstracted in order to encapsulate it. The only other thing I have heard encapsulation refer to from an OOP perspective is simply bundling real world objects into classes
Object orientation is about messages. If you can only ask for setting or getting a value inside an object, then the values are encapsulated. The only way to access them is via the predefined protocol, which is the setter or the getter or whatever other methods.
If you have a public field, it looks like there's no encapsulation, but you still don't own the variable, think of it as a default set or get.
I am reading a book about Java and it says that you can declare the whole class as final. I cannot think of anything where I'd use this.
I am just new to programming and I am wondering if programmers actually use this on their programs. If they do, when do they use it so I can understand it better and know when to use it.
If Java is object oriented, and you declare a class final, doesn't it stop the idea of class having the characteristics of objects?
First of all, I recommend this article: Java: When to create a final class
If they do, when do they use it so I can understand it better and know when to use it.
A final class is simply a class that can't be extended.
(It does not mean that all references to objects of the class would act as if they were declared as final.)
When it's useful to declare a class as final is covered in the answers of this question:
Good reasons to prohibit inheritance in Java?
If Java is object oriented, and you declare a class final, doesn't it stop the idea of class having the characteristics of objects?
In some sense yes.
By marking a class as final you disable a powerful and flexible feature of the language for that part of the code. Some classes however, should not (and in certain cases can not) be designed to take subclassing into account in a good way. In these cases it makes sense to mark the class as final, even though it limits OOP. (Remember however that a final class can still extend another non-final class.)
In Java, items with the final modifier cannot be changed!
This includes final classes, final variables, and final methods:
A final class cannot be extended by any other class
A final variable cannot be reassigned another value
A final method cannot be overridden
One scenario where final is important, when you want to prevent inheritance of a class, for security reasons. This allows you to make sure that code you are running cannot be overridden by someone.
Another scenario is for optimization: I seem to remember that the Java compiler inlines some function calls from final classes. So, if you call a.x() and a is declared final, we know at compile-time what the code will be and can inline into the calling function. I have no idea whether this is actually done, but with final it is a possibility.
The best example is
public final class String
which is an immutable class and cannot be extended.
Of course, there is more than just making the class final to be immutable.
If you imagine the class hierarchy as a tree (as it is in Java), abstract classes can only be branches and final classes are those that can only be leafs. Classes that fall into neither of those categories can be both branches and leafs.
There's no violation of OO principles here, final is simply providing a nice symmetry.
In practice you want to use final if you want your objects to be immutable or if you're writing an API, to signal to the users of the API that the class is just not intended for extension.
Relevant reading: The Open-Closed Principle by Bob Martin.
Key quote:
Software Entities (Classes, Modules,
Functions, etc.) should be open for
Extension, but closed for
Modification.
The final keyword is the means to enforce this in Java, whether it's used on methods or on classes.
The keyword final itself means something is final and is not supposed to be modified in any way. If a class if marked final then it can not be extended or sub-classed. But the question is why do we mark a class final? IMO there are various reasons:
Standardization: Some classes perform standard functions and they are not meant to be modified e.g. classes performing various functions related to string manipulations or mathematical functions etc.
Security reasons: Sometimes we write classes which perform various authentication and password related functions and we do not want them to be altered by anyone else.
I have heard that marking class final improves efficiency but frankly I could not find this argument to carry much weight.
If Java is object oriented, and you declare a class final, doesn't it
stop the idea of class having the characteristics of objects?
Perhaps yes, but sometimes that is the intended purpose. Sometimes we do that to achieve bigger benefits of security etc. by sacrificing the ability of this class to be extended. But a final class can still extend one class if it needs to.
On a side note we should prefer composition over inheritance and final keyword actually helps in enforcing this principle.
final class can avoid breaking the public API when you add new methods
Suppose that on version 1 of your Base class you do:
public class Base {}
and a client does:
class Derived extends Base {
public int method() { return 1; }
}
Then if in version 2 you want to add a method method to Base:
class Base {
public String method() { return null; }
}
it would break the client code.
If we had used final class Base instead, the client wouldn't have been able to inherit, and the method addition wouldn't break the API.
A final class is a class that can't be extended. Also methods could be declared as final to indicate that cannot be overridden by subclasses.
Preventing the class from being subclassed could be particularly useful if you write APIs or libraries and want to avoid being extended to alter base behaviour.
In java final keyword uses for below occasions.
Final Variables
Final Methods
Final Classes
In java final variables can't reassign, final classes can't extends and final methods can't override.
Be careful when you make a class "final". Because if you want to write an unit test for a final class, you cannot subclass this final class in order to use the dependency-breaking technique "Subclass and Override Method" described in Michael C. Feathers' book "Working Effectively with Legacy Code". In this book, Feathers said, "Seriously, it is easy to believe that sealed and final are a wrong-headed mistake, that they should never have been added to programming languages. But the real fault lies with us. When we depend directly on libraries that are out of our control, we are just asking for trouble."
If the class is marked final, it means that the class' structure can't be modified by anything external. Where this is the most visible is when you're doing traditional polymorphic inheritance, basically class B extends A just won't work. It's basically a way to protect some parts of your code (to extent).
To clarify, marking class final doesn't mark its fields as final and as such doesn't protect the object properties but the actual class structure instead.
TO ADDRESS THE FINAL CLASS PROBLEM:
There are two ways to make a class final. The first is to use the keyword final in the class declaration:
public final class SomeClass {
// . . . Class contents
}
The second way to make a class final is to declare all of its constructors as private:
public class SomeClass {
public final static SOME_INSTANCE = new SomeClass(5);
private SomeClass(final int value) {
}
Marking it final saves you the trouble if finding out that it is actual a final, to demonstrate look at this Test class. looks public at first glance.
public class Test{
private Test(Class beanClass, Class stopClass, int flags)
throws Exception{
// . . . snip . . .
}
}
Unfortunately, since the only constructor of the class is private, it is impossible to extend this class. In the case of the Test class, there is no reason that the class should be final. The Test class is a good example of how implicit final classes can cause problems.
So you should mark it final when you implicitly make a class final by making it's constructor private.
One advantage of keeping a class as final :-
String class is kept final so that no one can override its methods and change the functionality. e.g no one can change functionality of length() method. It will always return length of a string.
Developer of this class wanted no one to change functionality of this class, so he kept it as final.
The other answers have focused on what final class tells the compiler: do not allow another class to declare it extends this class, and why that is desirable.
But the compiler is not the only reader of the phrase final class. Every programmer who reads the source code also reads that. It can aid rapid program comprehension.
In general, if a programmer sees Thing thing = that.someMethod(...); and the programmer wants to understand the subsequent behaviour of the object accessed through the thing object-reference, the programmer must consider the Thing class hierarchy: potentially many types, scattered over many packages. But if the programmer knows, or reads, final class Thing, they instantly know that they do not need to search for and study so many Java files, because there are no derived classes: they need study only Thing.java and, perhaps, it's base classes.
Yes, sometimes you may want this though, either for security or speed reasons. It's done also in C++. It may not be that applicable for programs, but moreso for frameworks.
http://www.glenmccl.com/perfj_025.htm
think of FINAL as the "End of the line" - that guy cannot produce offspring anymore. So when you see it this way, there are ton of real world scenarios that you will come across that requires you to flag an 'end of line' marker to the class. It is Domain Driven Design - if your domain demands that a given ENTITY (class) cannot create sub-classes, then mark it as FINAL.
I should note that there is nothing stopping you from inheriting a "should be tagged as final" class. But that is generally classified as "abuse of inheritance", and done because most often you would like to inherit some function from the base class in your class.
The best approach is to look at the domain and let it dictate your design decisions.
As above told, if you want no one can change the functionality of the method then you can declare it as final.
Example: Application server file path for download/upload, splitting string based on offset, such methods you can declare it Final so that these method functions will not be altered. And if you want such final methods in a separate class, then define that class as Final class. So Final class will have all final methods, where as Final method can be declared and defined in non-final class.
Let's say you have an Employee class that has a method greet. When the greet method is called it simply prints Hello everyone!. So that is the expected behavior of greet method
public class Employee {
void greet() {
System.out.println("Hello everyone!");
}
}
Now, let GrumpyEmployee subclass Employee and override greet method as shown below.
public class GrumpyEmployee extends Employee {
#Override
void greet() {
System.out.println("Get lost!");
}
}
Now in the below code have a look at the sayHello method. It takes Employee instance as a parameter and calls the greet method hoping that it would say Hello everyone! But what we get is Get lost!. This change in behavior is because of Employee grumpyEmployee = new GrumpyEmployee();
public class TestFinal {
static Employee grumpyEmployee = new GrumpyEmployee();
public static void main(String[] args) {
TestFinal testFinal = new TestFinal();
testFinal.sayHello(grumpyEmployee);
}
private void sayHello(Employee employee) {
employee.greet(); //Here you would expect a warm greeting, but what you get is "Get lost!"
}
}
This situation can be avoided if the Employee class was made final. Just imagine the amount of chaos a cheeky programmer could cause if String Class was not declared as final.
Final class cannot be extended further. If we do not need to make a class inheritable in java,we can use this approach.
If we just need to make particular methods in a class not to be overridden, we just can put final keyword in front of them. There the class is still inheritable.
Final classes cannot be extended. So if you want a class to behave a certain way and don't someone to override the methods (with possibly less efficient and more malicious code), you can declare the whole class as final or specific methods which you don't want to be changed.
Since declaring a class does not prevent a class from being instantiated, it does not mean it will stop the class from having the characteristics of an object. It's just that you will have to stick to the methods just the way they are declared in the class.
Android Looper class is a good practical example of this.
http://developer.android.com/reference/android/os/Looper.html
The Looper class provides certain functionality which is NOT intended to be overridden by any other class. Hence, no sub-class here.
I know only one actual use case: generated classes
Among the use cases of generated classes, I know one: dependency inject e.g. https://github.com/google/dagger
Object Orientation is not about inheritance, it is about encapsulation. And inheritance breaks encapsulation.
Declaring a class final makes perfect sense in a lot of cases. Any object representing a “value” like a color or an amount of money could be final. They stand on their own.
If you are writing libraries, make your classes final unless you explicitly indent them to be derived. Otherwise, people may derive your classes and override methods, breaking your assumptions / invariants. This may have security implications as well.
Joshua Bloch in “Effective Java” recommends designing explicitly for inheritance or prohibiting it and he notes that designing for inheritance is not that easy.
I am writing a game and I have a class for the input which contains booleans for all the different keys. I create an instance of this class in the main game class. Is it ok for the booleans to be public, or should I access them with accessors?
Instead of having a boolean for each key, it would be more readable and easier to code if you had a private Map<String, Boolean> keyStates, with all keys initialized to false. Then your accessors might be:
public void setPressed(String keyName) {
keyStates.put(keyName, true);
}
public void setReleased(String keyName) {
keyStates.put(keyName, false);
}
public boolean isPressed(String keyName) {
return keyStates.get(keyName);
}
The general reason for having accessor methods rather than public variables is that it allows the class to change its implementation without requiring changes in the classes that interact with its members. For example, with the above, you can now add code to count or log key presses, or change the underlying type of Map used, without exposing any of this to the outside.
This is not personal preference. Encapsulation and Interfaces are integral parts of OO Software Engineering, and are the primary design reasons that the Internet is possible from a technical POV.
Generally I would recommend using getters and setters as it is cleaner, more organized, and more readable. This will also help if you have a lot of different programmers looking at your code. My outlook is to always make your variables private unless you need to expose them for a specific reason. If performance is really an issue in your game then making your variables public will help a little by reducing function calls.
It's mainly a personal taste thing - I'm sure you'll find people arguing on both sides, and I'd say it's not black or white but depends on how "big" the class is.
The rationale for using getters and setters is so that you abstract out the actual representation as a field, in order to give you the freedom to start presenting this as e.g. a derived value without changing your interface. So really it comes down to how valuable the interface to this class is to you.
If it's part of your first-class public interface, then definitely use getters and setters. At the other extreme, if it's a simple data holder like a tuple that's used solely within a single class (e.g. to map database rows before transformation into another class), then I wouldn't hesitate to use fields; there's no real value to the interface as it's only being used internally.
So how many classes/packages would use this class? If it's a private, "local" class then I don't think there's anything wrong with just using the fields, and updating your callers if this ever needs to change.
Accessing fields is much easier to justify if they're final too, which is often the case with this sort of object.
It's not bad, but usually you'll want to encapsulate the state of an object.
Standard practice is to make member variables either protected or private with getters/setters that follow java bean convention. This tends to be somewhat verbose, but there is a very nice library (www.projectlombok.org) out there that generates the getters/setters/constructors/toString/hashCode/equals methods for you.
It is always a good java programming practice to declare the class variables as private and access them with public getter and setter methods unless its really needed to declare them as public .
If you are using an IDE , then its just a click away to generate getters and setters for class variables/member variables .
And now that you have been told over and over to use getter and setters, and because you are in Java (where IDEs help you make getters/setters trivially, and everyone clearly uses them), read over this thread to help add some balance to your usage of them:
Getters and Setters are bad OO design?
Lets assume that a rule (or rule of thumb, anyway), has been imposed in my coding environment that any method on a class that doesn't use, modify, or otherwise need any instance variables to do its work, be made static. Is there any inherent compile time, runtime, or any other disadvantage to doing this?
(edited for further clarifications)
I know the question was somewhat open ended and vague so I apologize for that. My intent in asking was in the context of mostly "helper" methods. Utility classes (with private CTORs so they can't be instantiated) as holders for static methods we already do. My question here was more in line of these little methods that HELP OUT the main class API.
I might have 4 or 5 main API/instance methods on a class that do the real work, but in the course of doing so they share some common functionality that might only be working on the input parameters to the API method, and not internal state. THESE are the code sections I typically pull out into their own helper methods, and if they don't need to access the class' state, make them static.
My question was thus, is this inherently a bad idea, and if so, why? (Or why not?)
In my opinion, there are four reasons to avoid static methods in Java. This is not to say that static methods are never applicable, only to say that they should generally be avoided.
As others have pointed out, static methods cannot be mocked out in a unit test. If a class is depending on, say, DatabaseUtils.createConnection(), then that dependent class, and any classes that depend on it, will be almost impossible to test without actually having a database or some sort of "testing" flag in DatabaseUtils. In the latter case, it sounds like you actually have two implementations of a DatabaseConnectionProvider interface -- see the next point.
If you have a static method, its behavior applies to all classes, everywhere. The only way to alter its behavior conditionally is to pass in a flag as a parameter to the method or set a static flag somewhere. The problem with the first approach is that it changes the signature for every caller, and quickly becomes cumbersome as more and more flags are added. The problem with the second approach is that you end up with code like this all over the place:
boolean oldFlag = MyUtils.getFlag();
MyUtils.someMethod();
MyUtils.setFlag( oldFlag );
One example of a common library that has run into this problem is Apache Commons Lang: see StringUtilsBean and so forth.
Objects are loaded once per ClassLoader, which means that you could actually have multiple copies of your static methods and static variables around unwittingly, which can cause problems. This usually doesn't matter as much with instance methods, because the objects are ephemeral.
If you have static methods that reference static variables, those stay around for the life of the classloader and never get garbage collected. If these accumulate information (e.g. caches) and you are not careful, you can run into "memory leaks" in your application. If you use instance methods instead, the objects tend to be shorter-lived and so are garbage-collected after a while. Of course, you can still get into memory leaks with instance methods too! But it's less of a problem.
Hope that helps!
The main disadvantage is that you cannot swap, override or choose method implementations at runtime.
The performance advantage is likely negligible. Use static methods for anything that's not state dependent. This clarifies the code, as you can immediately see with a static method call that there's no instance state involved.
Disadvantage -> Static
Members are part of class and thus remain in memory till application terminates.and can't be ever garbage collected. Using excess of static members sometime predicts that you fail to design your product and trying to cop of with static /procedural programming. It denotes that object oriented design is compromised.This can result in memory over flow.
I really like this question as this has been a point I have been debating for last 4 years in my professional life. Static method make a lot of sense for classes which are not carrying any state. But lately I have been revised my though somewhat.
Utility classes having static methods is a good idea.
Service classes carrying business logic can be stateless in many cases. Initially I always added static methods in them, but then when I gained more familiarity with Spring framework (and some more general reading), I realized these methods become untestable as an independent unit as u cannot inject mock services easily into this class. E.g. A static method calling another static method in another class, there is no way JUnit test can short circuit tis path by injecting a dummy implementation at run time.
So I kind of settled to the thought that having utility static methods which do not need to call other classes or methods pretty much can be static. But service classes in general should be non static. This allows you to leverage OOPs features like overriding.
Also having a singleton instance class helps us to make a class pretty much like a static class still use OOPs concepts.
It's all a question of context. Some people have already given examples where static is absolutely preferable, such as when writing utility functions with no conceivable state. For example, if you are writing a collection of different sort algorithms to be used on arrays, making your method anything but static just confuses the situation. Any programmer reading your code would have to ask, why did you NOT make it static, and would have to look to see if you are doing something stateful to the object.
public class Sorting {
public static void quiksort(int [] array) {}
public static void heapsort(int[] array) { }
}
Having said that, there are many people who write code of some kind, and insist that they have some special one-off code, only to find later that it isn't so. For example, you want to calculate statistics on a variable. So you write:
public class Stats {
public static void printStats(float[] data) { }
}
The first element of bad design here is that the programmer intends to just print out the results, rather than generically use them. Embedding I/O in computation is terrible for reuse. However, the next problem is that this general purpose routine should be computing max, min, mean, variance, etc. and storing it somewhere. Where? In the state of an object. If it were really a one-off, you could make it static, but of course, you are going to find that you want to compute the mean of two different things, and then it's awfully nice if you can just instantiate the object multiple times.
public class Stats {
private double min,max,mean,var;
public void compute(float data[]) { ... }
public double getMin() { return min; }
public double
}
The knee jerk reaction against static is often the reaction of programmers to the stupidity of doing this sort of thing statically, since it's easier to just say never do that than actually explain which cases are ok, and which are stupid.
Note that in this case, I am actually using the object as a kind of special-purpose pass by reference, because Java is so obnoxious in that regard. In C++, this sort of thing could have been a function, with whatever state passed as references. But even in C++, the same rules apply, it's just that Java forces us to use objects more because of the lack of pass by reference.
As far as performance goes, the biggest performance increase of switching from a regular method is actually avoiding the dynamic polymorphic check which is the default in java, and which in C++ is specified manually with virtual.
When I tried last there was a 3:1 advantage of calling a final method over a regular method, but no discernible for calling static functions over final.
Note that if you call one method from another, the JIT is often smart enough to inline the code, in which case there is no call at all, which is why making any statement about exactly how much you save is extremely dangerous. All you can say is that when the compiler has to call a function, it can't hurt if it can call one like static or final which requires less computation.
The main problem you may face is, you won't be able to provide a new implementation if needed.
If you still have doubts ( whether your implementation may change in the future or not ) you can always use a private instance underneath with the actual implementation:
class StringUtil {
private static StringUtil impl = new DefaultStringUtil();
public static String nullOrValue( String s ) {
return impl.doNullOrValue();
}
... rest omitted
}
If for "some" reason, you need to change the implementation class you may offer:
class StringUtil {
private static StringUtil impl = new ExoticStringUtil();
public static String nullOrValue( String s ) {
return impl.doNullOrValue(s);
}
... rest omitted
}
But may be excessive in some circumstances.
No, actually the reason for that advice is that it provides a performance advantage. Static methods can be called with less overhead so any method that doesn't need a reference to this ought to be made static.
No there is no disadvantages, rather when you are not accessing any instance members in the method then there is no meaning of having it as an instance method. It is good programming skill to have it as a static method.
and adding to that you don't have to create any instances to access these methods and thus saving a memory and garbage collecting time.
In order to call the static methods you don't need to create class objects. The method is available immediately.
Assuming the class is already loaded. Otherwise there's a bit of a wait. :-)
I think of static as a good way to separate the functional code from procedural/state-setting code. The functional code typically needs no extension and changes only when there are bugs.
There's also the use of static as an access-control mechanism--such as with singletons.
One disadvantage is if your static methods are general and distributed in different classes as far as usage is concerned. You might consider putting all static methods that are general in a utility class.
There shouldn't be any disadvantages--there may even be a slight advantage in performance (although it wouldn't be measurable) since the dynamic lookup can be avoided.
It's nice to tag functions as functions instead of having them look like Methods--(and static "Methods" ARE functions, not methods--that's actually by definition).
In general a static method is a bad OO code smell--it probably means that your OO model isn't fully integrated. This happens all the time with libraries that can't know about the code that will be using it, but in integrated non-library code static methods should be examined to evaluate which of it's parameters it's most closely associated with--there is a good chance it should be a member of that class.
If a static method just takes native values, then you're probably missing a handful of classes; you should also keep passing native variables or library objects (like collections) to a minimum--instead containing them in classes with business logic.
I guess what I'm saying is that if this is really an issue, you might want to re-examine your modeling practices--statics should be so rare that this isn't even an issue.
As others have said, it provides a slight performance advantage and is good programming practice. The only exception is when the method needs to be an instance method for overriding purposes, but those are usually easily recognised. For example if a class provides default behaviour of an instance method, that happens not to need instance variables, that clearly can't be made static.
In general:
You should be writing your software to take advantage of interfaces and not implementations. Who's to say that "now" you won't use some instance variable, but in the future you will? An example of coding to interfaces...
ArrayList badList = new ArrayList(); //bad
List goodList = new ArrayList(); //good
You should be allowed to swap implementations, especially for mocking & testing. Spring dependency injection is pretty nice in this respect. Just inject the implementation from Spring and bingo you have pretty much a "static" (well, singleton) method...
Now, those types of APIs that are purely "utility" in purpose (i.e., Apache Commons Lang) are the exception here because I believe that most (if not all) of the implementations are static. In this situation, what are the odds that you will want to ever swap Apache Commons out for another API?
Specifically:
How would you elegantly handle the "staticness" of your implementation when you're targeting, say, a Websphere vs. Tomcat deployment? I'm sure there would be an instance (no pun intended) of when your implementation would differ between the two...and relying on a static method in one of those specific implementations might be dangerous...