Which is the best way to do the following task in java - java

I have more than 20 commonly used methods in my application. I would like to move that 20 methods into a common class.
Here my doubt is, define all the methods are static or normal method and create a global object to access that normal methods.
class Common {
public String method1() {........}
public String method2() {........}
public String method3() {........}
public String method4() {........}
public String method5() {........}
...
}
Creating object.
class CommonService {
private static Common common;
public static Common getCommon() {
if(null == common) {
common = new common();
}
return common;
}
}
If we create all the methods using static means, all 20 methods are stored in PermGen section of the heap.
But if we follow above method means, only one object can be created and stored in java heap.
Please clarify which one is the best way.

If we create all the methods using static means, all 20 methods are stored in PermGen section of the heap.
Methods are not data, but code. Where code is stored does not depend on whether a method accepts an implicit this parameter or not. If you use the singleton approach, method code will still occupy storage and additionally there will be an instance on the heap.
However, all of the above is irrelevant and you are focusing on a completely wrong aspect of your design. What matters is how the decision will affect the code which uses these methods:
static methods are simple and a great choice for pure functions (which don't depend on any external state);
singletons allow polymorphism, therefore make the methods easier to mock for testing.

You should think about the "best" way in terms of design.
If the methods are used for general purposes, making them static is preferable, as you won't have any state to store and you'll save memory this way.
You should consider other things before deciding if you want to use static methods in your utility class or not. On one hand the utility class will be very easy to test, and it's highly accessible. On the other hand, it's very hard to mock static methods in your test.
If I have a utility class, I would write it as follows:
public final class Common {
private Common() { }
public static int method1() { }
public static int method2() { }
// ...
}

"Common functions" is not quite accurate. It really depends on what you want to do, for example when I make some string utils I make StringUtils class and it has what I need. Whether to make it static or not depends on data to be processed, if one information might be used more than once for a call then answer is simple - use instances.

That depends on what the methods do.
If those methods are just helper methods, that do not alter state then static is probably better because that way you do not have to create an object every time you want to use one of the methods. You can just call Common.method()
However, if the object has state then you should rater use object methods and create a new object when you want to use the methods.
Hope this helps.

If sense of this method is "execute pure function" like mathematical sin(x), cos(x) etc static method is the best.
They belongs to one domain? (range of themats) or to different? (then create more "utility classes" with correct name)
If have state (like many people say) maybe better is singleton.
Shape of the question "i have 20 method in application" and name Common suggest previous (older) design problem, I say "procedural thinking", poor vision of OOP.
Hard to say without code.

Related

Non static methods vs Utilty with static methods

I am creating an application in Java which performs data movement task (like copy, move, etc.)
At the higher level, I can provide these operations on object level.
Sample code:
public class DataSource {
public boolean copy(DataSource dsDestination);
public boolean copy(DataSource dsDestination, Filter filter);
public boolean move(DataSource dsDestination);
public boolean exists();
// some other 10-15 methods
}
Or I can provide a utility with static methods:
public class DataSourceUtil {
public static boolean copy(DataSource dsSource, DataSource dsDestination);
public static boolean copy(DataSource dsSource, DataSource dsDestination, Filter filter);
public static boolean move(DataSource dsSource, DataSource dsDestination);
public static boolean exists(DataSource dsSource);
// some other 10-15 methods
}
Which one is better approach in terms of memory management?
The golden rule is: static is an abnormality within good OO design. You only use it if there are good reasons to do so.
You see, static leads to direct coupling between your classes. And it makes testing harder. Of course, the static methods themselves can be easily tested, but what would happen if you want to test a method that calls those static methods (and you have the need to influence what the static method is doing)? Then you might be tempted to turn to Powermock in order to mock those static calls. Which is not really a great idea.
If you insist on separating functionality, you better use interfaces, like:
public class DataSource {
... ctor, equals, ... methods
}
public interface DataSourceCopyAbility {
public void copy(DataSource source, DataSource destintion);
plus corresponding impl class.
EDIT: of course, convenience can be a valid reason to use static methods; for example I am using Objects.requireNonNull() all the time in code. But: those are standard API calls. When I am using them in my code, I really dont mind them to be running. I know that will never ever want to "mock" around such kind of static method invocations!
Finally: I assume you want to return true when your operations passed. Bad idea: booleans should only be used to distinguish between true and false. They are not return codes!
If such a complex operation as copying a DataSource fails - then throw an exception! Or if you really want to go without exceptions, define your own specific ReturnCode class that gives you insight into failing operations!
Forget about memory management.
No matter which method you use, you are still going to create two DataSource objects to call copy or move. There is little difference in memory usage.
What you should focus on instead, is readability and aesthetics :).
Compare these two:
someData.copy(otherData);
DataSourceUtils.copy(someData, otherData);
The second one is more verbose. Also, it seems that we need some other stuff (DataSourceUtils) to help with copying data. It would be less code to write and make more sense if we let the data copy itself (first one).
Another point that I want to point out is that you can add a To in the first one to make it a lot more readable:
someData.copyTo(otherData);
You can't do this with the second method.
I agree with #Jon Skeet , as all the operations need source object which is Datasource itself, then they should be instance methods. They are similar to equals in Object class.
From testable point-of-view instance methods are easy to test.
It depends on the functionality that you are writing in these methods..If the functionality is not using any object specific field values then using static methods would be the correct option.
i.e. make sure the variable information that you are using is not specific to object and data is common to class level
Memory management point of view, by the way, they are equivalent. The functions are share their compiled codes which is stored into the read only memory area. Only the difference between those two are the this pointer context. So it should not occupy any more space if you choose static or non static. Most of the compiled languages are following same manner.
the difference:
dataSource.copy();
copy is not my responsibility and it is a responsibility of DataSource.
DataSourceUtil.copy();
copy is my responsibility,but source code has been written in a utility class to avoid duplication.
Drawing from the experience of Apache Commons Lang library and java.lang.Objects, the advantage of static methods is that they can provide protection from NullPointerException
It is quite common to see something like this in Java code:
if (x != null && a.equals(otherX)) ...
or the practice of putting the literal on the left side:
if ("literal".equals(str)) ...
These are all NPE-protection ways. This is one of the reasons for the abovementioned liberary, and the case for static methods:
if (ds.copy(dest) == true) ... // may throw NPE
if (DataSourceUtil.copy(ds, dest) == true) ... // NPE protection

If a class has no state, should all the methods be static?

Lets say I have a Helper class like with a few methods
public class SomeClassesHelperClass(){
public List removeDuplicatesFromTheGivenList(List someList){
// code here
}
public int returnNumberOfObjectsThatHaveSomeSpecialState(List someList){
// code here
}
}
What are the advantages / disadvantages of making the methods in this class static? Which is the better practice?
If your class provides only utility methods (like yours), I believe it's better to:
make the class final (there's no point to extend it)
define а private constructor to avoid any attempt to create an instance of the class
make all the methods static.
If you decide to make all the methods static then you need to be aware of the impact that that will have on your ability to test other classes that depend up on it.
It severely limits your options for mocking ( or at least makes it more painful )
I don't think there is a right answer to our question - it depends on what the methods do. For example, it's easy to envisage a stateless data access object - if you make all its methods static then you are building a dependency on the data source in to your test cycle, or making your mocking code much uglier
Make them static when they use no state from an object. Most of it are helper classes like Math. http://docs.oracle.com/javase/6/docs/api/java/lang/Math.html

Shall we avoid writing static methods in our java code for better testability?

I was prefer using static methods in my java code, since I think they are "functional""stateless" and has less side-effect. So there may be some helper classes and methods like this:
public class MyHelper {
public static Set<String> array2set(String[] items) { ... }
public static List<String> array2list(String[] items) { ...}
public static String getContentOfUrl(String url) {
// visit the url, and return the content of response
}
}
public class MyApp {
public void doSomething() {
String[] myarray = new String[]{ "aa","bb"};
Set<String> set = MyHelper.array2set(myarray);
String content = MyHelper.getContentOfUrl("http://google.com");
}
}
But my friend says we should avoid defining such static utility methods, since we call them directly in our code, it will be hard to mock them or test them if they have external dependencies. He thinks the code should be:
public class ArrayHelper {
public Set<String> array2set(String[] items) { ... }
public List<String> array2list(String[] items) { ...}
}
public class UrlHelper {
public String getContentOfUrl(String url) {
// visit the url, and return the content of response
}
}
public class MyApp {
private final ArrayHelper arrayHelper;
private final UrlHelper urlHelper;
public MyApp(ArrayHelper arrayHelper, UrlHelper urlHelper) {
this.arrayHelper = arrayHelper;
this.urlHelper = urlHelper;
}
public void doSomething() {
String[] myarray = new String[]{ "aa","bb"};
Set<String> set = arrayHelper.array2set(myarray);
String content = urlHelper.getContentOfUrl("http://google.com");
}
}
In this way, if we want to write unit tests for MyApp, we can just mock the ArrayHelper and UrlHelper and pass them to the constructor of MyApp.
I agree totally about the UrlHelper part of his opinion, since the origin static code make MyApp untestable.
But I have a little confused about the ArrayHelper part, since it doesn't depend on any external resources and the logic will be very simple. Shall we avoid using static methods at this case too?
And when to use static methods? Or just avoid using it as much as possible?
update:
We are using "TDD" in our development, so the testability of a class often is the most important concern for us.
And I just replace the word "functional" with "stateless" in the first sentence since the that's real what I meant.
You'll probably never want to mock a method that converts an array to a list (or set), and this method doesn't need any state and doesn't depend on any environment, so a static method looks fine to me.
Just like the standard Arrays.asList() (which you should probably use).
On the other hand, accessing an external URL is typically the sort of thing that you want to be able to mock easily, because not mocking it would
make the test an integration test
require to have this external URL up every time you run your tests, which you probably can't guarantee
require to have this external URL return exactly what you want it to return in your test (including errors if you want to test the event of an error).
Just beware of one disease very common amongst Java "experts": overengineering.
In your specific example, you either do or don't have a mockability issue. If you had an issue, you wouldn't be asking general questions, therefore I conclude you don't have an issue at the moment.
The general argument is that static methods are simpler and therefore the preferred choice, whenever there is a choice. A would-be instance method must first prove itself of needing to be an instance method.
If this was my project, I would defer any makeovers into instance methods until such a moment where the need for that became clear and present.
Static means you can call the method without instantiating the class. Its good if you want to package your code into a class and you have a function that just does some logic or something basic.
Just don't use a static function to try and edit member variables in the class (obviously).
Personally I think its fine to use the static function, since it is stateless.
Static methods should be used by answering the question "is this method a functionality of a specific instance?".
You shouldn't decide about a static method according to tests, you should do it according to design. Your examples doesn't need an instance because it makes no sense. So static is the better choice. You can always wrap these methods inside specific tester classes to do your tests.
The only situation in which a self-contained functionality is not static is just when you want to provide multiple implementation, so that you are forced to avoid static because you need inheritance.
I often use static methods:
for factory methods (explicitly named constructors)
to provide a functional layer above an object-oriented layer, to compose the objects
and sometimes for general-purpose functions (Apache Commons has many good examples of this)
I never use "singletons" (static objects) and methods that refer to static objects because they are a complete headache to test and reuse. I also avoid hardcoding anything into a static method that could feasibly need to be changed. Sometimes I will provide multiple methods - one with all the dependencies as parameters and others, with fewer parameters, that call the more flexible method with some default (hardcoded) values.
java.lang.Math is static which is a good example. I thought statics are not beeing garbage collected and should be avoided if possible.
No.
As mentioned by Peter Lawrey in the comment for the question, Java is all about object oriented programming. While certain functional aspects are doable and being put into eg. Java 8, at its core Java is not functional. static breaks so much of the benefits of learning how to do modern Java - not to mention all kinds of not-fun-at-all scoping problems - that there's no purpose to use them unless you're some kind of a Java wizard who really knows what happens when you use that magical keyword.
You are not a wizard. Java is not functional. If you want to be a wizard, you can learn. If you want to program in functional fashion, look into hybrid languages such as Scala or Groovy or alternatively explore the fully functional world, eg. Clojure.

Access singleton's fields via a static method

I have a singleton class.
When accessing the methods of the class I have the choice of two possibilities.
Create those methods as instance specific and then get the instance and invoke them
Create those methods as static and invoke them and they will get the instance
For example:
Class Test{
private int field1;
Test instance;
private Test(){};
private Test getInstance(){
if (instance == null)
instance = new Test();
return instance;
}
public int method1() { return field1;}
public static int method2() {return getInstance().field1;}
}
Now, elsewhere I can write
int x = Test.getInstance().method1();
int y = Test.method2();
Which is better?
I can think of a 3rd alternative where I use "instance" directly in the static method and then capture the exception if it is null and instantiate it and then re-invoke itself.
I could, in theory, just make the whole lot static.
However, this will create me problems when saving the state at activity close since the serialization doesn't save static.
I think the first one is cleaner.
However, keep in mind that under some extreme cases, Android may kill your static instances. See this for example: http://code.google.com/p/acra/ .
A workaround I've found somewhere for this, is to keep a reference to your singleton from the Application class, as well. I don't know how problem-proof this is, though.
You should avoid making everything static. Some people would even say that a singleton is not done.
The whole point of the singleton pattern is that you can change the implementation. In most cases you use it to keep the possibility open to "hook" in some other implementations of this functionality later.
Read: when deciding in favor of singleton plan for a setInstance method too, not just for a getInstance. - If this does not make sense, just use a plain static class.
In the other hand singletons are out of season, if you want to be hip and all that. Do a search for "eliminating global state". There are some Google-sponsored talks about it too. In short: your code will be more testable and helps you avoid some dependency chaos. (Besides being hip and all, it is definitely a step into the right direction).
In my personal opinion having static methods is bad design in the first place. It, of course, depends on the program itself, but allowing a class to have static method will have impact on the whole design. Some reasoning behind my statement:
If static method can easily change state of some object, sooner or later bugs will emerge
If you publish static method with your program, every client that will use it will have a very strong dependency on your code. If you decide to remove or change this method someday - you will break every single client that used your class.
So, if you can - avoid it.
If, from any reason, you will insist on having static method, I guess the first solution is better. That's how singleton should work. You should obtain a reference to a SINGLETON OBJECT via static method, but this object should be then used according to all principles from Object Oriented Programming.

Are there any side effect of using to many static function?

Currently i`m interesting in play framework because this framework promise faster development.
When i see the code, there are so many static code. even the controller declared as static function. Thus all the code that called inside static function must be static right?
My question is, is this approach is right? are there any side effect of using to many static function?
This question has been asked in a similar way previously. The simple answer is that Play uses statics where it is sensible.
The HTTP model is not an OO model. HTTP requests themselves are stateless, and therefore, static methods allow access to controllers as functional requests from client code.
The Model classes on the other hand are pure OO, and as a result are not static heavy.
Some of the utility methods, such as findAll or findById are static, but these again are not statefull, and are utility methods on the class. I would expect this in a standard OO model anyway.
Therefore, I don't think there is any risk in doing things in the way Play expects. It may look odd, because it challenges the norm, but it does so for sound reasons.
Couple of things about static methods in an object oriented language: Let me try to explain the problems if you choose to have all static methods.
Using all static functions may not be idiomatic in an Object oriented language.
You cannot override static functions in a subclass. Therefore you lose the ability to do runtime polymorphism by overriding.
The variables that you define all become class variables automatically (since all your methods are static), so essentially you do not have any state associated with the instance.
Static methods are difficult to Mock. You might need frameworks like PowerMock to do the mocking for you. So testing becomes difficult.
Design becomes a bit complex as you won't be able to create immutable classes as you really only have the class and no instance. So designing thread-safe classes becomes difficult.
To elaborate on my comment.
static methods can call non-static methods provided you have an instance of something.
class A {
public void nonStaticMethod() { }
public static void staticMethod(String text) {
// calls non-static method on text
text.length();
// calls non-static method on new Object
new Object().hashCode();
// calls non static method on a instance of A
new A().nonStaticMethod();
}
}
Yes there is a side effect of using too many static functions or variables. You should avoid unnecessary static declarations.
Because static members always creates a memory space once the class is loaded in the JRE. Even if you don't create the object of the class it will occupy the memory.

Categories