⬆️ ⬇️

How Non-Member Functions Improve Encapsulation (C ++)

Scrolling through old magazines and stumbled upon Scott Meyers, a well-known in narrow circles article : How to improve the encapsulation . If someone has not read it yet, be sure to read it.

The idea is clear and true there, but still, in my opinion, there is a big understatement in the article.

In short, in this article, Meyers argues that removing functions from a class always makes code more encapsulated.



It is difficult to disagree with this in the general case. However, if we simply brought the functions out of the class and left them open, then what did we actually win? We simplified the class and made it more reliable and simple, but on the other hand, we really complicated its interface, because Now its interface is scattered in different places, and not concentrated inside the class. A programmer using this class will have to remember that some of the functions are in the class, and some are outside of it. This will only complicate the work of this programmer.

About this problem in the article said a little, but not enough.



IMHO, writing non-class members makes sense if and only if this function can be hidden and made inaccessible to clients of the class.

Such a function can be declared and implemented only in a cpp file, a bunch of code can be written in it, and the client will not even know about it - this is a great encapsulation and a great alternative to declaring such a function in a private section. Because Any function in the private section is also an actual class interface, often an extra interface.

One of the advantages of this approach is that there are almost no private methods left in the classes, since they all become static functions in the cpp file. And only interface public functions remain in the class. This means that the next change in the implementation of a class will have a much smaller effect on customers of the class.



Do you remove unnecessary functions from the class interface?

What other methods do you use to increase class encapsulation?


')

Source: https://habr.com/ru/post/39202/



All Articles