A security capsule can save your program’s life (Part.2)

In the previous post we have created an application. But there was a little bug in our program. Let’s find the bug. How about we run the program once again? And this time we provide the TextBoxes with some information and uncheck the Private CheckBox to see the mobile number of the user and click submit. Oops!!! It is still “N/A” in the ListView’s mobile column but it was not what we expected, Right!!! Cause we unchecked the Private CheckBox in the form. So what was the problem? The problem was not with our UI but with the implementation of our code. Let me show you where we actually made a mistake. Recall that we explicitly set the Boolean value of HideMobileNo to true. Now go back to our code behind the Form. Look carefully from the top. See that in the Form constructor we have instantiated a user object and gave some values for the fields so that at runtime at least one item is placed in the ListView control. Now go to our code of the Submit button. See that we are again instantiating the user object but now we are sending the values for the object’s field from respective TextBoxes. At last when we go to our CheckBox’s checked changed event we can see that we are passing the current check state of our CheckBox to user.SetMobileAsPublic method. If you have got this far then you know what the problem really is. The problem occurs actually when we create an instance of user object in the submit button’s code but didn’t set the Boolean field HideMobileNo to false if someone unchecked the Private CheckBox. What we really did here is we completely rely on our CheckBox’s check changed event. But if we look carefully we will see that we are not setting the HideMobileNo field of our object created in the button code to a true value rather we have actually done it for the object we have just created in the Form constructor. So when we submit a new user object in our program we may or may not change the Private CheckBox state in the UI but we accidently change the HideMobileNo field value of previously created object. So we never get a mobile number when we unchecked the Private CheckBox rather we always get a “N/A” in the ListView’s Phone column.

Here we didn’t intended to face such a bug but at the end of the day we did have one in our program. That’s because programs always don’t run in the way that we want it to be. And we introduce bugs in program in the process of doing so without taking cautions.

To overcome such problems object oriented programming (OOP) introduces a concept called Encapsulation. As with the name goes, we simply encapsulate our field variables with the help of some methods. The methods are actually a way of setting/getting values of our field variables.

So, in the next post I will show you how can we implement encapsulation in our code. Till then stay tuned.