Richard Bucker

Do you really want to improve your code quality? Try this!

Posted at — Sep 21, 2013

I have been tooling around with a code generator. Some piece of code generates some other, intermediate, piece of code; which is then compiled. However, along with the intermediate code I also generate state diagrams using graphviz. The outcome produced some wild results. (a) I caught more of my own bugs before letting them escape into test. (b) as part of the documentation it allowed the product owner, QA, audit etc… to validate the requirements with the code. This is MUCH better than writing your own flowcharts or even TDD, BDD, MDD, DDD, etc…The second observation. While the code was being generated from artifacts in a database; with the intent that different code fragments that were stored in the DB would be reused as-is; It became necessary that the generated code (a)implement immutable variable names, (b)class attribute names, (c)function names and (d)class member function names. Which if you have not guessed it flies in the face of everything we know but let me explain.1) Given a class User with a string attribute Name; we know a few things:a class is nothing more than a container of attributes and methodsUser is such a container with an implied semantic that it describes a userand that there is a Name attribute in the User containerof course User.Name could have many semantic meanings2) Given a class Printer with a string attribute Name; we know many of the same things.Since the code I was working on was completely green field I was generating many new classes, structures and interfaces. I found myself copying code and attributes from gist to gist. As the code got more complex I found myself using lots of reflection (I’m not sure which came first; the complexity or the reflection) And one strange outcome was that I started ignoring the semantics of the class and just started copying like named attributes.You might find yourself saying that this is all on me.  You’d be right too. But assuming that your language of choice implements a proper inheritance model or even proper OO structure – all of that is a complicated waste of time. What happens when you are looking at… WindowsUser.Name and UnixUser.Name? Or Windows.User.Name and Unix.User.Name? Nowhere is this more obvious than Duck Typing. But even here you have the type and none of the semantics.If you truly accept that the “class” does not really offer but the loosest semantics and that the strict semantics are on the actual attributes then you’ll see the benefits of getting the names right across classes, structures and such.