Should a class validate itself or create another class to validate it?

后端 未结 8 778
梦毁少年i
梦毁少年i 2021-02-01 17:30

Let\'s say I have a class like:

class NavigationData
{
  float roll;
  float pitch;
  double latitude;
  double longitude;
}

and if I want to c

8条回答
  •  别那么骄傲
    2021-02-01 18:28

    Typically it is a class's own responsibility to ensure that it maintains a logically consistent and valid internal state. For instance, Person may have a constructor that requires both a first and last name if operations on Person are meaningless without this data.

    However, "logically consistent and valid" is different from "makes sense in the domain", so it is sometimes the responsibility of an external class to ensure that domain rules are obeyed. For example, PersonValidator may require that Person has a phone number which is in the US. But Person shouldn't necessarily need to know anything about whether or not a PhoneNumber is in the US.

    A good rule of thumb is that if state or domain rules external to the class are required in addition to the data that already belongs to the class, you will want to consider having external validation. You may also want to centralize validation in an external class if the state of the class's instances can come from multiple sources (e.g., database, web form, file, etc.).

提交回复
热议问题