Programing

Java에서 상수 클래스를 어떻게 정의합니까?

lottogame 2020. 11. 4. 07:37
반응형

Java에서 상수 클래스를 어떻게 정의합니까?


상수를 보유하는 클래스를 정의해야한다고 가정합니다.

public static final String SOME_CONST = "SOME_VALUE";

이 작업을 수행하는 데 선호되는 방법은 무엇입니까?

  1. 상호 작용
  2. 추상 클래스
  3. 최종 수업

어떤 것을 사용해야하며 그 이유는 무엇입니까?


일부 답변에 대한 설명 :

열거 형 - 열거 형 을 사용하지 않을 것입니다. 아무것도 열거하지 않고 어떤 식 으로든 서로 관련이없는 상수를 수집합니다.

인터페이스 - 인터페이스 를 구현하는 클래스로 설정하지 않을 것입니다. 인터페이스를 사용하여 다음과 같이 상수를 호출하고 싶습니다 ISomeInterface.SOME_CONST.


최종 수업을 사용하십시오. 단순화를 위해 정적 가져 오기를 사용하여 다른 클래스의 값을 재사용 할 수 있습니다.

public final class MyValues {
  public static final String VALUE1 = "foo";
  public static final String VALUE2 = "bar";
}

다른 수업에서 :

import static MyValues.*
//...

if(variable.equals(VALUE1)){
//...
}

귀하의 설명은 다음과 같습니다. "나는 열거 형을 사용하지 않을 것입니다. 아무것도 열거하지 않고 서로 관련이없는 상수를 수집합니다."

상수가 서로 전혀 관련이없는 경우 왜 함께 수집하고 싶습니까? 가장 밀접하게 관련된 클래스에 각 상수를 넣으십시오.


내 제안 (내림차순) :

1) 하지 마십시오 . 가장 관련성이 높은 실제 클래스에서 상수를 만듭니다. '상수 가방'클래스 / 인터페이스를 갖는 것은 실제로 OO 모범 사례를 따르는 것이 아닙니다.

나와 다른 모든 사람들은 때때로 # 1을 무시합니다. 그렇게하려는 경우 :

2) 개인 생성자 가있는 최종 클래스 이것은 적어도 상수에 쉽게 접근 할 수 있도록 확장 / 구현함으로써 누군가가 당신의 '상수 가방'을 남용하는 것을 막을 것입니다. (당신이 이것을하지 않겠다고 말한 것을 알고 있습니다.하지만 그렇다고 누군가 당신이 그렇게하지 않을 것이라는 의미는 아닙니다.)

3) interface 이것은 작동하지만 # 2에서 가능한 남용 언급을 제공하는 선호하는 것은 아닙니다.

일반적으로 이것이 상수라고해서 정상적인 oo 원칙을 적용해서는 안된다는 의미는 아닙니다. 클래스에있는 사람 외에는 상수에 대해 신경 쓰지 않는 경우-해당 클래스에 비공개 여야합니다. 테스트 만 상수에 관심이 있다면 프로덕션 코드가 아닌 테스트 클래스에 있어야합니다. 상수가 여러 위치에서 정의 된 경우 (실수로 동일하지 않음)-리팩터링하여 중복을 제거합니다. 등등-당신이 방법처럼 그들을 대하십시오.


Joshua Bloch는 Effective Java에서 다음과 같이 말합니다.

  • 인터페이스는 유형을 정의하는 데만 사용해야합니다.
  • 추상 클래스는 불안정성을 방지하지 않습니다 (하위 클래스 화 될 수 있으며 서브 클래스 화되도록 설계되었음을 제안 할 수도 있음).

모든 상수가 관련되어있는 경우 (예 : 행성 이름) Enum을 사용하거나, 관련된 클래스에 상수 값을 넣거나 (액세스 권한이있는 경우), 불안정한 유틸리티 클래스를 사용 (개인 기본 생성자를 정의) 할 수 있습니다. .

class SomeConstants
{
    // Prevents instanciation of myself and my subclasses
    private SomeConstants() {}

    public final static String TOTO = "toto";
    public final static Integer TEN = 10;
    //...
}

그런 다음 이미 언급했듯이 정적 가져 오기를 사용하여 상수를 사용할 수 있습니다.


내가 선호하는 방법은 전혀하지 않는 것입니다. 상수의 시대는 Java 5가 typesafe 열거 형을 도입했을 때 거의 죽었습니다. 그리고 그 전에도 Josh Bloch는 Java 1.4 (및 그 이전 버전)에서 작동하는 (약간 더 장황한) 버전을 발표했습니다.

레거시 코드와의 상호 운용성이 필요하지 않는 한 더 이상 명명 된 문자열 / 정수 상수를 사용할 이유가 없습니다.


마지막 수업을 사용하십시오.

다른 값을 추가하려면 추상 클래스를 사용하십시오.

It doesn't make much sense using an interface, an interface is supposed to specify a contract. You just want to declare some constant values.


Aren't enums best choice for these kinds of stuff?


enums are fine. IIRC, one item in effective Java (2nd Ed) has enum constants enumerating standard options implementing a [Java keyword] interface for any value.

My preference is to use a [Java keyword] interface over a final class for constants. You implicitly get the public static final. Some people will argue that an interface allows bad programmers to implement it, but bad programmers are going to write code that sucks no matter what you do.

Which looks better?

public final class SomeStuff {
     private SomeStuff() {
         throw new Error();
     }
     public static final String SOME_CONST = "Some value or another, I don't know.";
}

Or:

public interface SomeStuff {
     String SOME_CONST = "Some value or another, I don't know.";
}

Or 4. Put them in the class that contains the logic that uses the constants the most

... sorry, couldn't resist ;-)


  1. One of the disadvantage of private constructor is the exists of method could never be tested.

  2. Enum by the nature concept good to apply in specific domain type, apply it to decentralized constants looks not good enough

The concept of Enum is "Enumerations are sets of closely related items".

  1. Extend/implement a constant interface is a bad practice, it is hard to think about requirement to extend a immutable constant instead of referring to it directly.

  2. If apply quality tool like SonarSource, there are rules force developer to drop constant interface, this is a awkward thing as a lot of projects enjoy the constant interface and rarely to see "extend" things happen on constant interfaces

참고URL : https://stackoverflow.com/questions/479565/how-do-you-define-a-class-of-constants-in-java

반응형