C# 其中';这是进行验证的最佳地点。。。构造函数还是留给客户来调用?
这确实是一个一般性的问题(可能也是一个更主观的问题)。我有一些类,在这些类中,我使用接口来定义验证对象状态的标准方法。当我这么做的时候,我开始抓挠我的头。。。最好是 1.)允许构造函数(或初始化方法)自动静默过滤错误信息,或。。。 2.)但是,是否允许客户端实例化对象,并允许客户端在继续之前调用接口的IsValid属性或Validate()方法 基本上,一种方法是沉默的,但可能会产生误导,因为客户可能不知道某些信息由于不符合验证标准而被过滤掉。那么,另一种方法会更直接,但也会增加一两个步骤?这里典型的是什么 好吧,经过一天的努力,我终于想出了一个例子。请原谅我,因为这并不理想,也不是什么美妙的事情,但希望我的发球足够好,能够让对方明白这一点。我目前的项目太复杂了,无法为这个做一些简单的事情,所以我编了一些东西。。。相信我。。。完全是虚构的 好的,示例中的对象如下: 客户端:表示客户端代码(控制台应用程序btw) IValidationInfo:这是我在当前项目中使用的实际界面。它允许我为“后端”对象创建一个验证框架,因为业务逻辑可能足够复杂,因此不一定要供客户机使用。这还允许我根据业务逻辑的需要分离验证代码和调用 OrderManager:这是客户端代码可以用来管理订单的对象。可以说,这对客户很友好 订单规范:这是客户端代码可以用来请求订单的对象。但是,如果业务逻辑不起作用,可以引发异常(或者如果必要,不添加顺序,忽略异常…)在我的实际示例中,我实际上有一个对象,它不是完全黑白的,不知道它会走到这道栅栏的哪一边。。。因此,当我意识到可以将验证请求(调用IsValid或Validate())推送到cilent时,我最初的问题是 客户描述:表示我已分类的客户(假装从数据库中读取) 产品:表示也被分类的特定产品 OrderDescription:表示正式的订单请求。业务规则是,客户不能订购任何未分类的商品(我知道……这不是很现实,但它给了我一些可以处理的东西……) 好的……我刚刚意识到我不能在这里附加文件,所以这里是代码。我为它的冗长外观道歉。这是我能做的最好的事情,使用我的验证界面创建一个客户端友好的前端和业务逻辑后端: 公共类客户端 { 静态OrderManager orderMgr=new OrderManager()C# 其中';这是进行验证的最佳地点。。。构造函数还是留给客户来调用?,c#,validation,C#,Validation,这确实是一个一般性的问题(可能也是一个更主观的问题)。我有一些类,在这些类中,我使用接口来定义验证对象状态的标准方法。当我这么做的时候,我开始抓挠我的头。。。最好是 1.)允许构造函数(或初始化方法)自动静默过滤错误信息,或。。。 2.)但是,是否允许客户端实例化对象,并允许客户端在继续之前调用接口的IsValid属性或Validate()方法 基本上,一种方法是沉默的,但可能会产生误导,因为客户可能不知道某些信息由于不符合验证标准而被过滤掉。那么,另一种方法会更直接,但也会增加一两个步骤?这里
static void Main(字符串[]args)
{
//请求新订单
//注意:客户机仅使用OrderManager和OrderSpecification作为
//客户不必了解和理解超出这一点的框架。
OrderSpecification orderSpec=新的订单规格(“Customer1”,新产品(IndustryCategory.FoodService,“自动售货项目”);
orderMgr.SubmiterRequest(orderSpec);
WriteLine(“OrderManager有{1}个客户的{0}个项目。”,orderMgr.ProductCount,orderMgr.CustomerCount);
//现在添加第二项,证明为现有客户添加的业务逻辑是有效的
WriteLine(“为同一客户添加另一个有效项目”);
orderSpec=新订单规范(“客户1”,新产品(IndustryCategory.FoodServices,“苏打”);
orderMgr.SubmiterRequest(orderSpec);
WriteLine(“OrderManager现在有{1}个客户的{0}个项目。”,orderMgr.ProductCount,orderMgr.CustomerCount);
WriteLine(“为新客户添加新的有效订单”);
orderSpec=新订单规范(“客户2”,新产品(IndustryCategory.Residential,“杂志”);
orderMgr.SubmiterRequest(orderSpec);
WriteLine(“OrderManager现在有{1}个客户的{0}个项目。”,orderMgr.ProductCount,orderMgr.CustomerCount);
Console.WriteLine(“添加无效项将无法工作,因为客户未设置为接收此类项目。应获得异常消息…”);
尝试
{
orderSpec=新订单规范(“客户3”,新产品(IndustryCategory.Residential,“杂志”);
orderMgr.SubmiterRequest(orderSpec);
}
捕获(例外情况除外)
{
控制台写入线(例如消息);
}
Console.ReadLine();
}
}
公共接口IValidationInfo
{
字符串[]ValidationItems{get;}
bool是有效的{get;}
void Validate();
列出GetValidationErrors();
字符串GetValidationError(字符串itemName);
}
公共类OrderManager
{
私有列表_orders=新列表();
公开名单命令
{
获取{返回新列表(_顺序);}
私有集{u orders=value;}
}
公共整数产品计数
{
得到
{
int itemCount=0;
this.Orders.ForEach(o=>itemCount+=o.Products.Count);
返回项目计数;
}
}
公共整数客户计数
{
得到
{
//因为每个订单只有一个客户,所以只需返回订单数量即可
返回此.Orders.Count;
}
}
static void Main(string[] args)
{
//Request a new order
//Note: Only the OrderManager and OrderSpecification are used by the Client as to keep the
// Client from having to know and understand the framework beyond that point.
OrderSpecification orderSpec = new OrderSpecification("Customer1", new Product(IndustryCategory.FoodServices, "Vending Items"));
orderMgr.SubmitOrderRequest(orderSpec);
Console.WriteLine("The OrderManager has {0} items for {1} customers.", orderMgr.ProductCount, orderMgr.CustomerCount);
//Now add a second item proving that the business logic to add for an existing customer works
Console.WriteLine("Adding another valid item for the same customer.");
orderSpec = new OrderSpecification("Customer1", new Product(IndustryCategory.FoodServices, "Sodas"));
orderMgr.SubmitOrderRequest(orderSpec);
Console.WriteLine("The OrderManager now has {0} items for {1} customers.", orderMgr.ProductCount, orderMgr.CustomerCount);
Console.WriteLine("Adding a new valid order for a new customer.");
orderSpec = new OrderSpecification("Customer2", new Product(IndustryCategory.Residential, "Magazines"));
orderMgr.SubmitOrderRequest(orderSpec);
Console.WriteLine("The OrderManager now has {0} items for {1} customers.", orderMgr.ProductCount, orderMgr.CustomerCount);
Console.WriteLine("Adding a invalid one will not work because the customer is not set up to receive these kinds of items. Should get an exception with message...");
try
{
orderSpec = new OrderSpecification("Customer3", new Product(IndustryCategory.Residential, "Magazines"));
orderMgr.SubmitOrderRequest(orderSpec);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
Console.ReadLine();
}
}
public interface IValidationInfo
{
string[] ValidationItems { get; }
bool IsValid { get; }
void Validate();
List<string> GetValidationErrors();
string GetValidationError(string itemName);
}
public class OrderManager
{
private List<OrderDescription> _orders = new List<OrderDescription>();
public List<OrderDescription> Orders
{
get { return new List<OrderDescription>(_orders); }
private set { _orders = value; }
}
public int ProductCount
{
get
{
int itemCount = 0;
this.Orders.ForEach(o => itemCount += o.Products.Count);
return itemCount;
}
}
public int CustomerCount
{
get
{
//since there's only one customer per order, just return the number of orders
return this.Orders.Count;
}
}
public void SubmitOrderRequest(OrderSpecification orderSpec)
{
if (orderSpec.IsValid)
{
List<OrderDescription> orders = this.Orders;
//Since the particular customer may already have an order, we might as well add to an existing
OrderDescription existingOrder = orders.FirstOrDefault(o => string.Compare(orderSpec.Order.Customer.Name, o.Customer.Name, true) == 0) as OrderDescription;
if (existingOrder != null)
{
List<Product> existingProducts = orderSpec.Order.Products;
orderSpec.Order.Products.ForEach(p => existingOrder.AddProduct(p));
}
else
{
orders.Add(orderSpec.Order);
}
this.Orders = orders;
}
else
orderSpec.Validate(); //Let the OrderSpecification pass the business logic validation down the chain
}
}
public enum IndustryCategory
{
Residential,
Textile,
FoodServices,
Something
}
public class OrderSpecification : IValidationInfo
{
public OrderDescription Order { get; private set; }
public OrderSpecification(string customerName, Product product)
{
//Should use a method in the class to search and retrieve Customer... pretending here
CustomerDescription customer = null;
switch (customerName)
{
case "Customer1":
customer = new CustomerDescription() { Name = customerName, Category = IndustryCategory.FoodServices };
break;
case "Customer2":
customer = new CustomerDescription() { Name = customerName, Category = IndustryCategory.Residential };
break;
case "Customer3":
customer = new CustomerDescription() { Name = customerName, Category = IndustryCategory.Textile };
break;
}
//Create an OrderDescription to potentially represent the order... valid or not since this is
//a specification being used to request the order
this.Order = new OrderDescription(new List<Product>() { product }, customer);
}
#region IValidationInfo Members
private readonly string[] _validationItems =
{
"OrderDescription"
};
public string[] ValidationItems
{
get { return _validationItems; }
}
public bool IsValid
{
get
{
List<string> validationErrors = GetValidationErrors();
if (validationErrors != null && validationErrors.Count > 0)
return false;
else
return true;
}
}
public void Validate()
{
List<string> errorMessages = GetValidationErrors();
if (errorMessages != null && errorMessages.Count > 0)
{
StringBuilder errorMessageReported = new StringBuilder();
errorMessages.ForEach(em => errorMessageReported.AppendLine(em));
throw new Exception(errorMessageReported.ToString());
}
}
public List<string> GetValidationErrors()
{
List<string> errorMessages = new List<string>();
foreach (string item in this.ValidationItems)
{
string errorMessage = GetValidationError(item);
if (!string.IsNullOrEmpty(errorMessage))
errorMessages.Add(errorMessage);
}
return errorMessages;
}
public string GetValidationError(string itemName)
{
switch (itemName)
{
case "OrderDescription":
return ValidateOrderDescription();
default:
return "Invalid item name.";
}
}
#endregion
private string ValidateOrderDescription()
{
string errorMessage = string.Empty;
if (this.Order == null)
errorMessage = "Order was not instantiated.";
else
{
if (!this.Order.IsValid)
{
List<string> orderErrors = this.Order.GetValidationErrors();
orderErrors.ForEach(ce => errorMessage += "\n" + ce);
}
}
return errorMessage;
}
}
public class CustomerDescription : IValidationInfo
{
public string Name { get; set; }
public string Street { get; set; }
public string City { get; set; }
public string State { get; set; }
public int ZipCode { get; set; }
public IndustryCategory Category { get; set; }
#region IValidationInfo Members
private readonly string[] _validationItems =
{
"Name",
"Street",
"City",
"State",
"ZipCode",
"Category"
};
public string[] ValidationItems
{
get { return _validationItems; }
}
public bool IsValid
{
get
{
List<string> validationErrors = GetValidationErrors();
if (validationErrors != null && validationErrors.Count > 0)
return false;
else
return true;
}
}
public void Validate()
{
List<string> errorMessages = GetValidationErrors();
if (errorMessages != null && errorMessages.Count > 0)
{
StringBuilder errorMessageReported = new StringBuilder();
errorMessages.ForEach(em => errorMessageReported.AppendLine(em));
throw new Exception(errorMessageReported.ToString());
}
}
public List<string> GetValidationErrors()
{
List<string> errorMessages = new List<string>();
foreach (string item in this.ValidationItems)
{
string errorMessage = GetValidationError(item);
if (!string.IsNullOrEmpty(errorMessage))
errorMessages.Add(errorMessage);
}
return errorMessages;
}
public string GetValidationError(string itemName)
{
//Validation methods should be called here... pretending nothings wrong for sake of discussion & simplicity
switch (itemName)
{
case "Name":
return string.Empty;
case "Street":
return string.Empty;
case "City":
return string.Empty;
case "State":
return string.Empty;
case "ZipCode":
return string.Empty;
case "Category":
return string.Empty;
default:
return "Invalid item name.";
}
}
#endregion
}
public class Product
{
public IndustryCategory Category { get; private set; }
public string Description { get; private set; }
public Product(IndustryCategory category, string description)
{
this.Category = category;
this.Description = description;
}
}
public class OrderDescription : IValidationInfo
{
public CustomerDescription Customer { get; private set; }
private List<Product> _products = new List<Product>();
public List<Product> Products
{
get { return new List<Product>(_products); }
private set { _products = value; }
}
public OrderDescription(List<Product> products, CustomerDescription customer)
{
this.Products = products;
this.Customer = customer;
}
public void PlaceOrder()
{
//If order valid, place
if (this.IsValid)
{
//Do stuff to place order
}
else
Validate(); //cause the exceptions to be raised with the validate because business rules were broken
}
public void AddProduct(Product product)
{
List<Product> productsToEvaluate = this.Products;
//some special read, validation, quantity check, pre-existing, etc here
// doing other stuff...
productsToEvaluate.Add(product);
this.Products = productsToEvaluate;
}
#region IValidationInfo Members
private readonly string[] _validationItems =
{
"Customer",
"Products"
};
public string[] ValidationItems
{
get { return _validationItems; }
}
public bool IsValid
{
get
{
List<string> validationErrors = GetValidationErrors();
if (validationErrors != null && validationErrors.Count > 0)
return false;
else
return true;
}
}
public void Validate()
{
List<string> errorMessages = GetValidationErrors();
if (errorMessages != null && errorMessages.Count > 0)
{
StringBuilder errorMessageReported = new StringBuilder();
errorMessages.ForEach(em => errorMessageReported.AppendLine(em));
throw new Exception(errorMessageReported.ToString());
}
}
public List<string> GetValidationErrors()
{
List<string> errorMessages = new List<string>();
foreach (string item in this.ValidationItems)
{
string errorMessage = GetValidationError(item);
if (!string.IsNullOrEmpty(errorMessage))
errorMessages.Add(errorMessage);
}
return errorMessages;
}
public string GetValidationError(string itemName)
{
switch (itemName)
{
case "Customer":
return ValidateCustomer();
case "Products":
return ValidateProducts();
default:
return "Invalid item name.";
}
}
#endregion
#region Validation Methods
private string ValidateCustomer()
{
string errorMessage = string.Empty;
if (this.Customer == null)
errorMessage = "CustomerDescription is missing a valid value.";
else
{
if (!this.Customer.IsValid)
{
List<string> customerErrors = this.Customer.GetValidationErrors();
customerErrors.ForEach(ce => errorMessage += "\n" + ce);
}
}
return errorMessage;
}
private string ValidateProducts()
{
string errorMessage = string.Empty;
if (this.Products == null || this.Products.Count <= 0)
errorMessage = "Invalid Order. Missing Products.";
else
{
foreach (Product product in this.Products)
{
if (product.Category != Customer.Category)
{
errorMessage += string.Format("\nThe Product, {0}, category does not match the required Customer category for {1}", product.Description, Customer.Name);
}
}
}
return errorMessage;
}
#endregion
}