Class design vs. IDE: Are nonmember nonfriend functions really worth it?

后端 未结 7 1069
面向向阳花
面向向阳花 2020-12-21 00:01

In the (otherwise) excellent book C++ Coding Standards, Item 44, titled \"Prefer writing nonmember nonfriend functions\", Sutter and Alexandrescu recommend

7条回答
  •  误落风尘
    2020-12-21 00:37

    It's true that external functions should not be part of the interface. In theory, your class should only contain the data and expose the interface for what it is intended and not utilitarian functions. Adding utility functions to the interface just grow the class code base and make it less maintainable. I currently maintain a class with around 50 public methods, that's just insane.

    Now, in reality, I agree that this is not easy to enforce. It's often easier to just add another method to your class, even more if you are using an IDE that can really simply add a new method to an existing class.

    In order to keep my classes simple and still be able to centralize external function, I often use utility class that works with my class, or even namespaces. I start by creating the class that will wrap my data and expose the simplest possible interface. I then create a new class for every task I have to do with the class.

    Example: create a class Point, then add a class PointDrawer to draw it to a bitmap, PointSerializer to save it, etc.

提交回复
热议问题