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.
Assertions are used when some really erroneous condition is true. It is so wrong that an exception is not enough. It is usually use to detect logic errors in your code.
Whether or not to use it in your specific example depends. Are you 100% sure that ParentModel
should be non-null, and that if it is null, it implies that something really unexpected and wrong has happened and you must stop the program? If yes, then you can use Debug.Assert
. Otherwise, do a null-check and if it is null, handle it by some other way than terminating the program.
Also note that the assert won't work in Release mode. To assert in Release mode, use Trace.Assert
.