Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

> If you have a simple method implementation that does not depend on instance state, it is a good idea to make it static, for both maintainability and performance reasons. Carrying around the class instance just to make the virtual call off it makes life harder for runtime.

Also anonymous inner classes retain a pointer to the parent which can impact memory usage.

Additionally although not relevant to the code in question, the author's habit of using if/else vs. ternary (or if-only) can have performance and caching implications:

http://stackoverflow.com/questions/4706696/which-if-construc...

http://kennethxu.blogspot.com/2013/10/ifelse-statement-vs-te...



It should be noted that making things static can impair testability a great deal. For this reason I frown upon static references across component boundaries. Even within components I tend to use dependency injection for this very reason.

I fail to see why static methods should be better with respect to maintenance unfortunately the author lacks an explanation of this opinion. I would express the contrary opinion as you can exchange the implementation easier at selected spots.


It depends a lot on what you do with the static method. If it's side-effect free, an Utils class with static methods can be a good way to test some business code without exposing private methods.

If it's impure, run away.


Yes, the Utils class is easier to test. But its clients are harder to test, if the Utils class crosses component Boundaries or rely on a fat runtime (such as an JEE server or an OSGi runtime) being up and running.


For some cases. But static methods can be easier to unit test.

But if you're concerned enough about performance to care about minute bytecode details (intended audience of the article), I think ease of testing is a lower priority.


> Additionally although not relevant to the code in question, the author's habit of using if/else vs. ternary (or if-only) can have performance and caching implications:

If ternary and if-else statement don't perform same in both cases, I'd call it a bug in JVM. On C/C++ compilers I've tried, ternary has always compiled to exactly same as if-else-statement.


The Java code ends up being different in subtle ways. Exemplified by this:

  static int x[] = new int[1];

  public static void main1(String[] args) {
    x[1] = grow() ? 10 : 20; //array index out of bounds!
  }

  public static void main2(String[] args) {
    if (grow()) {
      x[1] = 10;
    } else {
      x[1] = 20;
    }
    //no exceptions thrown
  }

  private static boolean grow() {
    x = new int[2];
    return true;
  }




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: