인터페이스 상수의 장단점
PHP 인터페이스는 인터페이스에서 상수 정의를 허용합니다.
interface FooBar
{
const FOO = 1;
const BAR = 2;
}
echo FooBar::FOO; // 1
모든 구현 클래스는 자동으로 이러한 상수를 사용할 수 있습니다.
class MyFooBar implement FooBar
{
}
echo MyFooBar::FOO; // 1
이것에 대한 내 자신의 견해는 글로벌은 모든 것이 악하다는 것 입니다. 그러나 동일한 것이 인터페이스 상수에 적용되는지 궁금합니다. 인터페이스에 대한 코딩 이 일반적으로 좋은 습관으로 간주 된다는 점을 감안할 때 인터페이스 상수를 사용하는 것이 클래스 컨텍스트 외부에서 사용할 수있는 유일한 상수입니까?
개인적인 의견과 인터페이스 상수를 사용하는지 여부가 궁금하지만 주로 답변에서 객관적인 이유를 찾고 있습니다. 나는 이것이 투표 유형 질문이되기를 원하지 않습니다. 인터페이스 상수를 사용하는 것이 유지 관리성에 어떤 영향을 미치는지 관심이 있습니다. 커플 링. 또는 단위 테스트. SOLID PHP 와 어떤 관련이 있습니까? PHP에서 Good Practice로 간주되는 코딩 원칙을 위반합니까? 당신은 아이디어를 얻습니다 ...
참고 : Java에 대한 유사한 질문 이 있는데, 이것이 나쁜 관행 인 이유를 나열한 것입니다. 그러나 Java는 PHP가 아니기 때문에 PHP 태그 내에서 다시 묻는 것이 정당하다고 느꼈습니다.
글쎄, 나는 그것이 차이로 귀결이라고 생각 좋은 과 충분히 좋은 .
대부분의 경우 다른 패턴 (전략 또는 플라이 웨이트)을 구현하여 상수 사용을 피할 수 있지만, 개념을 표현하기 위해 6 개의 다른 클래스가 필요하지 않다고 할 수 있습니다. 요약하면 다른 상수가 얼마나 필요할까요? 즉, 인터페이스에서 상수가 제공하는 ENUM을 확장 할 필요가 있습니까? 확장 할 필요가 있다고 예견 할 수 있다면 좀 더 공식적인 패턴으로 가십시오. 그렇지 않은 경우 충분할 수 있습니다 (충분히 좋으므로 작성하고 테스트 할 코드가 적습니다). 다음은 충분히 좋고 나쁜 사용의 예입니다.
나쁜:
interface User {
const TYPE_ADMINISTRATOR = 1;
const TYPE_USER = 2;
const TYPE_GUEST = 3;
}
충분하다:
interface HTTPRequest_1_1 {
const TYPE_CONNECT = 'connect';
const TYPE_DELETE = 'delete';
const TYPE_GET = 'get';
const TYPE_HEAD = 'head';
const TYPE_OPTIONS = 'options';
const TYPE_POST = 'post';
const TYPE_PUT = 'put';
public function getType();
}
자, 제가 그 예를 선택한 이유는 간단합니다. User
인터페이스는 사용자 유형의 정의를 열거한다. 이것은 시간이 지남에 따라 확장 될 가능성이 매우 높으며 다른 패턴에 더 적합합니다. 그러나 HTTPRequest_1_1
열거 형은 RFC2616에 의해 정의되고 클래스 수명 동안 변경되지 않기 때문에 괜찮은 사용 사례입니다.
일반적으로 나는 상수와 클래스 상수의 문제를 글로벌 문제 로 보지 않습니다 . 나는 그것을 의존성 문제로 본다. 좁은 구분이지만 확실한 구분입니다. 강제되지 않는 전역 변수에서와 같은 전역 문제를 보고 소프트 전역 종속성을 만듭니다. 그러나 하드 코딩 된 클래스는 강제 종속성을 생성하므로 하드 전역 종속성이 생성됩니다. 따라서 둘 다 종속성입니다. 그러나 나는 그것이 시행되지 않았기 때문에 글로벌 이 훨씬 더 나쁘다고 생각한다. 그래서 나는 동일한 배너 아래에서 글로벌 의존성 과 함께 클래스 의존성 을 묶는 것을 좋아하지 않는다 ...
If you write MyClass::FOO
, you're hard-coded to the implementation details of MyClass
. This creates a hard-coupling, which makes your code less flexible, and as such should be avoided. However, interfaces exist to permit exactly this type of coupling. Therefore MyInterface::FOO
doesn't introduce any concrete coupling. With that said, I wouldn't introduce an interface just to add a constant to it.
So if you're using interfaces, and you're very sure that you (or anyone else for that matter) won't need additional values, then I don't really see a huge issue with the interface constants... The best designs wouldn't include any constants or conditionals or magic-numbers or magic-strings or hard-coded anything. However, that adds additional time to the development, as you must consider the uses. My view is that most times it's absolutely worth taking the additional time to build a great solid design. But there are times when good enough really is acceptable (and it takes an experienced developer to understand the difference), and in those cases it's fine.
Again, that's just my view on it...
I think that its usually better to handle constants, specially enumerated constants, as a separate type ("class") from your interface:
define(TYPE_CONNECT, 'connect');
define(TYPE_DELETE , 'delete');
define(TYPE_GET , 'get');
define(TYPE_HEAD , 'head');
define(TYPE_OPTIONS, 'options');
define(TYPE_POST , 'post');
define(TYPE_PUT , 'put');
interface IFoo
{
function /* int */ readSomething();
function /* void */ ExecuteSomething(/* int */ param);
}
class CBar implements IFoo
{
function /* int */ readSomething() { ...}
function /* void */ ExecuteSomething(/* int */ param) { ... }
}
or, if you want to use a class as a namespace:
class TypeHTTP_Enums
{
const TYPE_CONNECT = 'connect';
const TYPE_DELETE = 'delete';
const TYPE_GET = 'get';
const TYPE_HEAD = 'head';
const TYPE_OPTIONS = 'options';
const TYPE_POST = 'post';
const TYPE_PUT = 'put';
}
interface IFoo
{
function /* int */ readSomething();
function /* void */ ExecuteSomething(/* int */ param);
}
class CBar implements IFoo
{
function /* int */ readSomething() { ...}
function /* void */ ExecuteSomething(/* int */ param) { ... }
}
Its not that you are using just constants, you are using the concept of enumerated values or enumerations, which a set of restricted values, are considered a specific type, with a specific usage ("domain" ? )
참고URL : https://stackoverflow.com/questions/5350672/pros-and-cons-of-interface-constants
'program story' 카테고리의 다른 글
정규식에서 단어 경계는 무엇입니까? (0) | 2020.08.18 |
---|---|
가비지 수집기는 여기서 무한 루프를 어떻게 피합니까? (0) | 2020.08.18 |
Python argparse로 숨겨진 인수 만들기 (0) | 2020.08.18 |
std :: vector 요소는 연속적입니까? (0) | 2020.08.18 |
배치 파일 : 콘솔 창을 열어 두는 방법 (0) | 2020.08.18 |