Sounds pretty basic, but I did not find an existing answer. Sorry if it's a duplicate.
I have never used assertions much in the past and I may not have understood the spirit behind them yet. Is it recommended or standard practice to write something like the following in method Remove()?
public class Model
{
public Model ParentModel {get; private set}
readonly List<Model> submodels = new List<Model>();
public Model AddSubmodel(Model m)
{
submodels.Add(m);
m.ParentModel = this;
}
public void RemoveSubmodel(Model m)
{
submodel.Remove(m);
m.ParentModel = null;
}
public void Remove()
{
Debug.Assert(ParentModel != null);
if (ParentModel != null) ParentModel.RemoveSubmodel(this);
}
// ...
}
The condition is something I am in control of (i.e. it doesn't depend on user interaction or something) and it determines the correctness of my code, so exceptions are out.
My rationale behind this is, I want it to fail in Debug mode, but I want to repair it as much as possible in Release mode.
Edit: as already mentioned in the comments,
The condition violation is not terribly fatal as such. If there is no parent, other than the the method call failing without the null check, nothing much will happen (in release build).
But what is more important, it indicates that the client of the class Model is doing something that is illogical. I want to be pointed to the fact (at least during debug) that there is something in my client code that I obviously haven't thought about, because if i had, the condition would have never happened.