How do you proactively guard against errors of omission?

Posted by Gabriel on Programmers See other posts from Programmers or by Gabriel
Published on 2011-10-31T17:25:56Z Indexed on 2011/11/25 10:06 UTC
Read the original article Hit count: 235

Filed under:
|
|

I'll preface this with I don't know if anyone else who's been programming as long as I have actually has this problem, but at the very least, the answer might help someone with less xp.

I just stared at this code for 5 minutes, thinking I was losing my mind that it didn't work:

    var usedNames = new HashSet<string>();
    Func<string, string> l = (s) =>
        {
            for (int i = 0; ; i++)
            {
                var next = (s + i).TrimEnd('0');
                if (!usedNames.Contains(next))
                {
                    return next;
                }
            }
        };

Finally I noticed I forgot to add the used name to the hash set.

Similarly, I've spent minutes upon minutes over omitting context.SaveChanges().

I think I get so distracted by the details that I'm thinking about that some really small details become invisible to me - it's almost at the level of mental block.

Are there tactics to prevent this?

update: a side effect of asking this was fixing the error it would have for i > 9 (Thanks!)

    var usedNames = new HashSet<string>();
    Func<string, string> name = (s) =>
        {
            string result = s;
            if(usedNames.Contains(s))
                for (int i = 1; ; result = s + i++)
                    if (!usedNames.Contains(result))
                        break;
            usedNames.Add(result);
            return result;
        };

© Programmers or respective owner

Related posts about c#

Related posts about coding-style