Ruby: Best Practices Flashcards

1
Q

Rules for If Statements

A
  1. Every if-statement must have an else.
  2. If this else should never be run because it doesn’t make sense, then you must use a die function in the else that prints out an error message and dies, just like we did in the last exercise. This will find many errors.
  3. Never nest if-statements more than 2 deep and always try to do them 1 deep. This means if you put an if in an if then you should be looking to move that second if into another function.
  4. Treat if-statements like paragraphs, where each if,elsif,else grouping is like a set of sentences. Put blank lines before and after.
  5. Your boolean tests should be simple. If they are complex, move their calculations to variables earlier in your function and use a good name for the variable.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Rules for Loops

A
  1. Use a while-loop only to loop forever, and that means probably never. This only applies to Ruby, other languages are different.
  2. Use a for-loop for all other kinds of looping, especially if there is a fixed or limited number of things to loop over.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Tips for Debugging

A
  1. Do not use a “debugger”. A debugger is like doing a full-body scan on a sick person. You do not get any specific useful information, and you find a whole lot of information that doesn’t help and is just confusing.
  2. The best way to debug a program is to use puts or p to print out the values of variables at points in the program to see where they go wrong.
  3. Make sure parts of your programs work as you work on them. Do not write massive files of code before you try to run them. Code a little, run a little, fix a little.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Access Control

A

When designing a class interface, it’s important to consider just how much of your class you’ll be exposing to the outside world. Allow too much access into your class, and you risk increasing the coupling in your application—users of your class will be tempted to rely on details of your class’s implementation, rather than on its logical interface. The good news

www.it-ebooks.info
ACCESS CONTROL 62
is that the only easy way to change an object’s state in Ruby is by calling one of its methods. Control access to the methods, and you’ve controlled access to the object. A good rule of thumb is never to expose methods that could leave an object in an invalid state.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Should you use inheritance?

A

In general, try to avoid inheritance. Other mix methods: modules and mixins are preferable.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly