Search code examples
typescript

Class with static methods vs exported functions typescript


I've been trying to research this but can't see to find any recommendations. I've inherited a code base where the team is using classes with static methods instead of functions for helper methods. I've never seen this approach taken and trying to decide if I should have them go back and create functions out of them. I feel like this is unclean and bloats imports since you're importing the entire class instead of just the function you're intending?

Is one approach better than the other?

For example's sake in case I'm not being clear:

    export class StringUtil {
      public static alterString(str: string) {
        return alteredString;
      }
    }

vs

    export function alterString(str: string) {
      return alteredString;
    }

This would then be used like so:

import { StringUtil } from '../StringUtil';

getString(str: string) {
  return StringUtil.alterString(str);
}

vs

import { alterString } from '../helper-functions';

getString(str: string) {
  return alterString(str);
}

Solution

  • Functionally, both implementations will produce the same result with the only difference being that for static methods the function is attached to the class' prototype. If you don't actually need that behavior (unlikely that you do), I'd keep you static methods as separate functions as this is better for tree-shaking and code-splitting (unless you have a LOT of static methods though, these will be only minor gains). In practice, I find that static methods usually only appear for two reasons:

    1. whoever wrote the code is used to Java and
    2. some IDEs present warnings that you should mark methods as static if they don't use instance variables.

    If you just want that ability to namespace a bunch of static methods, you can still do so by exporting an object with all of the individual functions attached.