In Java, is there any disadvantage to static methods on a class?

后端 未结 14 1485
无人及你
无人及你 2020-12-03 06:37

Lets assume that a rule (or rule of thumb, anyway), has been imposed in my coding environment that any method on a class that doesn\'t use, modify, or otherwise need any ins

14条回答
  •  生来不讨喜
    2020-12-03 07:21

    The main problem you may face is, you won't be able to provide a new implementation if needed.

    If you still have doubts ( whether your implementation may change in the future or not ) you can always use a private instance underneath with the actual implementation:

     class StringUtil {
         private static StringUtil impl = new DefaultStringUtil();
    
         public static String nullOrValue( String s ) {
              return impl.doNullOrValue();
         }
         ... rest omitted 
      }
    

    If for "some" reason, you need to change the implementation class you may offer:

      class StringUtil {
         private static StringUtil impl = new ExoticStringUtil();
    
         public static String nullOrValue( String s ) {
              return impl.doNullOrValue(s);
         }
         ... rest omitted 
      }
    

    But may be excessive in some circumstances.

提交回复
热议问题