Program Responsibility

In a business, what happens when nobody is responsible for restocking a product, buying toilet paper or making the daily deposit? The company obviously doesn't work very well. In fact, the best system is to have a single person responsible for any one thing, at any one time. No confusion about who should do what and who to blame if the service isn't done properly.

The most important part of Object Oriented Programming is to provide an "authority" to look after some group of data. If the data in an object isn't correct, you only need to look at the local functions that are responsible for that data. This property of OOP is called "encapsulation" and it is the most important attribute of that paradigm.

Some people's dislike of global variables comes from this same "program responsibility" idea. Who is looking after the changing of the global variable if anyone can do that from anywhere? An interesting point is that a global variable that is only read from anywhere, doesn't cause a problem. The singular responsibility problem only occurs when multiple people try to change the variable. This is also true when dealing with shared memory in a multi-core computer (you only need a lock if you need to sequence multiple entities changing the data). So the problem with global variables isn't so much the global nature of the variable but having no single entity with the authority to change the variable.

If you have a global service that contains a variable and you allow messages from anywhere that can read and/or change that variable, is that the same as a global variable? As with global variables, reading the value through this service causes no problem but changing that value from anywhere with a message does break the "one entity responsible" rule. I don't think this kind of situation can be eliminated in all cases but a programmer should be aware of the this problem and minimize it as much as possible. At least in the case of a service, you only have to look at the local code that is actually changing the variable, if there is a problem but that still doesn't tell you where the mistaken source message came from.

The idea of having a single entity responsible for changing all data is a fundamental best practice and should be implemented in all programming paradigm's including OOP, functional and all other systems.

Summary:


EditText of this page (last edited November 20, 2013) or FindPage with title or text search