views:

67

answers:

1

Consider the following. (in pseudocode).

Class
{
    hello
    world

    public
    constructor(hello, world)
    {
        if (hello is not String)
        {
            throw Exception()
        }

        if (world is not Array)
        {
            throw Exception()
        }

        this.setHello(hello)
        this.setWorld(world)
    }

    protected
    setHello(hello)
    {
        if (hello is not String)
        {
            throw Exception()
        }

        this.hello = hello
    }

    private
    setWorld(world)
    {
        if (world is not Array)
        {
            throw Exception()
        }

        if (not this:isASafe(world))
        {
           throw Exception()
        }

        this.world = world
    }

    public
    static
    isASafe(world)
    {
        if (world is not Array)
        {
            return false
        }

        if (world.length < 1)
        {
            return false
        }

        if (world['sky'] is not 'blue')
        {
            return false
        }

        return true
    }
}
  1. Is it best practice to perform parametric type/validity checking at the constructor and then again at the function, or at only one of the two methods. (ie. constructor xor method).

  2. Further, does the scope (public/protected/private/etc.) of said method change the above answer (1). For instance isASafe(world) is a public static method, and is only in the class to encapsulate logic.

  3. Should constructors even be doing any checks?

I have my own personal opinions on the matter, but would like to see what others think, and what they find most effective/efficient.

+1  A: 

Checking parameter validity is clearly more important for all public functions than protected or private. Since your constructor is public, then clearly checking makes sense.

It is not always possible to check validity in all cases- the question of what is valid or not, e.g. sky == blue, may differ in a context you do not have access to.

I prefer defensive code. The fewer statements that run before a data inconsistency is detected means the assert occurs closer to the statement that introduced the problem- making it easier/faster to find.

That means my preference is to do some sanity checking of parameters for most methods. I will often dispense with checking for certain private methods, although you take the risk that someone (maybe you) makes then protected or public someday, and you also skip the chance to catch a data inconsistency one step closer to the source.

james creasy