developer tip

Java에서 클래스 불변이란 무엇입니까?

copycodes 2020. 9. 22. 08:22
반응형

Java에서 클래스 불변이란 무엇입니까?


주제를 검색했지만 위키피디아 외에는 유용한 문서 나 기사를 찾지 못했습니다.

아무도 그것이 의미하는 바를 간단한 말로 설명하거나 멋지고 이해하기 쉬운 문서를 참조 할 수 있습니까?


Java와 관련하여 특별히 의미하는 것은 아닙니다.

클래스 불변은 다른 코드가 수행하는 작업에 관계없이 항상 클래스의 모든 인스턴스를 유지하는 속성입니다.

예를 들면

class X {
  final Y y = new Y();
}

X는 y속성이 있고 결코 존재하지 않으며 nulltype 값 이 있다는 불변 클래스를 가지고 Y있습니다.

class Counter {
  private int x;

  public int count() { return x++; }
}

두 가지 중요한 불변성을 유지하지 못함

  1. count때문에 가능한 언더 플로우의 음의 값을 반환하지 않습니다.
  2. 그 호출 count은 엄격하게 단조롭게 증가하고 있습니다.

수정 된 클래스는이 두 가지 불변성을 유지합니다.

class Counter {
  private int x;

  public synchronized int count() {
    if (x == Integer.MAX_VALUE) { throw new IllegalStateException(); }
    return x++;
  }
}

그러나 예외가 발생하거나 교착 상태가 된 스레드가 카운터의 모니터를 소유하는 경우 차단 될 수 있기 때문에 호출이 count항상 정상적으로 성공 하도록하는 불변성을 보존하지 못합니다 (TCB 위반 † 없음 ) count.

클래스가있는 각 언어를 사용하면 일부 클래스 불변성을 쉽게 유지할 수 있지만 다른 것은 그렇지 않습니다. Java도 예외는 아닙니다.

  1. Java 클래스는 일관되게 속성과 메소드를 갖거나 갖지 않으므로 인터페이스 불변을 유지하기 쉽습니다.
  2. Java 클래스는 private필드 를 보호 할 수 있으므로 개인 데이터에 의존하는 불변성은 유지 관리하기 쉽습니다.
  3. Java 클래스는 최종 클래스가 될 수 있으므로 악성 하위 클래스를 작성하여 불변을 위반하는 코드가 없다는 것에 의존하는 불변을 유지할 수 있습니다.
  4. Java는 null값이 다양한 방식으로 몰래 빠져 나갈 수 있도록 허용 하므로 "실제 값을 가짐"불변성을 유지하기가 어렵습니다.
  5. Java에는 스레드가 있습니다. 즉, 동기화되지 않는 클래스는 함께 발생하는 스레드에서 순차적 작업에 의존하는 불변성을 유지하는 데 문제가 있습니다.
  6. Java에는 "속성 p로 결과를 반환하거나 결과를 반환하지 않음"과 같은 불변성을 유지하기 쉽게하는 예외가 있지만 "항상 결과를 반환합니다"와 같은 불변성을 유지하기가 더 어렵습니다.

†- 외부 성 또는 TCB 위반 은 시스템 설계자가 낙관적으로 발생하지 않을 것이라고 가정하는 이벤트입니다.

Typically we just trust that the basic hardware works as advertised when talking about properties of high-level languages built on them, and our arguments that invariants hold don't take into account the possibility of:

  • A programmer using debug hooks to alter local variables as a program runs in ways that code cannot.
  • Your peers don't use reflection with setAccessible to modify private lookup tables.
  • Loki altering physics causing your processor to incorrectly compare two numbers.

For some systems our TCB might include only parts of the system, so we might not assume that

  • An administrator or privileged daemon won't kill our JVM process,

but we might assume that

  • We can checkpoint to a reliable transactional file-system.

The higher-level a system, the larger its TCB typically is, but the more unreliable things you can get out of your TCB, the more likely your invariants are to hold, and the more reliable your system will be in the long run.


Invariant means something that should stick to its conditions no matter whatever changes or whoever uses/transforms it. That is to say, a property of a class always fulfills or satisfies some condition even after going through transformations by using public methods. So, the client or user of this class is ensured about the class and its property.

For example,

  1. condition on function argument is that, it should always be > 0 (greater than zero) or should not be null.
  2. minimum_account_balance property of an account class states, it cannot go below 100. So all public functions should respect this condition and ensure class invariant.
  3. rule based dependency between variables, that is, value of one variable depends on another, so if one changes, using some fix-rule, other must also change. This relationship between 2 variables must be preserved. If it does not, then invariant is violated.

They are facts that must be true about an instance class. For example if a class has a property X and invariant can be X must be greater then 0. To my knowledge there is no built-in method for maintaining invariants you must make properties private and make sure your getters and setters enforce invariance property.

There are annotations available which can check properties using reflection and interceptors. http://docs.oracle.com/javaee/7/api/javax/validation/constraints/package-summary.html

참고URL : https://stackoverflow.com/questions/8902331/what-is-a-class-invariant-in-java

반응형