OOP 420 No Scope

Scope is important.

If you don’t limit the visibility of variables you quickly have code that is unruly and hard to debug. By having all variables accessible from everywhere you create a number of problems including an inability to re-use variable names and variables being directly accessible from outside of a its own class.

Diagram illustrating the visibility of various types of variables. God bless alliteration.

An example might better help me explain, lets say you have a biscuit tin object. The biscuit tin knows how many biscuits its has in it and stores this in a variable. The way you get a biscuit is by asking the tin for a tasty treat. In response the tin will return you a biscuit and lower its biscuit count by 1. Hooray, that all sounds nice. However if the biscuit tin variable is accessible from outside of the biscuit tin class, as a user I could simply set that variable to whatever I wanted and in the process create biscuits out of thin air or delete them from existence.

If you could reach in and change the number of biscuits in a tin at will

Now if I had the ability to wish biscuits into existence I would be working night and day building my confectionery Empire, as I’m instead writing this blog you can take it from me this isn't possible. Object Oriented Programming attempts to match real world behaviour as close as possible, since we cannot do this in real life, we shouldn't be able to do it in OOP. The returning of biscuits is a function of the tin and the number is biscuits in something that is private (no accessible outside the tin) to the tin. If we want to know how many biscuits are in the tin and if therefore to by that £2 Multi-pack of chocolate digestives while they are on offer we can kindly as the tin (tin.count_biscuits) how many biscuits it contains.

Much better.