c# - SOLID-原则的尝试,实不实?

标签 c# unit-testing solid-principles separation-of-concerns

在我们的分层架构中,我正在设计一个名为 AppHandover 的 BLL 逻辑组件,并为此编写了基本的高级代码。我希望它遵循 SOLID 原则并松散耦合,采用关注点分离并可测试。

这是 AppHandover 应该做的

  • 检查用户是否拥有应用程序。如果没有抛出错误
  • 如果可能,删除历史记录(即不再向用户分配应用程序)
  • 将所有权转移到下一个实例

问题是,我走在正确的轨道上吗?下面的示例看起来可靠吗?

public interface ITransferOwnership
{
    void TransferOwnership(string userId, string appId, TransferDirection transferDirection);
}
public interface IOwnershipVerification
{
    bool UserOwnsApp(string userId, int budgetId, string appId);
}
public interface IPreserveHistoryCheck
{
    bool ShouldDeleteTemporaryBudgetData(string userId, int budgetId);   
}
public interface IRemoveHistory
{
    void DeleteTemporaryBudgetData(string userId, int budgetId);
}

交接流程实现

public class AppHandoverProcess : KonstruktDbContext, ITransferOwnership
{
    private IOwnershipVerification _ownerShipVerification;
    private IPreserveHistoryCheck _preserveHistory;
    private IRemoveHistory _removeHistory;
    private ITransferOwnerShip _transferOwnership;

    public AppHandoverProcess()
    {

    }
    public AppHandoverProcess(IOwnershipVerification ownerShipVerification, 
        IPreserveHistoryCheck preserveHistory, 
        IRemoveHistory removeHistory)
    {
        _ownerShipVerification = ownerShipVerification;
        _preserveHistory = preserveHistory;
        _removeHistory = removeHistory;
    }

    public void PerformAppHandover(string userId, string appId, int budgetId)
    {
        if (_ownerShipVerification.UserOwnsApp(userId,budgetId,appId)) {
            if (_preserveHistory.ShouldDeleteTemporaryBudgetData(userId, budgetId))
            {
                _removeHistory.DeleteTemporaryBudgetData(userId, budgetId);
            }

            //handover logic here..

            _transferOwnership.TransferOwnership(userId, appId, TransferDirection.Forward);
        }
        else
        {
            throw new Exception("AppHandover: User does not own app, data cannot be handed over");
        }
    }
}

最佳答案

关于您在上面概述的代码,我绝对认为您走在正确的轨道上。我会进一步插入设计并将 TransferOwnership 定义为附加接口(interface)。

按照这种方法,您的AppHandoverProcess 与其客户端完全分离,并且行为将在服务配置中定义。

TransferOwnership 强制执行隔离将使您能够轻松地对实现该接口(interface)的任何对象进行单元测试,而无需模拟 AppHandoverProcess 依赖项。

此外,任何 AppHandoverProcess 测试都应该是微不足道的,因为您唯一需要确保的是调用您的服务或抛出异常。

希望这是有道理的,

问候。

关于c# - SOLID-原则的尝试,实不实?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26914439/

相关文章:

c# - 什么时候委托(delegate)和 Func/Action 不能互换?

Angular 关闭通用对话框测试

java - Mockito - 模拟子类方法调用

尝试应用里氏替换原理的 C# 编译错误

c# - 扩展基类以包含详细信息?

c# - 如何为嵌套集合编写 Linq 或 Lambda 表达式

c# - 以高分辨率间隔/计时器引发事件

unit-testing - 快速单元测试 : HotSwap an CLLocationManager Object

c# - string.IsNullOrEmpty(myString) 或 string.IsNullOrWhiteSpace(myString) 是否违反 SRP 规则?

c# - 在 Windows 8 Metro App C# 中打开文件