Are type fields pure evil?

后端 未结 9 1335
旧巷少年郎
旧巷少年郎 2021-02-06 16:27

As discusses in The c++ Programming Language 3rd Edition in section 12.2.5, type fields tend to create code that is less versatile, error-prone, less intuitive, and less maintai

9条回答
  •  余生分开走
    2021-02-06 17:20

    My take is: It depends.

    A parameterized Factory Method design pattern relies on this technique.

    class Creator {
        public:
            virtual Product* Create(ProductId);
    };
    
    Product* Creator::Create (ProductId id) {
            if (id == MINE)  return new MyProduct;
            if (id == YOURS) return new YourProduct;
            // repeat for remaining products...
    
            return 0;
    }
    

    So, is this bad. I don't think so as we do not have any other alternative at this stage. This is a place where it is absolutely necessary as it involves creation of an object. The type of the object is yet to be known.

    The example in OP is however an example which sure needs refactoring. Here we are already dealing with an existing object/type (passed as argument to function).

    As Herb Sutter mentions -

    "Switch off: Avoid switching on the type of an object to customize behavior. Use templates and virtual functions to let types (not their calling code) decide their behavior."

提交回复
热议问题