在哪里提供验证的逻辑规则 [英] Where to provide logic rules for validation

查看:270
本文介绍了在哪里提供验证的逻辑规则的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个文件导出器,并将字段类型验证为字符串,日期等+还有每行的字段计数。

I have a file exporter and validate the field types as strings, dates etc + also the field count of each row.

现在,保留规则对于这样的逻辑,使得负责创建csv的类是通用的,并且与任何业务逻辑分离,并且业务需要改变,那么导出的类不需要修改。

Now, where would one keep the rules for such logic so that the class responsible for creating the csv is generic and decoupled from any business logic and that should business needs change then the exported class need never be amended.

我曾经想过创建一个用于业务逻辑的第二个类,但这将需要以下几点:我同样认为:

I had though about creating a second class used for business logic but that would require the following - both equally as bad i think:


  • 硬编码类中的规则

  • 要传递给构造函数的规则

似乎没有良好的解决方案,但这必定是一个常见的问题?

There doesn seem to be a good solution but this must be a common problem?

推荐答案

像往常一样依赖..

数据的责任在于提供商。如上所述,fileExporter将导出文件,如果数据提供者被密封,那么显然,您将创建一个验证器来声明数据,随后断言的数据将被传递到文件导出器。

responsiblity of the data lies with the provider. "fileExporter" as mentioned will export the file, if the data provider is sealed then obviously you would have create an validator which will assert the data, subsequently the asserted data would be passed to the file exporter.

如果没有密封,您可以注入依赖关系。

If it is not sealed you could inject dependencies into it.

ie

class DataProvider(IDataValidator dataValidator, IFileFormat fileFormat){...}
interface IFileFormat { void Export();}
interface IDataValidator { void AsserData(); }
class CSVDataValidator : IDataValidator{...}
class CSVFileExporter : IFileExporter {..}

var dataValidator = new CSVDataValidator();
var iFileFormat = new CSVFileFormat();
var dataProvider = new DataProvider(dataValidator, fileFormat);
var data = dataProvider.Data;
var csvFileExporter = new CSVFileExporter(data)
csvFileExporter.Export();

基本上的可能性是无止境的,只是取决于你想要关闭什么你希望在将来扩展什么

basically the possibilities are endless, it just depends what it is you would like to close and what is it that you wish to extend in the future

我会阅读策略/依赖注入/开放原则

I would read upon strategy / dependency injection / open close principle

这篇关于在哪里提供验证的逻辑规则的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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