So I don't know if this is good or bad code design so I thought I better ask.
I frequently create methods that do data processing involving classes and I often do a lot of checks in the methods to make sure I 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)?
_someEntityto benull" (or if you prefer, is anull_someEntityfield a valid state for the object to be in?). My suggestions: If there's no reason for the class to hold a null value for this field: If you can, pass in the entity in the constructor and throw an exception there, if you can't provide it in the constructor, throw an exception inAssignEntity... – jrh Jul 03 '18 at 14:16nullcheck is reasonable. Now the design decision is inSetName, as in, is it safe for it to ignore the entity being null and just return? (e.g., because the entity is optional) Or is it better for it to throw anInvalidOperationExceptionbecause you tried to rename something that doesn't exist? This particular design decision depends on whether or not the caller ofSetNameknows / cares the entity exists, or if it's okay / acceptable for it to say "well I tried to rename it" and give up... – jrh Jul 03 '18 at 14:18_someEntityto be notnull(e.g., in the constructor / usingreadonly), hypothetically if you are doing Fox Moulder programming and you just can't afford any risk at all, and you feel like it's in your best interest to have a recovery option for absolutely everything (even against a future developer not understanding that_someEntitycan't benull), you could do something to indicate that this is an unexpected condition, then perform whatever recovery you set to get you out of it. – jrh Jul 03 '18 at 14:23