开发者

Can I make a utility method static?

开发者 https://www.devze.com 2023-03-20 04:08 出处:网络
I have some functions like: One that takes input on string and modifies and returns the string Function that takes a string (holding XML) as input and parses it and returns an object.

I have some functions like:

  1. One that takes input on string and modifies and returns the string

  2. Function that takes a string (holding XML) as input and parses it and returns an object.

For examp开发者_如何学Cle:

public class MyUtils{

    public static modifyString(String str){
        return someString;
    }

    public MyObject parseString(String xml){
        //Parse XML
        return obj;
    }
}
  1. Can I make such functions static, so that anyone can use those without creating instance of my class?
  2. What if two threads call the function at same time? Is the code thread-safe? If yes/no, how?
  3. When should I use a singleton object and when should I use static methods?


  1. Yes, just add the static keyword. Using the example you have given, you could call modifyString like this:

    MyUtils.modifyString("Some string data");

  2. in your example, as you aren't modifying anything that is stored on your class, it would depend on whether multiple things were accessing what was being passed in. The class itself should be thread-safe.

  3. They are different things, you should use a singleton when you need to use instance data, that is, when you need your class to have attributes or a state. For utility functions, the better option is often to use static methods instead as you are less likely to have a state associated with a utility function.


  1. Yes, you should.

  2. There's no problem specific to static methods; however, if your method references a static field or a mutable argument, there could be conflicts with other threads. If it is referencing a static field, consider using singleton pattern instead.

  3. Use the singleton pattern when the class has state of its own to manage, and particularly to hide such state from clients. If the class just consists of stateless utility functions, you can use static methods and you don't need to use singleton pattern.


  1. Yes, you can make these methods static. In fact these "utility classes" are normally created with static methods.

  2. No, these methods are not thread-safe, a thread could interrupt the method execution and change the value that was currently being worked on.

  3. You should use a singleton when you only need one instance of a class. A good example is a logging class that logs information about the execution of your program. In this case, it wouldn't make sense to use a singleton, because you would be using static methods.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号