一个类应该验证自己还是创建另一个类进行验证? [英] Should a class validate itself or create another class to validate it?

查看:68
本文介绍了一个类应该验证自己还是创建另一个类进行验证?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个类似的课程:

Let's say I have a class like:

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

,如果我想创建一个方法:

and if I want to create a method:

const bool validate() const;

基本上可以验证这4个字段是否包含有效值.

which basically validates whether the 4 fields contain valid values.

validate()应该是NavigationData类的一部分,还是应该创建类似NavigationDataValidator的东西,其中包含validate(const NavigationData&)方法.

Should validate() be part of NavigationData class, or should I create something like a NavigationDataValidator, that contains a validate(const NavigationData&) method.

我只是举一个简单的例子,显然我的真实课堂比这要复杂得多.我正在寻找良好的面向对象原则.

I'm just giving a simple example, obviously my real class is a lot more complicated than this. I'm looking for good OO principles.

换一种说法:给定一个方法,我们如何知道它应该属于该类还是应该属于一个单独的类?

Put it another way: given a method, how do we know if it should belong to the class, or should belong to a separate class?

推荐答案

通常,类有责任确保它在逻辑上保持一致和有效的内部状态.例如,如果Person的操作在没有此数据的情况下毫无意义,则Person可能需要一个名字和姓氏的构造函数.

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.

但是,逻辑上一致且有效" 在域内有意义" 不同,因此有时,外部类负责确保遵守域规则.例如,PersonValidator可能要求Person具有在美国的电话号码.但是Person不一定需要了解PhoneNumber是否在美国.

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.

一个好的经验法则是,如果除了已经属于该类的数据之外,还需要类外部的状态或域规则,您将要考虑进行外部验证.如果该类实例的状态可能来自多个来源(例如,数据库,Web表单,文件等),您可能还希望将验证集中在一个外部类中.

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.).

这篇关于一个类应该验证自己还是创建另一个类进行验证?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆