Given the class named OrderInfo, what’s the best way to ensure other developers (including myself) do not accidentally make the recursive error shown here:
public class OrderInfo : ICollection<UnitModule> {
// Other code for class...
public bool Changed { get; private set; }
public void Save() {
Save(this); // I want the static method to handle saving the data
}
public static void Save(OrderInfo item) {
for (int i = 0; i < item.Count; i++) {
if (item[i].Changed) {
item[i].Save();
}
}
if (item.Changed) {
item.Save(); // this would be bad!
// Instead, all of the other developers should have to call the
// Database Save method.
// Is there a way to ensure this happens or do I have to rely on
// everyone remembering this?
}
}
}
EDIT: Using the marked answer, I can write my class as follows (why does not matter – this simply prevents the recursion):
public class OrderInfo : ICollection<UnitModule> {
// Other code for class...
bool saving; // <= new variable
public bool Changed { get; private set; }
public void Save() {
if (!saving) {
Save(this);
} else {
throw new Exception("This item is already being saved.");
}
}
public static void Save(OrderInfo item) {
item.saving = true;
try {
for (int i = 0; i < item.Count; i++) {
if (item[i].Changed) {
item[i].Save();
}
}
if (item.Changed) {
// item.Save(); <= NOTE: this would throw an exception
DataAccess.Save(item);
item.Changed = false;
}
} finally {
item.saving = false;
}
}
}
This might work: