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

    I leafed through old magazines and stumbled upon Scott Meyers: How non-member functions improve encapsulation article, widely known in narrow circles . If someone has not read it yet, be sure to read it.
    The idea there is stated clear and true, but nevertheless, in my opinion there is a big understatement in the article.
    In brief, in this article, Meyers argues that taking functions out of a class always makes the code more encapsulated.

    It is difficult to disagree with this in the general case. However, if we simply took the functions out of the class and left them open, then what did we really win? We simplified the class and made it more reliable and simple, but on the other hand, we actually 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 it. This will only complicate the work of this programmer.
    The article says a little about this problem, but not enough.

    IMHO, writing functions not members of a class makes sense if and only if this function can be hidden and made inaccessible to class clients.
    Such a function can be declared and implemented only in a cpp file, you can write a bunch of code 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 actually the interface of the class, and often an extra interface.
    One of the advantages of this approach is that there are almost no private methods left in classes, because 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 the class will have a much lesser effect on the class clients.

    Do you remove unnecessary functions from the class interface?
    What other methods do you use to increase class encapsulation?

    Also popular now: