Log in

tobes31415 in tobes31415_code

Compile Time Semantic Checking

C# is a TypeSafe language, what about SemanticSafe?

In a project I'm working on we have a lot of database records ids being passed around as integers. Today I needed to add a new record id to this list. Adding the new item to the function signature is easy. the hard part comes in making sure the right value is being assigned.
Public void MyFunction(int TableA_ID, int TableB_ID, String someOtherValue);

int A_ID = 5;
int B_ID = 4;
MyFunction(B_ID, A_ID, "Hello World");

so what happens when I compile? nothing, it works fine. yet that line where I called the function have have just corrupted the entire database because those database ID's were transposed. Which would kinda suck.

Its one thing to guarantee type safety, what what about semantic safety? An idea popped into my head to use the existing type-checking to accomplish this.
    public struct UserID
        private int value;
        public static implicit operator int(UserID source)
        { return source.value; }

        public UserID(int intValue)
            value = intValue;

    private void TryToFail(UserID test) { }    

    UserId works = new UserId(5);
    int fails = works;

    TryToFail(works) //compiles fine
    TryToFail(fails) //Doesn't compile

Even though both works and fails contain the exact same value, the function can be made to fail if the values are put in the wrong order. And I used an implicit operator so that I didn't lose the convince of having a simple integer, neato.

Obviously this technique is not something you would want to use for every possible field as there is one extra step involved in getting the value but if you only did this for the record ids I think it'd be enough gain to make it worthwhile.

I would like to think of a way to do this so that it has compile time checking, but once compiled only contains the primitive value. Any ideas?


January 2009

Powered by LiveJournal.com