I have one class with two important functions:
public class Foo {
//plenty of properties here
void DoSomeThing(){/*code to calculate results*/}
void SaveSomething(){/* code to save the results in DB*/}
}
SaveSomething() uses the results calculated in DoSomeThing().
the problem is that we must not to call SaveSomething() before DoSomeThing() or if that happens the results are not true results. I mean order of calls are important, this is a problem in maintaining the code.(when new one is added to team).
is there any way to manage this?
I think of 3 methods as below
- throwing exception in
SaveSomething()if it called beforeDoSomeThing() -
having a
boolthat are set inDoSomeThing()andSaveSomething()code changes to: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*/ } -
implementing it Fluent like :
Foo x = new Foo(); x.DoSomeThing().SaveSomething();in this case, it is important to guarantee that this is not happens:
x.SaveSomething().DoSomeThing();
right now, i use the second method. is there any better way or is that enough?
One option to help avoid user error is to make it clear by passing a variable. By doing this, it raises a flag for the user that they need to get the results (i.e. DoSomething()) before calling SaveSomething(…).