Rediscovering the Obvious

…stumbling in the footsteps of greatness

Dirty, or elegant?

without comments

The nature of our development standards require a certain degree of exception wrapping at every public layer boundary, and I’ve been getting frustrated with the need to write 11 extra lines of code for what could/should be a one line method. At the same time, I respect the reasons that led us to this approach. As such, I decided to find a way to make it as clean as possible. I arrived at the following approach using anonymous delegates to introduce an aspect (little a, not big AOP a)  to the class.

I’d like a consensus on whether this was scary, dirty, nasty shortcutting in code, or if it’s an elegant way to clean the code and encapsulate the default exception behavior for a layer.

First, the delegate side:

        private delegate void CodeDelegate();

        private void WrapBusinessExceptions(CodeDelegate code)
        {
            try
            {
                code();
            }
            catch ( BusinessException be )
            {
                throw;
            }
            catch ( Exception ex )
            {
                throw new BusinessException(ex);
            }
        }

 
Second, an example of the usage:

        public void ActivateUser(Guid userId)
        {
            WrapBusinessExceptions(delegate()
            {
                SetActivationStatus(userId, true);
            });
        }

[EDIT]

Turns out, there’s a problem there… no support for return values… to support any and all return types, I added this second, generics-based set of code (with corresponding example)

        private delegate T CodeDelegate<T>();

        private T WrapBusinessExceptions<T>( CodeDelegate<T> code)
        {
            try
            {
                return code();
            }
            catch ( BusinessException )
            {
                throw;
            }
            catch ( Exception ex )
            {
                throw new BusinessException(ex);
            }
        }

         public bool IsEmailAvailable(string email)
        {
            return WrapBusinessExceptions<bool>(delegate()
            {
                    return IsEmailUnique(email );
            });
        }

Written by erwilleke

October 10th, 2007 at 11:19 am

Posted in Uncategorized

Leave a Reply