views:

74

answers:

1

In my app, I am creating a series of validation classes to check, for example, that a user entered Name property of the class (from a WinForm) doesn't exceed the size of the varchar() in the database.

Currently, the validation code will throw a custom Exception if the Name field is too large. (The custom exception, when caught by the UI, will show the custom exception message in a MessageBox as opposed to my generic error form for regular exceptions.) Validation classes are in the app's class library, and are scoped as Friend. The flow looks like this:

  • The DLL's Public Service Layer used by the WinForms --(calls)--> Friend Validation Layer
  • The DLL's Public Service Layer used by the WinForms --(calls)--> Friend Data Access Layer if validation succeeds.

Simplified example:

Public Shared Sub CreateCustomer(cust as Customer)
    Validation.Customer.ValidateForCreate(cust) ' scoped as Friend
    Dal.Customer.Create(cust) ' scoped as Friend
End Sub

Is it "smart" design to have the Validation Layer throw custom exceptions back to the UI when validation fails?

Is it better design to just return True/False from the Validation Layer along with a String message of what failed, and have the Service Layer handle throwing exceptions?

Is it better design to just return True/False from the Validation Layer, and have the Services Layer bubble up the True/False to the UI along with a String message of what failed?

I'm trying to keep an object oriented approach. My opinion is that throwing custom exceptions doesn't break OOP principles, but I'd like other opinions :)

+1  A: 

Hi,

AFAIK the exception mechanism is in fact at the core of OOP methodology, and is actually encouraged where it is built into the programming language. I'd say having your validation throw a custom exception is very much a good thing, especially if you have several custom exceptions (NameTooLongException, NameIncludesNonStandardCharactersException...) that are self-documenting and easily readable to future maintainers of the code.

Once your exception reaches your service layer, you can decide whether to catch and handle it (this depends on your business logic) or let it go all the way to the UI. If the exception carries a meaningful error message that is always appropriate, perhaps letting the UI present it to the user is not a bad idea. (Bare in mind though that you may want to internationalize your application at some point, in which case the message will need to be in the correct language.)

My opinion is that layer separation, while sometimes purely logical, has its reasons, and exceptions should not be thrown from the back-end to the front-end, but this is more of a guideline than a rule. Bottom line, do what needs to be done, don't overthink the design.

Hope this helps somehow...

Yuval =8-)

Yuval