Thinking about value object

Time:2020-7-15

useValue objectThe benefits of the model.

Generally, we use get and set methods to manipulate the properties in a class, which are very common and easy to use.

class MyClass {
public:
    MyClass();

    void setProperty1(const QString &value);
    QString getProperty1() const;

    void setProperty2(const QString &value);
    QString getProperty2() const;
}

   but we are not careful or third-party interface users in the process of manipulating classesMiscallThe set method causes theState changesThis is something we don’t want.

   classes should be restricted, so how. We can use it at this timeBuilder modeIt is a read-only object, but the builder pattern is used for comparisonTedious

   do you have a simpler oneRead only objectWhat about it?
The answer is yesValue objectThrough theConstructorcomeset a property

class MyClass {
public:
    MyClass(const QString &property1,
            const QString &perperty2);

    QString getProperty1() const;
    QString getProperty2() const;
};

   from the above code, we can see that the MyClass class no longer provides methods to set properties, but only provides read methods. If you need to set the MyClass in class attribute, you can only use theRecreateMyClass object mode to set, this method is very good to avoid being randomly modified by other people.

   this method is likeHTTP requestThe same,StatelessIt’s reassuring to use, but it has a fatal effectshortcomingIt is a constructor and cannot have too many arguments.

Recommended Today

ASP.NET Example of core MVC getting the parameters of the request

preface An HTTP request is a standard IO operation. The request is I, which is the input; the responsive o is the output. Any web development framework is actually doing these two things Accept the request and parse to get the parameters Render according to the parameters and output the response content So let’s learn […]