Search code examples
code-generationdefensive-programmingrobustnesssolid-principles

Robust Code framework?


I hate writing code that makes my software more solid. This is something the framework should have done! So, is anybody aware of a code "enhancing" utility that solidifies the code?

If I had to create something like this myself, it would work as follows: When you're compiling your code with a Debug flag, it would auto-magically add "solidifying" code for each method:

Warp the code with a try-catch and put a Debug.Assert(true) in the catch (so that exceptions are caught at their origin).

Log each method's entry, printing "ToString()" values of arguments, so I can trace what's going on.

Check each argument for null.

Use an "IsValid" framework to check the object itself and each argument, where IsValid() is the object's way of declaring that its expectations are true (for example, if I'm a TableOfContentsEntry I expect to always be in a Book that's IsValid() and to point to a Page that's IsValid().

So, why not?


Solution

  • If you want to log method calls, you could use an AOP framework like PostSharp. Things like enforcing method pre/postconditions would be best achieved using design-by-contract mechanisms like the new Code Contracts library which will ship with .net4.0. It certainly doesn't make sense to just check arguments for null since this may be a valid value depending on the method. Injecting Debug.Asserts into code could be problematic since you may not want to/be able to handle exceptions in the source function. I think it would be impractical if not impossible to create a generic framework for this sort of thing since requirements will differ so greatly between projects.

    EDIT: To clarify my comment about adding debug assertions into methods - I read your proposal to be to convert a method body into something like this:

    public void SomeMethod(args)
    {
        try
        {
            //original method body
        }
        catch(Exception ex)
        {
            Debug.Assert(false);
            throw;
        }
    }
    

    The problem with this is that Asserts indicate things that should never be false - so this construct means that the method can never throw which isn't true in general. The problem is now that if the method does throw, the assertion will fail even if the calling method handles the exception appropriately. From your comment it seems that you are doing something like this:

    public void SomeMethod(object arg)
    {
        Debug.Assert(arg != null);
        if(arg == null) throw new ArgumentNullException("arg");
    
        //rest of method
    }
    

    This is a useful practice, and I believe that the code contracts library supports 'legacy' precondition checking (throwing exceptions) in its static analysis.