So iI don't know if this is good or bad code design so iI thought iI better ask.
I frequently create methods that do data processing involving classes and iI often do a lot of checks in the methods to make sure iI don't get null references or other errors before hand.
For a very basic example:
// fields and properties
private Entity _someEntity;
public Entity SomeEntity => _someEntity;
public void AssignEntity(Entity entity){
_someEntity = entity;
}
public void SetName(string name)
{
if (_someEntity == null) return; //check to avoid null ref
_someEntity.Name = name;
label.SetText(_someEntity.Name);
}
So as you can see im checking for null every time. But should the method not have this check?
For example should external code cleanse the data before hand so the methods don't need to validate like below:
if(entity != null) // this makes the null checks redundant in the methods
{
Manager.AssignEntity(entity);
Manager.SetName("Test");
}
In summary, should methods be "data validating" and then do their processing on the data, or should it be guaranteed before you call the method, and if you fail to validate prior to calling the method it should throw an error (or catch the error)?