Is encapsulation violated, if I use a global variable in a class member function's definition?

前提是你 提交于 2019-12-23 10:11:56

问题


I've been asked to explain what encapsulation is and I replied "bundling of data and functions that modify this data, is called encapsulation."

The answer was followed by another question—"So, by your definition if I modify a global variable from a member function of a class then the encapsulation is violated."

It made sense to answer YES.

I am not sure whether my explanation is wrong or following question is valid and my answer to it as YES is correct.

Can somebody help.


回答1:


Quoting from wikipedia:

In programming languages, encapsulation is used to refer to one of two related but distinct notions, and sometimes to the combination thereof:

  • A language mechanism for restricting access to some of the object's components.
  • A language construct that facilitates the bundling of data with the methods (or other functions) operating on that data

In my humble opinion the answer to the follow up question is subjective and it depends on the interpretation of the notion of encapsulation.

For example it's not a violation if the encapsulating data are limited to be the member variables of classes. A global variable that doesn't belong to an object is accessible by everyone and thus, accessing it via a member function doesn't consist any encapsulation violation.

On the other hand if you consider that encapsulation should be applied to your entire program then this global variable should have been bundled to an object and thus, raw access to it constitutes an encapsulation violation.

The bottom line is that the answer lies in the realms of theology, meaning that it depends on how encapsulation is interpreted by the different programming dogmas.




回答2:


This depends on how global variable defined and accessed.

Imagine header file containing declaration, but not definitions of member functions, and corresponding implementation file containing class members implementation.

Now consider global variable defined in this header file as internal linkage one (static). Or placed in unnamed namespace. It is a global variable, but functionally it does not differ from private static class member.

It is smelly code, but, I say, that variable is encapsulated properly:



来源:https://stackoverflow.com/questions/35818314/is-encapsulation-violated-if-i-use-a-global-variable-in-a-class-member-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!