Valid XHTML 1.0! Valid CSS!

Good programming techniques

Too many tutorials simply teach you how to program, without ever teaching you how to make good programs.

Pick good variable names

Here are some things should consider when choosing variable names.

Meaningful names

The variable name should convey what kind of information is contained in the object. Here are some examples:

Good     Bad
age
student
name
count
sum
product
a
foo
xwy     

Multi-word names.

Don't be afraid of making variable names with more than one word. Just make sure that it's readable.

There are two conventions for doing this:

  • studentAge
  • student_age

I prefer the last one, but it's up to you.

Plese do not write 'studentage'. You would not appreciate it if I wrote this tutorial without any spaces.

Use irb

You should not stop using irb simply because you can use an editor. I showed you irb first for a reason. When you program, you should keep an irb window open, and go back to it whenever you want to experiment with ideas.

This is what irb was designed for. If you use it wisely, it will make you a much better programmer.

Use constants

Whenever you have a value that should not change, always make it a constant. This way Ruby will help you catch some possible errors.

Some examples:

Pi = 3.14159265
Electron_mass  = 9.109e-31
Speed_of_light = 3e8
Earth_Sun_distance = 5.79e10

In general, do not write numerical values directly. Use constants to make your code more clear.

For instance, the formula for the area of a circle is A=πr2. Where r is the radius. Your code should resemble this formula as much as possible.

Good Bad
PI = 3.14159265

area = PI*radius**2

area = 3.1416*radius**2