How not to write C# applications?
In my new job at Sela I came across an application ( written by a client) that needed refactoring. This app has so many coding errors I’ve decided it worth its own post.
Why not rewrite the application?
You could suggest to rewrite the application but I’m strongly against it. To understand why you MUST read the excellent article Things You Should Never Do by Joel Spolsky. Go ahead and read it, it’s more important then reading this post!
Code Duplication
Never write the same code twice. I know, it’s so obvious but nevertheless a common (bad) practice.
Every time you use copy/paste to copy more than one line inside the IDE you should consider to write a new function.
And no, don’t squeeze those four lines into one. It makes reading this line extremely hard and generally means you didn’t handle those null return values in case of errors.
Encapsulation: Public Fields
Never use public fields. Always wrap them with properties. The only exception to this rule is when you write interop code which uses structs with a definite layout.
Maintain class responsibility
This is OOD basics. Every class should have a specific responsibility. The responsibility should be reflected in the class name and should not be too large, meaning you should not put all your application code into the Application class.
For example, suppose you have several places in your app that manipulate folders. Instead of having similar folder manipulation code in 50 different places like: Application, Main Window, different controls etc. you should create some sort of FolderManipulation class that will be responsible on this topic.
This will also help future developers of the project to easily find functionality they need, instead of rewriting them (in a different way).
Comment
Please, comment. Even if you think the code is self explanatory. Write comments that explain what you are doing and not only how you do it.
Those comments will be proved useful in the future when you or your colleagues will need to update the code.
Also, avoid short names for variables. Prefer “xmlSerializer” over “ser”,
Happy Refactoring!
Arik Poznanski.