简体   繁体   中英

How do I need to change my program to use Open/close Principle?

What is the best way to rewrite this code so that the open/close principle is used? It's a method of my class:

void Entity::insertPropertyIfExists(std::string& name, std::string& value)
{
    else if (name == "Age")
        set_property("Age", std::make_shared<Age>(std::atoi(value.c_str())));
    else if (name == "City")
        set_property("City", std::make_shared<City>(value));
    //...
    else if (name == "Interests")
        set_property("Interests", std::make_shared<InterestList>(value));
}

And this is an example of a class for which you need to implement the open/close principle

class Property {
public:
    virtual int compare(Property& p) = 0;
    virtual ~Property() = default;
};

class City final : public Property {
public:
    City(std::string new_city);
    int compare(Property& p) override;
private:
    std::string city;
};

Please, show me some example on my code.

This question is not specific to c++, it would be better to be tagged as design question.

Nevertheless, regarding the question itself. Open/Close principal suggests that our design will be easy to extend but close modification. In other words, you want to extend your code functionality without effecting exiting functionality and code.

A good question to ask before suggesting modifications, is what is expected to be changed? Then, we will make sure our design encapsulates the parts the is changing/extending.

As stated above by @Mahesh Attarde, it seems that you want to make sure you can add new "property" without effecting existing properties functionality.

using factory method is indeed the right direction, for each string you should have a factory method that creates the proper property, that why when you want to add new property you don't need to change existing factory methods, but create a new one.

In my opinion, there is no going around the fact that some "HUB" will be needed to direct to the proper factory method according to the string identifier. However, you can make the code more closed to modification by using a "registration" method. Meaning registering string id and matching factory dynamically in some structure so that insertPropertyIfExists doesn't need to change for every new property. Still you will need to add registration for every new property, but that can be done in the "main" context, so that "entity" code is not effected and doesn't need even recompilation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM