2

I'm new to java. I have been reading about Getter/Setter (Why to use getter/setter and getter/setter poor design). While I read on Oracle Understanding JIT. I've two questions as follows :

My question is that, if JIT replaces some getters/setters with actual value while compiling a code, how is the purpose of getter/setter being fulfilled?

How will we achieve encapsulation ?

Community
  • 1
  • 1
Shatayu Darbhe
  • 797
  • 1
  • 7
  • 13

3 Answers3

4

You're confusing the two different "compile times" (which is easily done).

The usual "compile time" we refer to is literally that: When the source code text is converted into bytecode. But the JIT (the Just-In-Time compiler) happens at runtime.

The encapsulation happens because any code using your class only sees the getters and setters. The JIT can then inline those getters and setters, but that's a runtime optimization, not something code can use.

Consider the common pattern where the setter is private and the getter is public:

class Square {
    int size;

    public Square(int size) {
        this.setSize(size);
    }

    private void setSize(size) {
        this.size = size;
    }

    public int getSize() {
        return this.size;
    }
}

While the JIT (or even the main compiler) may well inline setSize, and the JIT may well inline getSize, code using Square instances cannot use that in any way to modify the size field.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
4

if JIT replaces some getters/setters with actual value while compiling a code how purpose of getter/setter is fulfilled in java particular ?

Because it's only an optimization. The getters and setters still work exactly as expected - and if you later change the implementation to use different fields or some other mechanism, the JIT compiler will have to change how it transforms the code as well.

For the most part, your reasoning about program design shouldn't care about the JIT compiler at all - that's an implementation detail about how your program happens to get executed. You may well want to care about it occasionally to achieve better performance, but it doesn't change whether or not your program design still holds up.

Just because a JIT may compile code that uses a getter to effectively just get the field directly doesn't mean it's appropriate to expose the field publicly yourself - that would expose an implementation detail, making it hard to change later. It doesn't matter if you change things which make your JIT-compiled code invalid later, because by the time you're running the new code, the JIT compiler won't be aware of what it did with the old code anyway.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
0

JIT is for the compiler, while the getters/setters is for programmer. even JIT will do such a change for performance reasons, we can still make advantage of the getters/setters while we are coding.

ZhaoGang
  • 4,491
  • 1
  • 27
  • 39