Friday, April 11, 2014

How to Write Better Code

Writing code is all about readability.  Even if it's just for you.  When writing code, using some best practices and standards will make your life a lot easier when trying to fix errors, stay organized, or when working with teammates.

1. Use Comments to Help Readability



Comments within code are useful for several reasons.  First, comments are a great way to type out in a conversational language what the code is doing.  Second, they are a great way to organize your code.  If you're scrolling through a long piece of you, it's a lot easier to look for comments than a particular line of code; they stand out more.  Third, it's a great way for team members to understand what you were doing or thinking as well.

2. Use a Standard When Indenting



When writing code, make sure to keep a standard throughout all of your code.  When you indent a certain way, do it for a similar piece of code later on.  It helps improve readability, audience understanding, and it might even help you spot errors.

3. Use a Standard When Naming Files, Classes, Etc.

Take a look at the code in green.  It's in camelCase.

There are several ways to name files and it really just boils down to what you're comfortable with.  A lot of people might be used to doing something like this: Desk_Talk_Blog or DESK_TALK_BLOG, or Desk-talk-blog.  But for me, I like to use a modified version of PascalCase called camelCase.  I will keep the first word lower-cased and for the second word I will capitalize the first letter and so on.  This is what it ends up looking like: deskTalkBlog.  So why do this?  Again, it helps with readability and it just gives you some organization.  I recommend doing it throughout your website down to the folder directories.

4.  Avoid Deep Nesting and Keep Line Length To A Minimum

Don't do this
It's easy to get carried away with nesting.  It is usually a great way to keep organized and matches a standard when indenting, but sometimes it is totallly unneccesary and just adds difficulty when trying to read it.


Furthermore, keep the length of your lines short.  It is so annoying when you're trying to read a line of code and you have to scroll to the right to continue reading it.  There's a reason why newspapers use multiple columns rather than one column; it's much easier to read.

That's it for now.  These tips have mostly been focused on HTML/CSS, but they can extend how to other languages as well.

1 comment:

  1. The fact that I already do these things makes me feel pretty good about myself, not gonna lie.

    ReplyDelete