【发布时间】: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