Monday, November 19, 2012

BlogPost blogPost = BlogPostFactory.MakeBlogPost(NewBlogPostOptions.BlogPostWithAbsurdTitle)

Don't leak useless implementation details in your variable, method, or class names. Just don't.

Sure, the name may be accurate and true, but so what? I don't need to see the class name 5 times in one line - that just clutters up the place. It also makes it harder to see similarities in code and opportunities for refactoring. These kinds of names also go against the entire point of polymorphism: you don't need to know the type, just it's capabilities. Hungarian notation obviously falls into this category of cluttering up the place with implementation details. I rarely need to know the exact type or inner working of something. What I need to know is the intent.

There is one place where a name should leak implementation details though: choosing a strategy. Not just the Strategy Pattern, but even between different methods that all do the same thing but in a different way. I'm thinking of things like depthFirst vs breadthFirst, MaximizeBenefitStrategy vs MinimizeCostStrategy vs MinimizeRiskStrategy, or calculateLevenshteinDistance vs calculateJaroWinklerDistance. These seem like good implementation leaking names to me since when I choose one, I need to choose the exact details. Of course they could be wrapped in intention revealing names which would be used most of the time:

public double PercentSimilarTo(this string myself, string other)
    var longest = (double)Math.Max(myself.Length, other.Length);
    return EditDistanceCalculations.CalculateLevenshteinDistance(myself, other) / longest;

Try it for a few weeks and see what happens. I think that replacing implementation revealing names with intention revealing names is one of the easiest ways to improve code.

No comments:

Post a Comment