Coding style 如何消除方法的副作用?

Coding style 如何消除方法的副作用?,coding-style,solid-principles,code-cleanup,side-effects,clean-architecture,Coding Style,Solid Principles,Code Cleanup,Side Effects,Clean Architecture,当我编写代码时,我会尽量注意坚实和干净的代码原则。当我看我的函数时,我认为我陷入了副作用错误 例如,假设我在web服务中有一个逻辑。当我触发一个方法时,它必须从另一个服务获取所有数据并将它们插入数据库。我的代表方法如下 //when I call the method, process starts public void TriggerProcess() { GetInformationsFromService(); } public vo

当我编写代码时,我会尽量注意坚实和干净的代码原则。当我看我的函数时,我认为我陷入了副作用错误

例如,假设我在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();
        //...
     }

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

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

以下是您可以做的,消除
TriggerProcess()
,因为
SyncInformation()
已经是一个进程,直接调用它即可:

此用例/过程也应包含在域层中:

同步信息用例:

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

  informationRepository.insertInformation(informations);
}
public List<Information> GetInformation() {
  return exampleService.getInformation();
}
获取信息用例:

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

  informationRepository.insertInformation(informations);
}
public List<Information> GetInformation() {
  return exampleService.getInformation();
}
在这里,我们遵循关注点的分离,因为我们将其分为两层,域和数据域层处理所有应用程序/业务逻辑,例如如何同步信息的步骤它知道什么时候应该保存数据,但不知道如何保存数据层知道如何读取和保存数据,但不知道何时发生