Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using static methods in enterprise application in JAVA

I am working on a Enterprise java application which is essentially a HTTP server. There I need to use some constants and sort of utility functions for parsing, file I/O etc. I have used static methods and variables for this purpose, but someone pointed out to me that using static for this purpose is a bad choice since from performance and memory point of view.

While I do not agree with this argument, I also do not see any other choice. Even if I convert them to instance methods, and access through a singleton instance, the instance will be accessed by some static function.

So, I want to know if this is really a problem. And If it is, what is the best approach to fix it?

Thanks in advance.

like image 962
Aarkan Avatar asked Dec 09 '25 22:12

Aarkan


1 Answers

You're quite right that ultimately everything is run from a static main() method. And many functions are suitable for being made static, e.g. simple methods like those on java.lang.Math. Speed and memory-use are non-issues - a static method does not take up any more memory or run slower than any other method. Internally, it's exactly the same as any other method but is defined and runs on a class-instance instead of an instance of the class.

A problem I've found with static methods is that it's easy inadvertently to slip in some specific assumptions (e.g. where a directory is) which makes it harder to reuse the function elsewhere. It also can become much harder to test the code. When you're unit testing, you usually want to be able to test without doing *time-consuming) I/O - e.g. by mocking or stubbing out the I/O parts. If your method doesn't allow that, it's much harder. Singleton classes can cause similar testing difficulties.

Static methods tend to lead to functional or procedural, rather than object-oriented code. I find static methods useful as a functional layer of "syntactic sugar" above a rich domain model of objects.

It's also worth mentioning that there are loads of existing utilities classes around, such as Apache Commons IO, Google Guava etc. They are well-written, heavily used and well-tested. You might consider looking at them before reinventing the wheel.

like image 116
ᴇʟᴇvᴀтᴇ Avatar answered Dec 11 '25 12:12

ᴇʟᴇvᴀтᴇ



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!