본문 바로가기

Programming/SW Engineering , Architecture, etc.

Perfecting OO's Small Classes and Short Methods. 완벽한 객체지향의 작은 클래스와 짧은 메소드, Book:ThoughtWorks Anthology, Java,cpp,자바,oop,좋은코드,객체지향프로그래밍 - (#9, Tell, Don't Ask)

Perfecting OO's Small Classes and Short Methods. 완벽한 객체지향의 작은 클래스와 짧은 메소드, Book:ThoughtWorks Anthology, Java,cpp,자바,oop,좋은코드,객체지향프로그래밍 - (#9, Tell, Don't Ask)




원글 ( 여기 )

Origin ( Here )




TellDontAsk 말해라, 묻지말고



Tell-Don't-Ask is a principle that helps people remember that object-orientation is about bundling data with the functions that operate on that data. It reminds us that rather than asking an object for data and acting on that data, we should instead tell an object what to do. This encourages to move behavior into an object to go with the data.


 TellDontAsk 는 데이터를 실행하는 함수들과 데이터의 묶음에 관한 객체지향을 기억하는데 도움을 주는 원리이다. 이것은 우리가 객체에 데이터를 묻고나서 행동하게 하기보다는, 대신 객체에 무엇을 할지를 말해줘야 한다. 이것은 행동이 객체 안의 데이터와 같이 있도록 이동시킨다.



Let's clarify with an example. Let's imagine we need to monitor certain values, signaling an alarm should the value rise above a certain limit. If we write this in an "ask" style, we might have a data structure to represent these things…


 예제를 확인하자. 우리가 특정 값을 확인해야 한다고 상상해보는데, 한계치 위로 특정값이 초과하면 신호가 온다. 만약 이것을 "ask" 스타일로 쓰면, 이것들을 표현하기 위한 자료구조가 있을 것이다.



class AskMonitor...


  private int value;

  private int limit;

  private boolean isTooHigh;

  private String name;

  private Alarm alarm;


  public AskMonitor (String name, int limit, Alarm alarm) {

    this.name = name;

    this.limit = limit;

    this.alarm = alarm;

  }


…and combine this with some accessors to get at this data

그리고 이 데이터를 얻기위해 접근자를 결합한다.


class AskMonitor...


  public int getValue() {return value;}

  public void setValue(int arg) {value = arg;}

  public int getLimit() {return limit;}

  public String getName()  {return name;}

  public Alarm getAlarm() {return alarm;}



We would then use the data structure like this

우린 이와같이 자료구조를 쓸 것이다.



AskMonitor am = new AskMonitor("Time Vortex Hocus", 2, alarm);

am.setValue(3);

if (am.getValue() > am.getLimit()) 

  am.getAlarm().warn(am.getName() + " too high");




"Tell Don't Ask" reminds us to instead put the behavior inside the monitor object itself (using the same fields).


"Tell Don't Ask" 는 우리가 동작 자체를 모니터하고 있는 객체 안에 넣도록 상기시켜준다. (같은 필드를 사용해서)




class TellMonitor...


  public void setValue(int arg) {

    value = arg;

    if (value > limit) alarm.warn(name + " too high");

  }




Which would be used like this

이렇게 사용될 것이다




TellMonitor tm = new TellMonitor("Time Vortex Hocus", 2, alarm);

tm.setValue(3);




Many people find tell-don't-ask to be a useful principle. One of the fundamental principles of object-oriented design is to combine data and behavior, so that the basic elements of our system (objects) combine both together. This is often a good thing because this data and the behavior that manipulates them are tightly coupled: changes in one cause changes in the other, understanding one helps you understand the other. Things that are tightly coupled should be in the same component. Thinking of tell-don't-ask is a way to help programmers to see how they can increase this co-location.


 많은 사람들이 tell-don't-ask는 유용한 원리라고 한다. 객체지향 디자인의 가장 기본적인 원리들 중 하나는 데이터와 동작의 결합인데, 시스템의 기본적인 요소들을 한데로 묶기 위해서 이다. 이것은 종종 좋은데, 왜냐면 이 데이터와 데이터를 조작하는 동작이 타이트하게 결합되어 있기 때문이다. 하나를 바꾸면 하나를 바꾸고, 하나를 이해하는 것이 다른 것을 이해하는데 도움을 준다. 강하게 결합된 것들은 같은 컴포넌트 안에 있어야 한다. 


But personally, I don't use tell-dont-ask. I do look to co-locate data and behavior, which often leads to similar results. One thing I find troubling about tell-dont-ask is that I've seen it encourage people to become GetterEradicators, seeking to get rid of all query methods. But there are times when objects collaborate effectively by providing information. A good example are objects that take input information and transform it to simplify their clients, such as using EmbeddedDocument. I've seen code get into convolutions of only telling where suitably responsible query methods would simplify matters [1]. For me, tell-don't-ask is a stepping stone towards co-locating behavior and data, but I don't find it a point worth highlighting.


 그러나 개인적으로, 난 tell-dont-ask 를 사용하지 않는다. 나는 같은 위치의 데이터와 동작을 두고 비슷한 결과를 낸다. tell-dont-ask 에서 내가 찾은 문제는 모든 질의 메소드를 없애려고 하면서, GetterEradicators 가 되어 버리는 것이다. 그러나 정보를 제공받으며(질의문을 쓰면서) 효과적으로 같이 동작할 때도 있다. 좋은 예는 속의 정보를 가져오고, 클라이언트를 단순화 하기 위해서 변환하는 객체이다( EmbeddedDocument를 사용하는 것과 같은 것). 나는 적절하게 응답하는 쿼리 메소드가 문제들을 단순화하는 부분에 telling 하는 것에 코드가 얽히는 것을 보았다. 나에게는, tell-dont-ask 는 행동과 데이터를 함께 위치시키는 것으로 나아가는 디딤돌이지만, 강조 할 가치가있는 부분은 아니다. 

 -> 뭐라는지 모르겠지만 암튼 본인은 그대로는 안쓴다는 듯



Further Reading 더 읽을 것


This principle is most often associated with Andy Hunt and "Prag" Dave Thomas (The Pragmatic Programmers). They describe it in a IEEE Software column and a post on their website.


Notes 노트..


1: And indeed even the more fundamental principle of co-locating data and behavior should sometimes be dropped in favor of other concerns - such as layering. Good design is all about trade-offs, and co-locating data and behavior is just one factor to bear in mind.


 그리고 대체로 데이터와 동작을 같이 위치시키는 더 기본적인 원리는 다른 염려를 떨쳐야 한다 (layering 과 같은). 좋은 디자인은 모두 트레이드에 관한 것이고 (거래), 같은 위치에 데이터와 동작을 두는 것은 단지 한가지 요소일 뿐이라는 것을 명심해라.




Something else you might like...?





2018/12/26 - [Programming/Software Architecture] - Perfecting OO's Small Classes and Short Methods. 완벽한 객체지향의 작은 클래스와 짧은 메소드, Book:ThoughtWorks Anthology, Java,cpp,자바,oop,좋은코드,객체지향프로그래밍



2018/12/28 - [Algorithm/Code Fights (Code Signal)] - Aracade Intro #49 lineEncoding. Algorithm, 알고리즘 문제풀이, Codefights, CodeSignal, 코드파이트, 코드시그널, 예제, example, c++ java c# scalar

2018/12/26 - [Algorithm/Code Fights (Code Signal)] - Aracade Intro #48 isDigit. Algorithm, 알고리즘, Codefights, CodeSignal, 코드파이트, 코드시그널, 예제, example, c++ java c# scalar

2018/12/26 - [Algorithm/Code Fights (Code Signal)] - Aracade Intro #47 isMAC48Address. Algorithm, 알고리즘, Codefights, CodeSignal, 코드파이트, 코드시그널, 예제, example, c++ java c# scalar

2018/12/25 - [Algorithm/Code Fights (Code Signal)] - Aracade Intro #46 electionsWinners. Algorithm, 알고리즘, Codefights, CodeSignal, 코드파이트, 코드시그널, 예제, example, c++ java c# scalar



2018/12/26 - [Life/Health care] - Selenium 셀레늄 usage/side effects/dosage 효능/부작용/성인,소아 용법

2018/12/27 - [Life/Health care] - Milk-Thistle 밀크시슬 usage/side effects/dosage/fatigue/supplement,효능/부작용/성인,소아 용법/건강/피로회복/영양제



2018/12/21 - [Programming/Design Pattern ] - What is, How to express Classdiagram relationships, 클래스다이어그램 관계선 종류, 그리기 / java,cpp,c++,designpattern,디자인패턴


2018/12/21 - [Programming/Programming Language] - Scala Advantages & Disadvantages 스칼라 장단점, 객체지향, 함수적, 절차지향적, 프로그래밍언어


2018/12/18 - [Programming/Java] - How to access controller from existing Pane in JavaFX, pane에서 해당 controller로 접근하기, java/cpp/c++/fx/gui