Er. alokpandey's Blog

11 tips for better code

Posted in ASP.NET (C# & VB), C#, HTML and XHTML, J-Query, JavaScript, LINQ, PLINQ, SilverLight, VB, WCF by Alok Kumar Pandey on December 22, 2010

11 tips for better code

There are several reasons why you should write clean and readable code. Most importantly, every code is written once, but read many times over and over. When you come back to your code next day, you have to read it. When you show your code to someone else, he has to read it. Thus by spending little more time with writing, you save A LOT of time when reading it again.Lets see some of the basic rules
1- keep methods short2- never ever ever reuse a variable for different purpose3- use self-descriptive variable and method names4- define variables as close as possible to the place of their usage5- no magic numbers6- be friend with your language7- don’t fight the convention8- watch out for premature optimization9- always refactor the code after you test it10- don’t get sucked into overengineering11- learn new things by prototyping

Now, let’s look up at each point in more detail
1. Keep methods shortEven though many people obey this rule, it is still very important. Method should always fit on the screen. When you have to scroll, it takes away your concentration and you can’t see whole context. Optimal length is 5-20 lines, depending on the situation. Of course getters/setters are usually one-line methods, but they’re more like accessors than actual methods.
2. Never ever ever reuse a variable for different purposeOne variable should be used only for one purpose.  By making variable constant (const in C++, final in Java), you also help the compiler with optimization and make your code scream This variable is not going to change, which makes the code a lot more readable.
3. Use self-descriptive variable and method namesAnyone should be able to understand your code by just looking at it. You should almost never use abbreviations, except for the most idiomatic ones likesrc – sourcepos – positionprev – previousIf you think writing descriptive names is not worth the time, just comparen, ns, nsisdwith numTeamMembers, seatCount, numSeatsInStadium
4. Define variables as close as possible to the place of their first usage
While building a house, you don’t want your hammer to be on the other side of the yard. Instead, you keep your tools as close as possible. The same applies to foo = 3;int bar = 5;// bunch of code that use “bar”// but doesn’t care about “foo”// …
baz(foo);This could be easily refactored toint bar = 5;// bunch of code that use “bar”// but doesn’t care about “foo”// …
int foo = 3;baz(foo);This becomes a real issue when the code between declaration and first usage is very long (more than one screen). It is much harder to keep the context in your mind, when you have to scroll a lot to find out what given variable is.
5. No magic numbers
Whenever you compare something against constant value, it should be defined as constant. There is nothing worse than debugging your teammate’s code with things likeil < 4384What about this instead?inputLength < MAX_INPUT_LENGTH
6. Be friend with your language
Learning new language is always fun, you can learn to do things in new cool way. There is one big downside of being pro in one language while learning other one though. Say you’re Java developer trying to learn Ruby. You should learn how to do things the Ruby way, instead of trying to apply your skill in doing things the same way you’d do them in Java.You need to write 5 times “Hello world!”. In Java, you would do something like.for (int i = 0; i < 5; i++) {  System.out.println(“Hello world!”);}In Ruby, you might be tempted to writefor i in (0..5)  puts “Hello world!”endWhich seems OK, but there is a much better way
5.times { puts “Hello world!” }
7. Don’t fight the convention
Many languages have many different conventions. In general, people most probably know is Code Conventions for Java. Lets look at some of those conventions.method names should always begin with lower-case letter, followed by CamelCase (veryLongVariableName)class names should always be in CamelCaseconstant names should be all in upper case with underscores (MY_CONSTANT)open brace should be on the same line as if condition
Breaking any of conventions should have a valid reason, never do it just because you don’t like it. If you decide to change some convention inside your team, that’s OK, but you might have problem when sharing code with other not so enlightened programmers.8. Watch out for premature optimizationPremature optimization is root of all evil, at least that’s what TV said … First thing you should care about is to write understandable code. It doesn’t have to be fast the first time you write it.All optimization is premature unless the program is slow. If you want to optimize something, at first you need to find out where the problem is. Thats why we have profilers.Trying to optimize something without finding source of the problem always ends up in breaking something, or at least your code may turn out to be unreadable. If you think that something is slow, don’t just blindly start rewriting the code, find a proof first.Don’t solve problems that don’t exist.
9. Always refactor the code after you test it
Nothing is perfect. Even though you might think you’re writing a perfect code, try looking at it few months later. You will probably fell like “wtf is that?”.Good way to improve the quality of your code is to refactor it after you test it. By testing I mean assuring that it works, which can be done either automatically or manually.First of all, you need your code to work. Don’t write it perfect the first time, just make it work. Then refactor it to make it perfect. For those of you that  know something about Test Driven Development, this might seem very familiar. The key here is to get used to the whole refactoring thing. If you’re using powerful IDE like IntelliJ IDEA, your life will be a lot easier while refactoring.
After you try refactoring, you will probably make a mistake and break something. That’s why it is good to write automated tests. Any time you refactor, you can just run all test suites and see exactly what went wrong.10. Don’t get sucked into overengineeringWhen I first read about design patterns, I thought I found The Holy Grail. It all seems to be thought out, working perfectly and making design easy to understand, because you can just say “I used an observer pattern”, instead of explaining it all.So where is the problem? Because it all looks so natural and easy, you start using design patterns for everything. Why not make this class singleton? And what about creating another factory?Then instead of writing simple 80 line script, you end up with 10 class + 15 interface monster with bunch of generics and annotations, where 97% of the code doesn’t do anything.Design patterns are very useful tool to simplify the design, which doesn’t mean using them everywhere you can. You should use them, but don’t abuse them.
11. Learn new things by prototyping
Programming is all about learning new things. When you learn new library or language, you suddenly have the urge to throw away all old code and rewrite it from scratch. There are lots of reasons why you don’t want to do that.Adding a new library or framework to existing application is a similar problem. Say you’re writing a javascript web application, and in the middle of everything, you discover jQuery. Now you have sudden urge to throw away all your javascript and write it in jQuery, even though you haven’t used it yet.The best way to go is to first create a lot of simple things with jQuery, where you will learn all the stuff you need in your application. You need AJAX? Try it on simple example outside the project and after you fully understand it, throw it away and move into production.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: