- Delphi Cookbook
- Daniele Spinetti Daniele Teti
- 262字
- 2025-04-04 16:22:47
Getting ready
Referring to duck typing, Wikipedia (http://en.wikipedia.org/wiki/Duck_typing) gives the following explanation :
How can all these concepts be used in everyday programming? This is the question that this recipe aims to answer.
Let's say that you have a form, and you want to inform the user that something bad happened by changing all the colorable components to clRed. You don't know what the property Color means for any control that has that property, you only want to set all the properties named Color to clRed. How can you achieve this? The naive approach could be to cycle the Components property, check whether the current control is a control that you know has a Color property, and then cast that control reference to an actual TEdit (or TComboBox, TListBox, or whatever) reference, and change the Color property to clRed; however, what if tomorrow you need to color another kind of control as well? Or you have to change the Color property on TPanel, but the Font.Color property on TEdit? You get the point, I think. Using the naive approach can raise the complexity of your code. A programmer should hate complexity. More complexity means more time dealing with code, and more time means more money to spend. As usual, the KISS approach is the best one—Keep It Simple, Stupid!