繁体   English   中英

验证实体使用值的性能问题 object

[英]The performance issue of validating entity using value object

我有以下值 object 代码,它通过一些昂贵的数据库操作验证 CustCode。

public class CustCode : ValueObject<CustCode>
{
    private CustCode(string code) { Value = code; }

    public static Result<CustCode> Create(string code)
    {
        if (string.IsNullOrWhiteSpace(code))
            return Result.Failure<CustCode>("Code should not be empty");

        // validate if the value is still valid against the database. Expensive and slow
        if (!ValidateDB(code)) // Or web api calls
            return Result.Failure<CustCode>("Database validation failed.");

        return Result.Success<CustCode>(new CustCode(code));
    }

    public string Value { get; }

    // other methods omitted ...
}

public class MyEntity 
{
    CustCode CustCode { get; }
    ....

当只有一个或几个实体实例具有该类型时,它工作正常。 但是,对于像GetAll()这样返回大量具有该类型的实体的方法,它变得非常慢。

public async IAsyncEnumerable<MyEntity> GetAll()
{
    string line;
    using var sr = File.OpenText(_config.FileName);
    while ((line = await sr.ReadLineAsync()) != null)
    {
        yield return new MyEntity(CustCode.Create(line).Value); // CustCode.Create called many times
    }
}

由于文件中的数据在保存之前已经过验证,因此实际上没有必要再次验证。 是否应该创建另一个不验证要创建的值的Create function? DDD 惯用的方法是什么?

我通常尝试不让域调用来检索任何其他数据。 应该传递域完成其工作所需的一切。

由于值对象表示不可变状态,因此一旦成功创建,值就可以了。 为此,也许可以在集成/应用程序“层”中执行初始数据库验证,然后仅使用提供的值创建CustCode

只是想为@Eben Roux 的回答补充一点:

在许多情况下,数据库查询的验证结果取决于运行查询的时间。

例如,当您想检查电话号码是否存在某些产品是否有货时 这些查询的答案可以随时更改,但不适合允许或阻止创建值 object。

您可以创建一个“有效的”object,即(不知不觉地)在下一秒(或相反)变得无效。 那么,如果验证结果不可靠,为什么还要运行昂贵的验证呢?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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