【问题标题】:How to eliminate method side effects?如何消除方法副作用?
【发布时间】:2019-06-18 14:37:18
【问题描述】:

在编写代码时,我会尽量注意 SOLID 和简洁代码原则。当我查看我的函数时,我认为我陷入了副作用错误。

例如,假设我在 Web 服务中有一个逻辑。当我触发一个方法时,它必须从另一个服务获取所有数据并将它们插入数据库。我的代表方法如下。

   //when I call the method, process starts
    public void TriggerProcess()
    {
       GetInformationsFromService();
    }

    public void GetInformationsFromService()
    {
       var informations = exampleService.GetInformations();

       InsertInformations(informations);
    }

    public void InsertInformations(informations)
    {
       insertThemToDb(informations);
    }

当我编写上述代码时,我陷入了副作用错误。如果有人只想在服务中使用 GetInformationsFromService() 方法,则不应插入数据。

但是,如果我调用如下方法..

  public void TriggerProcess()
    {
       var informations = GetInformationsFromService();
       InsertInformations(informations);
    }

总会有很多方法,比如链式方法,它们的一个目的就是以正确的顺序调用方法,并且总是有一个中间 触发方法和具有一项职责的方法之间的层。如果生意变大,我觉得这很奇怪。

  public void RepresentativeMethod()
     {
        method1();
        method2();
        method3();
        //...
     }

如何避免副作用?我可以使用哪种模式来实现良好的实现?

【问题讨论】:

    标签: coding-style solid-principles code-cleanup side-effects clean-architecture


    【解决方案1】:

    从另一个服务的数据更新/插入数据库中的数据和仅查看数据是两个不同的用例/过程。不要试图重复使用您的GetInformationsFromService(),因为它有不同的用途。实际上,您必须将其重命名为 SyncInformation() 之类的名称,并且您将拥有另一个名为 GetInformation() 的方法来查看数据。

    你可以这样做,去掉TriggerProcess(),因为SyncInformation()已经是一个进程,直接调用就行了:

    这个用例/流程也应该包含在领域层中:

    同步信息用例:

    public void SyncInformation() {
      var informations = exampleService.GetInformations();
    
      informationRepository.insertInformation(informations);
    }
    

    获取信息用例:

    public List<Information> GetInformation() {
      return exampleService.getInformation();
    }
    

    数据的获取和保存应该在您的数据层中:

    示例服务:

    public List<Information> getInformation() {
      // logic to fetch from another service, eg: API
    }
    

    信息存储库:

    public void insertInformation(informations)
    {
       // insert to database logic
    }
    

    在这里,我们遵循关注点分离,因为我们将其分为两层,域和数据。 域层 处理所有应用程序/业务逻辑,例如如何同步信息的步骤。 它知道何时应该保存数据,但它不知道如何保存数据数据层 知道如何读取和保存数据,但不知道何时应该发生。

    【讨论】:

      猜你喜欢
      • 2018-05-26
      • 1970-01-01
      • 2015-03-03
      • 1970-01-01
      • 1970-01-01
      • 2015-01-22
      • 2020-06-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多