15 Şubat 2018 Perşembe

Tell, Don't Ask Kuralı

Giriş
Bu kural 3 varsayım ile geliyor. Bunlar şöyle.
1. You're using objects.
2. Your objects have state.
3. The state of your objects affects their behavior.
Tell, Don't Ask kuralı başka nesnenin iç durumuna erişme diyor. Açıklaması şöyle.
Allow your class to manage its own state. Don't ask it for its state, and then take action based on that state. Tell the class what you want, and let it decide what to do based on its own state.
Bir başka açıklama şöyle.
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 us to move behavior into an object to go with the data.
Örnek
Şu kod kuralı ihlal eder.
var color = trafficLight.Color;
var elapsed = trafficLight.Elapsed;
If (color == Color.Red && elapsed > 2.Minutes)
    trafficLight.ChangeColor(green);
Düzeltmek için şöyle yaparız.
var result = trafficLight.ChangeColor(Color.Green);


Hiç yorum yok:

Yorum Gönder