验证是否应该更改数据?

我有一些用于验证的服务。它们包含简单的数据验证和一些更复杂的业务逻辑的组合。其中一些验证调用还会“清理”数据,使其符合我们的标准。这似乎应该在其他地方完成(单一责任)。

我对验证数据的理解是,它只是回答是/否问题(是否有效)并可能返回一些验证消息。因此它将返回一个布尔值或某种类型的验证错误。

如果我们想在保存或处理之前格式化数据,我们应该有另一层代码来清理数据格式。

看看下面的例子。我们有两种方法来检查字符串的长度。如果长度正确,第二个还会将其转换为上部。因此,它会在其过程中更改字符串。

问题:我的核心问题是,在谈论验证时,我们是否应该关心清理/格式化数据?换句话说,验证是否应该改变数据?

public class ValidationService

{

    public bool ValidateText(string text)

    {

        bool rtn = false;


        if (IsStringCorrectLength(text))

        {

            rtn = true;

        }


        return rtn;

    }


    public bool ValidateTextAndFormat(string text)

    {

        bool rtn = false;


        if (IsStringCorrectLength(text))

        {

            text = text.ToUpper();

            rtn = true;

        }


        return rtn;

    }


    private bool IsStringCorrectLength(string text)

    {

        bool rtn = false;

        if (text.Length < 11)

        {

            rtn = true;

        }


        return rtn;

    }

}


烙印99
浏览 78回答 2
2回答

一只萌萌小番薯

当你“闻到”这应该是单独的问题。验证问题操纵/标准化问题这将防止调用验证时的复杂性和“奇怪”的副作用(更改数据),并且它确保验证只关心检查验证而不关心“如何”格式化数据。如果您将它们连接在一起,那么您将无法“重用”这些组件,甚至无法干净地测试它们。它还会鼓励您在验证中添加更多操作和业务逻辑,并慢慢地削弱您的开发。

慕容3067478

也许这就是您想要采取的方法:public class ValidationService{&nbsp; &nbsp; private const int MaximumStringLength = 11;&nbsp; &nbsp; public bool IsStringValid(string text)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; return IsStringLengthCorrect(text) && IsStringUpper(text);&nbsp; &nbsp; }&nbsp; &nbsp; public bool IsStringLengthCorrect(string text)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; return text.Length < MaximumStringLength;&nbsp; &nbsp; }&nbsp; &nbsp; public bool IsStringUpper(string text)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; return text.All(x => char.IsUpper(x));&nbsp; &nbsp; }&nbsp; &nbsp; public string ValidateStringLength(string text)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; if (IsStringLengthCorrect(text))&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return text;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; else&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return text.Substring(0, MaximumStringLength);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; public string ValidateStringUpper(string text)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; if (IsStringUpper(text))&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return text;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; else&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return text.ToUpper();&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}在我看来,验证类应该只检查并返回文本是否有效。无论如何,通过良好的命名、顺序和方法,您可以提供返回有效输入的方法。
打开App,查看更多内容
随时随地看视频慕课网APP