Win a copy of High Performance Python for Data Analytics this week in the Python forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Paul Clapham
  • Ron McLeod
  • Bear Bibeault
  • Liutauras Vilda
Sheriffs:
  • Jeanne Boyarsky
  • Tim Cooke
  • Junilu Lacar
Saloon Keepers:
  • Tim Moores
  • Tim Holloway
  • Stephan van Hulst
  • Jj Roberts
  • Carey Brown
Bartenders:
  • salvin francis
  • Frits Walraven
  • Piet Souris

When to use static methods

 
Ranch Foreman
Posts: 2348
12
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks. It says to do like

CashRegisterLauncher.java:


CashRegister.java:



Is it acceptable to have the run method of CashRegister.java class to call methods like CashRegisterHelper.staticMethod1, CashRegisterHelper.staticMethod2 etc ?


 
Marshal
Posts: 71752
312
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Monica Shiralkar wrote:. . . call methods like CashRegisterHelper.staticMethod1, CashRegisterHelper.staticMethod2 etc ?

Yes, but why do you want such static methods? You would call methods like takeMoney(...), giveChange(...), getCurrentTotal(), etc.
 
Monica Shiralkar
Ranch Foreman
Posts: 2348
12
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
For example, once I had a simple FileStatusReport application which reads the status of files using a query from database, prepares the email Content and send to the Notification Engine. From the main method of class FileStatusReport.java, I called the static methods of FileStatusReportHelper.java named getFileDataFromDb, prepareEmailContent, sendToNotificationEngine. Now after going through the WIKI for Main Pain, I will write such kind of codes differently but I am still thinking how could static have been removed in this case.
 
Campbell Ritchie
Marshal
Posts: 71752
312
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
You want to see your objects working; you should already know your helper class works correctly.
 
Monica Shiralkar
Ranch Foreman
Posts: 2348
12
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Campbell Ritchie wrote:You want to see your objects working; you should already know your helper class works correctly.



I had felt that  methods getFileDataFromDb, prepareEmailContent, sendToNotificationEngine are suitable to be made static methods instead of instance methods. Do you mean I can instead make these instance methods?
 
Campbell Ritchie
Marshal
Posts: 71752
312
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
No. I meant that you should see the new instance methods working as a priority. Let's look at a different example:-Now explain the remainder of that class, including my not overriding equals(), hashCode(), and toString().
 
Monica Shiralkar
Ranch Foreman
Posts: 2348
12
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Campbell Ritchie wrote:No. I meant that you shouldd see the new instance methods working as a priority.


Yes, but to me those methods which I mentioned had looked suitable to be static methods and not instance methods.  


Let's look at a different example:-Now explain the remainder of that class, including my not overriding equals(), hashCode(), and toString().



The constructor has been made private to disallow creating instance of this class which would be useless as we already have this class as the entry point.

We are getting our actual work done in Game class by creating instance and calling the instance method.

From what I understand:
It makes sense to have a method as instance method , if it alters an instance variable. E.g set an instance variable named score in a Game class.
It makes sense to have a method as static , it only does what it does and does not set any instance variable.
 
Saloon Keeper
Posts: 12628
273
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Monica Shiralkar wrote:Yes, but to me those methods which I mentioned had looked suitable to be static methods and not instance methods.


They probably weren't. You were probably either accessing static variables that really should have been instance fields, or your static method accepted method parameters that could instead have been encapsulated in an object.

It makes sense to have a method as static , it only does what it does and does not set any instance variable.


That's not the full story. If the static method requires a method parameter to do what it does, you should consider adding an instance method to the class of that method parameter instead. Here is an example:

DO NOT DO:

DO DO:
 
Monica Shiralkar
Ranch Foreman
Posts: 2348
12
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator



But if all we are doing is reading something from the database, whey do we want to tie that to an instance instead of just having it static?
 
Monica Shiralkar
Ranch Foreman
Posts: 2348
12
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

If the static method requires a method parameter to do what it does, you should consider adding an instance method to the class of that method parameter instead.



Suppose I have a method which "requires a method parameter", then shouldn't I simply make that static and that piece of work done?
 
Marshal
Posts: 26308
80
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Monica Shiralkar wrote:... shouldn't I simply make that static and that piece of work done?



You have followed Stephan's advice here; you have considered whether you should add an instance method to the String class and decided not to do that. It's obvious why you wouldn't do that, of course.

But don't confuse that particular decision with the idea that you should never modify the class of the method parameter, nor with the idea that you should always modify that class either. It's always necessary to consider doing that and to decide to do it, or not to do it.
 
Paul Clapham
Marshal
Posts: 26308
80
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Monica Shiralkar wrote:But if all we are doing is reading something from the database, whey do we want to tie that to an instance instead of just having it static?



If you have a collection of static methods which access a database, then changes to that scenario should involve adding (or removing) static methods. But there are good reasons why you would have an object of some class which accesses a database. And in that case changes to that scenario would involve adding (or removing) instance methods.
 
Monica Shiralkar
Ranch Foreman
Posts: 2348
12
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Paul Clapham wrote:
You have followed Stephan's advice here;


But he had said "If the static method requires a method parameter to do what it does, you should consider adding an instance method to the class of that method parameter instead".
As per that since the method takes a parameter, I should have made that instance method instead of static. I did the opposite of that and made that static.
 
Stephan van Hulst
Saloon Keeper
Posts: 12628
273
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Monica Shiralkar wrote:But if all we are doing is reading something from the database, whey do we want to tie that to an instance instead of just having it static?


Static methods should have no side-effects. Something goes in, something comes out. No application state is changed.

When you access a database, you change application state. That means the method that accesses the database should not be static, but instead it should be an instance method of an object that wraps around the data source.

The methods in java.lang.Math are proper static methods. For instance, Math.atan2(y, x) accepts Euclidean coordinates and outputs the angular component of the corresponding polar coordinates. It uses no application state to perform this transformation, and does not change the application state.

Now, before we jump into another rabbit hole, what I said here are good guidelines to follow in general. It's not a hard rule to follow in all cases. If you're in software engineering for many years, you will find edge cases where applying the guidelines will be difficult.

Incidentally, these guidelines are another nail in the coffin of lazily instantiated singletons: Lazy singletons require a static method that affects application state. That means lazy singletons are a bad idea per se.

Suppose I have a method [...] which "requires a method parameter", then shouldn't I simply make that static and that piece of work done?


No. Your example doesn't affect application state.
 
Stephan van Hulst
Saloon Keeper
Posts: 12628
273
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Monica Shiralkar wrote:But if all we are doing is reading something from the database


This phrase betrays a fundamental difference in thinking about the application.

You seem to think that reading from a database is easy. Maybe for you, the programmer, it is. However, compared to everything else in the application it is extremely difficult. It's a big source of bugs for many small applications that grew to include a database. Usually such applications have to be rewritten from the ground up to make sure that the database access layer is well planned out from the start.

Abstracting away complexity one of the most important goals of OOP. Encapsulate complexity and application state in objects on which you can call simple instance methods. Static methods are not OOP.
 
Monica Shiralkar
Ranch Foreman
Posts: 2348
12
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Stephan van Hulst wrote:
No. Your example doesn't affect application state.


That's why I wrote that I wanted it to be Static. You also said that if it doesn't affect application state , it can be static . So I am trying to understand why did you say "No" in that case.
 
Paul Clapham
Marshal
Posts: 26308
80
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Monica Shiralkar wrote:That's why I wrote that I wanted it to be Static.



This is the main problem, I think. You want methods to be static. But as you know Java is an object-oriented language, so you should be asking when a method must be static.

Like Stephan said before, you should be designing objects to do the work for your application. Static variables and methods should only be used when they specifically apply to the workings of the entire class and not to the working of an individual object.

It's unfortunate that people are often taught Java via programs which only use static methods. For a lot of people it seems like a big step to switch over to programs which use objects, apparently.
 
Campbell Ritchie
Marshal
Posts: 71752
312
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Paul Clapham wrote:. . . It's unfortunate that people are often taught . . . only . . . static methods. For a lot of people it seems like a big step to switch over to programs which use objects, apparently.

Agree.
Some people make the change to objects easily and some take ages; I know somebody who took two years to understand the difference. If that delay occurs during a University course or other training, that is longer than the duration of the module and failure to understand objects can make the difference between a grade A and a scrape pass. I don't like the idea of taking the risk of several of one's trainees/students learning badly like that.
 
Campbell Ritchie
Marshal
Posts: 71752
312
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Paul Clapham wrote:. . . . Static . . . methods should only be used when they specifically apply to the workings of the entire class . . . .

I would add to that, or when they are being used as functions and the class only acts as a container for the method. The methods in java.lang.Math are like that; since the introduction of static import you can write sin(x) and get its sine. A more object‑oriented design might have been to give Math an argument field:-Maybe this design of the Math class follows C where such functions can exist all on their own in a math.h file.
 
Stephan van Hulst
Saloon Keeper
Posts: 12628
273
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Monica Shiralkar wrote:That's why I wrote that I wanted it to be Static. You also said that if it doesn't affect application state , it can be static . So I am trying to understand why did you say "No" in that case.


I read my post back and I'm not sure what I meant to tell you there. I think I misread your post that I was responding to.

If your method doesn't affect application state and doesn't rely on application state, yes, it CAN be static. But see Paul and Campbell's comments on why that's still often a bad idea: You're fighting against the Object Oriented nature of Java.
 
Campbell Ritchie
Marshal
Posts: 71752
312
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I have thought a bit more about having Math as an ordinary class with fields; maybe they thought it would be expensive in processing time to create new objects. It isn't, but it probably would have been back in 1996.
 
Stephan van Hulst
Saloon Keeper
Posts: 12628
273
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Object oriented programming is more than just making objects of everything though. The abstract concept of "Math" doesn't really lend itself well to making an object out of it.

The real solution is to treat primitives as objects and do stuff like 123.45.sin(). As of Java 15 we still can't do this, so the best way is still to use pure functions in a static utility class. Maybe when project Valhalla is finally done.
 
Campbell Ritchie
Marshal
Posts: 71752
312
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Stephan van Hulst wrote:. . . treat primitives as objects . . . when project Valhalla is finally done.

It can't come too soon.
 
Paul Clapham
Marshal
Posts: 26308
80
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Campbell Ritchie wrote:

Paul Clapham wrote:. . . . Static . . . methods should only be used when they specifically apply to the workings of the entire class . . . .

I would add to that, or when they are being used as functions and the class only acts as a container for the method.



Another situation is when the Factory method pattern is being used. In modern Java you'll often find an "of(...)" method which is a static method in class or interface X whose purpose is to produce an object of type X based on the parameters passed to it.

For example in the java.time package there's Year.of(2021) and YearMonth.of(2021, 1) and many others. Those could just be constructors (e.g. new Year(2021)) so why aren't they? Well, the objects in the java.time package are immutable so the factory method doesn't have to return different objects every time Year.of(2021) is called.

Similarly in the functional programming area there are Stream.of(...) and Stream.empty(). And for collections there's List.of(...) and List.copyOf(collection) and many others whose purpose is to produce immutable collections. Because immutable objects are easier to work with, especially for functional programming.
 
Greenhorn
Posts: 1
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
We can use static methods in the following scenarios:

1. If you are writing utility classes and they are not supposed to be changed and we want to call them without creating object.
2. If the method is not using any instance variable.
3. If any operation is not dependent on instance creation means object creation.
4. If there is some code that can easily be shared by all the instance methods, extract that code into a static method.
5. If you are sure that the definition of the method will never be changed or overridden. As static methods can not be overridden.
For more details you can read about static class in java
 
Bartender
Posts: 2782
135
Google Web Toolkit Eclipse IDE Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

anmol singh wrote:1. If you are writing utility classes and they are not supposed to be changed and ...

Not sure about what you mean here. Are you referring to method definition ?

anmol singh wrote:4. If there is some code that can easily be shared by all the instance methods, extract that code into a static method.

Disagree, this is not always true and might need a non-static method

anmol singh wrote:For more details you can read about ...

I didn't read in much, but that URL covers topics related to static class and not static methods. Quite honestly, I find the indentations of the code posted on that tutorial quite confusing.

I find the default java tutorial page much concise about this topic: https://docs.oracle.com/javase/tutorial/java/javaOO/classvars.html
 
Campbell Ritchie
Marshal
Posts: 71752
312
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
That link describes static nested classes, which are of course more or less completely unrelated to static methods.
 
Monica Shiralkar
Ranch Foreman
Posts: 2348
12
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Paul Clapham says

Static variables and methods should only be used when they specifically apply to the workings of the entire class and not to the working of an individual object.



Stephan van Hulst says

You're fighting against the Object Oriented nature of Java.




But the below code is not related to object. All it is doing is taking a name and creating a greetings message using it. Thus, can I use static for the below?

 
Paul Clapham
Marshal
Posts: 26308
80
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Monica Shiralkar wrote:But the below code is not related to object. All it is doing is taking a name and creating a greetings message using it. Thus, can I use static for the below?



Since it doesn't compile there's no point in asking the question.
 
Stephan van Hulst
Saloon Keeper
Posts: 12628
273
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Monica Shiralkar wrote:But the below code is not related to object. All it is doing is taking a name and creating a greetings message using it. Thus, can I use static for the below?


It depends on the implementation. If it uses application state to build the greeting message, then no. By application state I don't just mean instance fields, but database connections and the like as well.

If on the other hand the method is just a simple conversion of its input arguments to an output result, then static may be appropriate. However, make the method private. If you have to reuse that method in multiple other classes, it might be a sign that it should be refactored into a service instead:


Granted, my example here is contrived, and in many cases a simple static utility class will be easier. It's just that the need for static utility methods that are reused by multiple classes should not arise very often. If it does, there's something smelly about your application design.
 
Paul Clapham
Marshal
Posts: 26308
80
Eclipse IDE Firefox Browser MySQL Database
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
It's also possible that the simple code to build a greeting message might be the code which is used in the base class of some inheritance hierarchy. Perhaps the designer intended for that greeting-message method to be overridden in subclasses, where it might very well use application state of those subclasses.

So you can't tell just by looking at the code whether a method should be static or not. You have to know about the design of the method and the class which it's contained in.
 
Monica Shiralkar
Ranch Foreman
Posts: 2348
12
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Paul Clapham wrote:

Since it doesn't compile there's no point in asking the question.



Yes, sorry about that. I meant something like the below:

 
Monica Shiralkar
Ranch Foreman
Posts: 2348
12
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Stephan van Hulst wrote:the need for static utility methods that are reused by multiple classes should not arise very often.



Why so ? I may have a static method in a helper class and whichever class needs that functionality would use that.
 
Stephan van Hulst
Saloon Keeper
Posts: 12628
273
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Yes, but it's indicative of that you're not using an object oriented approach.

Your buildGreetingsMessage() example is very simple, and doesn't really reflect the kind of static utilities that are written in real-life applications. In big applications, the static utility classes that people write are often full of complex methods that do a lot of work and require different parameters. In such a case, you're better off creating a service contract for the utility, and inject an implementation of the service contract into the class that called the static utility.
 
Monica Shiralkar
Ranch Foreman
Posts: 2348
12
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Stephan van Hulst wrote:
Your buildGreetingsMessage() example is very simple, and doesn't really reflect the kind of static utilities that are written in real-life applications.



As builGreetingsMessage example doesn't reflect, what can be such an example which reflects ?
 
Stephan van Hulst
Saloon Keeper
Posts: 12628
273
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I'll give you a rough example of what I encounter in the code base at my company. We haven't had the time to refactor it yet.

There's a static method in one of our services that converts a bunch of very complex objects containing raw data to an XML document that can then be processed by another system. This method is called by a whole lot of plugins that extend our service because they either need to send the XML to another system, or they need to modify the XML itself.

Instead of letting the plugins call this static method, it would have been better to pass an interface into the plugin which the plugin could use to perform the conversion. It prevents your service from exposing all its internals to the outside world and it makes plugins more easily testable because you can inject mocked implementations of the interface.
 
He was expelled for perverse baking experiments. This tiny ad is a model student:
the value of filler advertising in 2020
https://coderanch.com/t/730886/filler-advertising
reply
    Bookmark Topic Watch Topic
  • New Topic