DISQUS

Andy Palmer: Static Utility Methods

  • Mc · 1 year ago
    You'd have to involve at least 3 classes and some DI library refs to accomplish your two strategies scenario. Even then you're still coupled to one of those 3 types (interface or abstract class supertype). This complexity may be appropriate at some times, but the setup/overhead/code is overkill for a great number of common cases. Think of Math.cos or StringUtils.reverse - very unlikely that'd you'd want to change those, much less do the plumbing for keeping instances of those utility class available in some global context.


    Your post did leads me to wonder: what if static methods could be "extended" how might that work. I certainly haven't thought through that extensively. I'm sure the java language people have, and there must be great reasons why its not possible.



    Maybe look at it this way: using "composition," you can make whatever instantiable utility classes to wrap any existing other classes/methods you find are otherwise unsatisfactory.
  • Andy · 1 year ago
    It's true with StringUtils.reverse that I would be unlikely to want to change the implementation, but I would much rather write:
    "abc1234".reverse();

    than:

    StringUtils.reverse("abc1234");



    I think if I bumped into one of the instances I mentioned where I wanted to be able to change out the configuration at runtime, then I would use an instance wrapper around a static method...



    My opinions are no way set in stone, it's just that static methods make me feel icky and I'm not 100% sure why :-)