CAFE

C# 2.0

c# Fluent interface 이게 뭐꼬?

작성자심재운|작성시간12.04.03|조회수479 목록 댓글 4



wikipedia 에서는  Fluent interface 을 단지 좀 더 가독성 즉, 읽기 편하게 객체지향언어를 구현하는데 있다고 명시되어 있습니다.

말 그대도 어떤 성능 이슈도 아니고, 개발자 분들이 읽기 편하고, 줄 라인 줄이고, 간단하게 기술할 수 있다는 매력을 갖고 있다는

의미인데요...


In software engineering, a fluent interface (as first coined by Eric Evans and Martin Fowler) is an implementation of an object oriented API that aims to provide for more readable code.

A fluent interface is normally implemented by using method chaining to relay the instruction context of a subsequent call (but a fluent interface entails more than just method chaining [1]). Generally, the context is


여러분들은 OOP 를 배울때 아래와 같은 구조로 개발을 하였을 겁니다.

인터페이스를 구현하시고, 기술할 메소드를 설계 한 다음에 클래스에서 인터페이스를 상속받아 내부 변수 및 프로퍼티, 그리고 메소드를 이용하여 하나의 클래스를 설계 합니다.


public interface IConfiguration
    {
        void SetColor(string newColor);
        void SetDepth(int newDepth);
        void SetHeight(int newHeight);
        void SetLength(int newLength);
    }
 
    public sealed class Configuration : IConfiguration
    {
        private string color;
        private int depth;
        private int height;
        private int length;
 
        public void SetColor(string newColor)
        {
            this.color = newColor;
        }
 
        public void SetDepth(int newDepth)
        {
            this.depth = newDepth;
        }
 
        public void SetHeight(int newHeight)
        {
            this.height = newHeight;
        }
 
        public void SetLength(int newLength)
        {
            this.length = newLength;
        }
    }



그럼 위의 클래스를 가지고 객체를 생성해 볼까요?

간단히 클래스의 인스턴스를 생성하여 객체를 만들고 프로퍼티를 통해 지역변수에 값을 할당하였습니다. 보통 여러분들은 이렇게 구현하였겠지요? 이를 좀 더 가독성 있게 한번 구현해 보고자 하는게 Fluent interface  인데요. 꼭 이것을 써야 좋다는 것은 아니고..^^;



IConfiguration config = new Configuration();
config.SetColor("blue");
config.SetHeight(1);
config.SetLength(2);
config.SetDepth(3);






자...이제 Fluent interface  를 어떻게 위와 다른지 알아보죠.

인터페이스를 보시면 반환이 void 가 아닌 자신의 인터페이스명을 기술하고 있는게 독특합니다.

이를 상속받은 클래스 또한 void 가 아닌 인터페이스로 반환을 처리하고 있지요. 그래서 return this; 를 통해 변수의 자기 자신을 반환합니다.

그리고 static 으로 New() 생성자를 구현하여 객체 인스턴스를 반환하고요.  좀 익숙 스럽지 못한 구조이라서 난감하실겁니다. ^^;



public interface IConfigurationFluent { IConfigurationFluent SetColor(string newColor); IConfigurationFluent SetDepth(int newDepth); IConfigurationFluent SetHeight(int newHeight); IConfigurationFluent SetLength(int newLength); } public sealed class ConfigurationFluent : IConfigurationFluent { private string color; private int depth; private int height; private int length; private ConfigurationFluent() { } public static IConfigurationFluent New() { return new ConfigurationFluent(); } public IConfigurationFluent SetColor(string newColor) { this.color = newColor; return this; } public IConfigurationFluent SetDepth(int newDepth) { this.depth = newDepth; return this; } public IConfigurationFluent SetHeight(int newHeight) { this.height = newHeight; return this; } public IConfigurationFluent SetLength(int newLength) { this.length = newLength; return this; } }




이제 위의 클래스를 어떻게 호출하여 구현할까요. 아까 위에 static 으로 생성자를 호출하는 New() 를 구현하여 인스턴스를 생성한 다음 세미콜론 (;) 으로 구문을 닫지 않고 곧바로 점(.) 을 통해 간결하게 프로퍼티를 호출하여 값을 할당하고 있습니다. 

사실 코드는 깔끔하고 보기 좋긴 하지만 디버깅 할 때 아래의 코드를 하나의 덩어리로 보기 때문에 어느 라인에서 문제가 생기는지 빨리 잡아내기가 어렵다는 단점이 있긴 합니다. ^^

 


IConfigurationFluent fluentConfig =
                ConfigurationFluent
                    .New()
                    .SetColor("blue")
                    .SetHeight(1)
                    .SetLength(2)
                    .SetDepth(3);





어떤가요??? 여러분은 어떤구조로 구현을 하실 건가요??? 이는 가독성이지, 성능과 전혀 무관하므로 참고하시기 바랍니다.


감사합니다.




다음검색
현재 게시글 추가 기능 열기
  • 북마크
  • 공유하기
  • 신고하기

댓글

댓글 리스트
  • 작성자퇴근5분전 | 작성시간 12.04.03 아 ... 첨 oop 공부하면서 비슷하게 구현해봤는뎅... 이런거군요..

    항상 잘보고 있습니다. +_+;
  • 작성자남처리 | 작성시간 12.04.03 자기 자신을 리턴해서 메서드 체인으로 이용하는 부분이 Jquery Plugin 같군요.
  • 작성자퓨전마법사 | 작성시간 12.04.04 남철이 많이 컸네.. 체인? 체인은 자전거 체인밖에 모르는데 .. 플러그인에다가.. 워~~~ 어려운말 너무 많이 쓴다...
  • 답댓글 작성자심재운 작성자 본인 여부 작성자 | 작성시간 12.06.25 미안허다..ㅡㅡ;
댓글 전체보기
맨위로

카페 검색

카페 검색어 입력폼