C# – common pattern for handling missing data found deep in an application

cdatadesigndesign-patterns

I have a manufacturing management application that I'm in the middle of redesigning to make it more universal (we acquired a small company and they will use the tool as well). Where before I had many values hard coded because the application had a single client, now it's more configuration based with various data elements coming from options files or database tables. This is rewarding in that it's a better design and the application is evolving, but it has presented a new challenge: low level services and components encountering situations where they are missing data.

For example I may have a serial number generation component that used to have a hard coded string it would use as a part of the serial number, now that "base serial number" is dynamically generated and coming from a format string stored in the product table. There are several layers and classes between the product table data and the component generating the serial number. I want to handle the missing data exception and allow the user to correct the problem in the current application session rather than blow up and crash.

I see two possible approaches:

  1. Add deep data validation at the point of request to make sure everything is there to avoid encountering exceptions at the low level code. I don't like this because it means my presentation layer would need to either have knowledge about the objects and data involved downstream or I would need to sprinkle all my objects with "HasRequiredData()" methods.

  2. Create a new Exception type that represents the general problem of missing data. When a low level component encounters a situation where data it needs isn't available it would throw this exception. Presentation layer then handles this exception nicely.

So my question is: Does option #2 seem like a good approach and design to you all? Is there another common approach to issues like this?

Best Answer

The common handling (as I see it) is to raise an exception and log the error. You always will have cases where business logic comes to places where nobody has been before. That means you need to handle the exception gracefully:

  • inform the user about the exception,
  • clean the stack,
  • log the error and
  • later on check the log regularly for messages to clean up and provide fixes.
Related Topic