2012-05-08 6 views
1

내 문제를 설명하기 위해 C#을 사용하여 예제 코드를 보여 드리겠습니다. 예에 Demeter 원칙에 대한 혼동

interface IConstructorInfoSelector 
{ 
    //ConstructorInfo is System.Reflection.ConstructorInfo class. 
    ConstructorInfo SelectConstructorInfo(Type declaringType); 
} 

class TestClass 
{ 
    private readonly ConstructorInfo _constructorInfo; 

    public TestClass(IConstructorInfoSelector constructorInfoSelector, Type type) 
    { 
     //Let the line to (A) 
     _constructorInfo = constructorInfoSelector.SelectConstructorInfo(type); 
    } 

    public TestClass(ConstructorInfo constructorInfo) 
    { 
     _constructorInfo = constructorInfo; 
    } 

    public Type GetTypeForConstructor() 
    { 
     //Let the line to (B) 
     return _constructorInfo.DeclaringType; 
    } 
} 

, 내가 ctor에로의 TestClass를 구성하는 경우 (IConstructorInfoSelector, 유형)과 라인 (A)와 (B)를 통해 디테일 정도 (데메테르 원칙의 법을) 위반하는 것이라고 GetTypeForConstructor 전화 .

그러나 다음 코드를 실행하면 코드가 LoD를 위반합니까? 나는 line (C)의 testClass 객체가 메소드 내에서 초기화되고 GetTypeForConstructor 메소드가 호출되고 다른 한편으로는 위의 경우와 같은 원칙을 위반하는 것으로 보이기 때문에 위반하지 않는다고 생각한다. 요약하면 반환 객체가 다른 객체를 만드는 데 사용되면이 실행은 LoD를 위반 한 것으로 간주됩니까?

class LoDQuestionForTestClass 
{ 
    public void DeosThisVoliateTheLoD() 
    { 
     IConstructorInfoSelector concreteSelector = ...; 
     Type testType = ...; 
     var selectConstructorInfo = concreteSelector.SelectConstructorInfo(testType); 
     //Let the line to (C) 
     var testClass = new TestClass(selectConstructorInfo); 
     var result = testClass.GetTypeForConstructor(); 
    } 
} 

답변

2

한 개체가 세 번째 개체에서 제공 한 다른 개체의 동작에 의존하면 LoD를 위반하게됩니다. 그 중 하나는 "친구의 친구를 신뢰하지 말 것"입니다.

두 번째 예에서는 타사에서 제공하는 개체에 따라 다른 개체가 있으므로 예를 들어 "친구를 신뢰하지 마십시오. 친구의 "를 제외하고 selectConstructorInfo는 단지 그것의 가치를 위해 사용됩니다.

LoD는 특정 프로젝트 (Demeter) 용으로 작성되었으며 가장 엄격한 형식은 다른 프로젝트에는 적용되지 않을 수 있습니다.

+0

답장을 보내 주셔서 감사합니다. 좀 더 질문 할 수 있을까요? 1) "selectConstructorInfo가 오직 사용 된 경우를 제외하고 ..."에 대한 자세한 정보를 제공해 주시겠습니까? " 즉, 메서드는 논리 또는 연산없이 지정된 반환 유형으로 값 (또는 객체) 만 반환합니다. –

+0

죄송합니다. 약간 길어요. 2) 내가 이해하는 한, LoD 원칙을 유지한다는 것은 메소드가 반환 값의 어떤 메소드도 반환하지 않기 때문에 메소드가 단순한 값 (int, string 등) 또는 DTO (데이터 전송 객체)와 같은 데이터 구조 값만을 반환해야한다는 것을 의미합니다. 체인 상태에서 사용해서는 안됩니다. –

+0

@jwjung 모든 객체는 비헤이비어가 있지만 값이기도합니다. 귀하의 경우에는 selectedConstructorInfo를 다른 객체와 비교하면 값을 위해 사용하고 있습니다. Invoke 메서드를 사용하여 새 객체를 구성하면 이제 친구 친구의 행동에 의존합니다. LoD를 위반합니다. –