Encapsulation in Delphi
A note about encapsulation
The idea of encapsulation is literally ‘wrapping things up’ In this case we wrap up the complex workings of our code, the workings that we don’t want to be directly manipulated or read. Instead we provide an interface to the outside world. If someone wants to use our code they have to use the interface. The interface is public, the workings are private and are not visible to anyone but us. The interface is, in fact, a series of functions that we’ve written to do precisely this job – to translate between incoming requests and the real mechanics of the program. It’s our responsibility to make sure that the interface works. Provided that we do that, what we do in the private part is up to us. This means we can change it without worrying about breaking other people’s work, provided we keep the interface functional – they don’t even have to know. For example, the Windows operating system includes a public function to create a window on the screen. That function takes parameters such as the width, height etc. How exactly windows draws the screen, and even what the resulting window looks like (think of the difference between XP and Vista and Windows 7) we don’t know. That bit’s private. What matters is that whenever we call the function, we get a window – as wide and high as we specified. As a result we shouldn’t need to re-write all of our programs for every new version of Windows. It’s an important idea - particularly when we are writing pieces of code that need to co-operate, perhaps in a project or in a shared environment. It preserves flexibility for the programmer whilst maintaining a reliable and consistent approach to others. type |