我可以使用规范设计模式来改进以下场景吗?我正在努力寻找如何实现它?
谢谢,
if (!string.IsNullOrEmpty(obj.Firstname) && !string.IsNullOrEmpty(obj.Lastname)
&& !string.IsNullOrEmpty(obj.Email)
&& !string.IsNullOrEmpty(obj.Username))
{
// do something
}
最佳答案
当然,规范可以隐藏这个条件。但如果这是您的代码的唯一问题,并且仅在一个地方检查此条件,我不会创建规范。即使重复此检查,我首先想到的是避免对象处于无效状态 - 即避免将 null
值分配给此属性。如果不可能,那么您可以询问用户它是否有效,而不是从用户那里获取值并在用户外部检查它们(Tell, Don't Ask Principle):
public bool IsValid // consider better name here
{
get
{
return !String.IsNullOrEmpty(Firstname) &&
!String.IsNullOrEmpty(Lastname) &&
!String.IsNullOrEmpty(Email) &&
!String.IsNullOrEmpty(Username);
}
}
但如果您打算创建复杂的规范,或者您打算将它们传递给您的系统(例如,将规范传递给存储库以获取某些特定对象),那么这是个好主意。
定义规范接口(interface)(如果你想要更多规范,或者如果你想模拟它们):
public interface ISpecification<T>
{
bool IsSatisfiedBy(T value);
}
创建具体的规范(当然,名字可以更具体,比如OvertimeWorkerSpecification
,检查worker是否有加类):
public class UserSpecification : ISpecification<User>
{
public bool IsSatisfiedBy(User user)
{
return !String.IsNullOrEmpty(user.Firstname) &&
!String.IsNullOrEmpty(user.Lastname) &&
!String.IsNullOrEmpty(user.Email) &&
!String.IsNullOrEmpty(user.Username);
}
}
假设用户看起来像:
public class User
{
public string Firstname { get; set; }
public string Lastname { get; set; }
public string Email { get; set; }
public string Username { get; set; }
}
用法很简单:
var spec = new UserSpecification();
// then pass your user to check if he satisfies specification
if (spec.IsSatisfiedBy(obj))
// do something
// or filter users with specification
var validUsers = users.Where(spec.IsSatisfiedBy);
另外我建议你阅读很好Specifications Martin Fowler 的文章。
关于c# - 实现规范设计模式以检查一系列字符串属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21017882/