c# – 课堂上的电话顺序很重要的最佳实践?
发布时间:2020-12-15 06:14:52 所属栏目:百科 来源:网络整理
导读:我有一个类有两个重要的功能: public class Foo { //plenty of properties here void DoSomeThing(){/*code to calculate results*/} void SaveSomething(){/* code to save the results in DB*/}} SaveSomething()使用在DoSomeThing()中计算的结果. 问题是
我有一个类有两个重要的功能:
public class Foo { //plenty of properties here void DoSomeThing(){/*code to calculate results*/} void SaveSomething(){/* code to save the results in DB*/} } SaveSomething()使用在DoSomeThing()中计算的结果. 问题是我们不要在DoSomeThing()之前调用SaveSomething(),或者如果发生这种情况,结果不是真的结果.我的意思是调用顺序很重要,这是维护代码的一个问题(当新的添加到团队时). 有什么办法来管理这个吗? 我想到3种方法如下 >在SaveSomething()中抛出异常(如果在DoSomeThing()之前调用) bool resultsAreCalculated = false; void SaveSomething(){ if (!resultsAreCalculated) { DoSomeThing(); // the resultsAreCalculated = true; is set in DoSomeThing(); // can we throw some exception? } /* code to save the results in DB*/ } >实现它流利的喜欢: Foo x = new Foo(); x.DoSomeThing().SaveSomething(); 在这种情况下,保证不会发生这一点很重要: x.SaveSomething().DoSomeThing(); 现在,我使用第二种方法.有什么更好的方法还是够的? 解决方法
帮助避免用户错误的一个选择是通过传递一个变量来清除它.通过这样做,它会在调用SaveSomething(…)之前为用户提供他们需要获取结果的标志(即DoSomething()).
results = DoSomething(); // returns the results to be saved SaveSomething(results); (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |