Avatar billede fredand Forsker
26. september 2017 - 15:37 Der er 7 kommentarer og
1 løsning

Debate over static methods

Hello guys!

We have a debate about use static methods or not use static methods.
In this case it is in a EJB-context, (but I do not think that matter, correct me if I'm wrong).
What do you think is the best way or pattern for this code below.
We have a method in a class where the class has no fields, similar to this.

imports ...

public class JmsUtil
{

      public String sendBytesMessage( byte[] messageBytes ) throws JMSException, NamingException
      {
                        String jmsMessageID =null;
                        Connection connection = null;
                        try
                        {
                                    Context context = new InitialContext();
                                    ConnectionFactory connectionFactory = (ConnectionFactory) context.lookup( "ourfactory" );
                                    Queue queue = (Queue)context.lookup( "ourqueue" );
                                   
                                    connection = connectionFactory.createConnection();
                                    Session session = connection.createSession(false,  Session.AUTO_ACKNOWLEDGE);
                                    MessageProducer messageProducer = session.createProducer( queue );
                                    BytesMessage bytesMessage = session.createBytesMessage();
                                    bytesMessage.writeBytes( messageBytes );
             
                                    messageProducer.send( bytesMessage );
                                    jmsMessageID = bytesMessage.getJMSMessageID();
     
                        }
                        finally
                        {
                                    if(connection != null)
                                    {
                                                  connection.close();
                                    }
                        }
                        return jmsMessageID;
     
      }
}

Would you prefer to use the code above like:

JmsUtil jmsUtil = new JmsUtil();
String jmsid = jmsUtil.sendBytesMessage( "Hello".getBytes() );

...or change the method to be static and use it like this...

String jmsid = JmsUtil.sendBytesMessage( "Hello".getBytes() );

Is there an pros or cons with one way or the other?

Best regards
Fredrik
Avatar billede arne_v Ekspert
26. september 2017 - 16:00 #1
This is a topic with a lot of subjective opinions.

My take is:
* In modern OOP / modern Java people realize that not everything is OO in nature but that there actually are things that are procedural in nature
* The way to do that in Java is static methods
* But one need to be careful - I have many times started static and later had to change to non-static, but never the other way around
* I would limit static methods to:
  - utility style classes with only static methods (and maybe a private constructor to prevent instantiation)
  - private static utility methods in other classes
  to keep things under control.
Avatar billede fredand Forsker
26. september 2017 - 20:17 #2
Hello Arne!
Thanks for your reply.
Really Interesting to get your thoughts about it.
I do agree with you that static is the way. Me myselef use it a lot in utillty classes.
But you also mention private static utillty methods in other classes. I must admitt that I do not think I have  used that. Could you explain it a bit more?
Best regards
Fredrik
Avatar billede arne_v Ekspert
27. september 2017 - 04:26 #3

    public class MyUtil {
        private MyUtil() {
        }
        public static int giveMe42() {
            return 42;
        }
    }
    public class A {
        // ...
        public void something() {
            // ...
            int v = MyUtil.giveMe42();
            // ...
        }
        // ...
    }
    public class B {
        // ...
        public void somethingElse() {
            // ...
            int v = MyUtil.giveMe42();
            // ...
        }
        // ...
    }



    public class Foobar {
        private static int giveMe42() {
            return 42;
        }
        // ...
        public void something() {
            // ...
            int v = giveMe42();
            // ...
        }
        // ...
        public void somethingElse() {
            // ...
            int v = giveMe42();
            // ...
        }
        // ...
    }
Avatar billede arne_v Ekspert
27. september 2017 - 04:28 #4
And I am sure you have used that before.

:-)

By "other classes" I just meant "classes that are not utility classes".
Avatar billede arne_v Ekspert
27. september 2017 - 04:32 #5
If you need a well-known reference to utility classes with static methods being OK see
"Effective Java, 2nd Edition, Joshua Bloch" Item 4.
Avatar billede fredand Forsker
11. oktober 2017 - 08:30 #6
Hello Arne!

Thanks for you input about this.

1) I have now read a couple of items from Joshua Bloch, really interesting. How ever I also found some arguments while googling about this that only use "static" when a method is a "pure function". Does that mean that my example in this thread is disqualified to be a "static" since it use external resources as those for JMS? What do you think?
In other hand what could be the disadvantage/danger with using external resources in a static context? The only argument I have found is that it might be hard to test since it should be hard to mock.

2) Actuality after all these years I still have to admit that I have not used a private static method, but I think I see the the reason. Please correct me if I am wrong:
- If the method is only of interest for instances of the same class, and not to instances of  other classes and it performs work/value that is suitable on class level (for all instances)

Best regards'
Fredrik
Avatar billede arne_v Ekspert
11. oktober 2017 - 15:31 #7
re 1)

I am not sure how they define "pure function".

But I see multiple levels of "pureness".

A) No side effects aka calculation only.
B) External side effects - file system, database, message queues, singletons etc..
C) Internal side effects - static fields in class.

I consider both A and B to be OK (C smells of bad design).

They may only consider A to be OK.

But I believe that many actions of the B are truly procedural in nature.
Avatar billede arne_v Ekspert
11. oktober 2017 - 15:39 #8
re 2)

My point was just that while there are some cases where static methods make sense, then I like to have some restriction on it.

If it need to be called from multiple classes then a utility class with only static methods and name containing Util in it is a reasonable well documented approach.

If it only need to be called from one class then making it private within that class reduces scope of the method and I automatically consider it OK as anyone looking at that class  can easily see it.
Avatar billede Ny bruger Nybegynder

Din løsning...

Tilladte BB-code-tags: [b]fed[/b] [i]kursiv[/i] [u]understreget[/u] Web- og emailadresser omdannes automatisk til links. Der sættes "nofollow" på alle links.

Loading billede Opret Preview

Log ind eller opret profil

Hov!

For at kunne deltage på Computerworld Eksperten skal du være logget ind.

Det er heldigvis nemt at oprette en bruger: Det tager to minutter og du kan vælge at bruge enten e-mail, Facebook eller Google som login.

Du kan også logge ind via nedenstående tjenester