Private method inlining

前端 未结 2 644
花落未央
花落未央 2020-12-09 13:47

In the Scala immutable Vector code there is a comment that says:

In principle, most members should be private. However, access privileges must be car

2条回答
  •  春和景丽
    2020-12-09 14:33

    I'm not an expert in "compiler decision" but logically I would say:

    Let's imagine these two classes (in Java for instance):

    class A {
    
      private B b;
    
      public void execute(){
        b.execute();
      }
    
    }
    
    class B {
    
      private int number;
    
      public void execute {
        println(number);
      }
    
    }
    

    If B's execute is inlined by the compiler into A's execute, it would lead to an illegal access since number is private in B:

    class A {
    
      private B b;
    
      public void execute(){
        println(number);  //OUPS! number is unreachable directly from A
      }
    
    }
    

    So I would say that when you expect some "inlining", prefer to avoid some uncompatible variable's scope.

    Of course, I would imagine it's useful in rare cases (mostly for performance optimization, I don't imagine other cases)..maybe the case you shew, otherwise it would lead to a lot of "bad encapsulations"...

提交回复
热议问题