Saturday, March 7, 2009

Programming: Closed/Open principle

Sounds confusing but its not.
Actually it is a great strategy when you apply it while coding.

It goes like this: when you write a class to do a particular job. Keep in mind that you do not want anybody to make changes to this class. Hence it is closed for any modifications.

However you should allow other programmers to add new features or change the flow of the behavior by extending the class. So you give away your class as black box to programmers with documentation. Then they extend your class and add actions to its method. Hence it is opened for extension.

Here is an example of a core class (pseudo code) written to switch off all the lights at your house. It is installed and wired with all your house lights.

Public Class TurnOffLights

Public Sub TurnOff()

// Some Code
End Sub

End Class

Now you want to add some behavior to this class to prompt you before switching off the light! You cannot modify the class but you can extend (inherit) it.

So we'll write another class.

Public Class TurnOffLightPrompt Extends TurnOffLights

Public Sub Overrides TurnOff()

//I Don't know what code is written up there in the base class but I can add my own

if (MsgBox("Are you sure?",vbYesNo") == vbNo) Then Exit Sub
MyBase.TurnOff () //Call the original turnoff

End Sub

End Class

You may want to read Head First Design Patterns, it just makes you fall in love with Object Oriented.