CSC/ECE 517 Fall 2012/ch1 1w23 ph

From Expertiza_Wiki
Jump to navigation Jump to search

Ruby Coding Guidelines

Designed and developed in the mid-1990s by Yukihiro "Matz" Matsumoto in Japan, Ruby embodies syntax inspired by Perl with Smalltalk-like features and was also influenced by Eiffel and Lisp. Ruby Coding Guidelines include best practices followed generally for most of the object oriented programming languages as Ruby is entirely 'Object Oriented'. Also known as 'Ruby Coding conventions', these are a set of guidelines that recommend programming style, practices and methods for each aspect of a piece of program written in Ruby.

Software programmers are highly recommended to follow these guidelines to help improve the readability of their source code and make software maintenance easier. Naming conventions, class and member design principles, maintainability, performance, documentation and layout are the important areas where these guidelines have to be followed. More important than the reasons for having a guideline is actually adhering to it consistently. Having a coding guideline documented and available means nothing if developers are not using it consistently.


Importance of guidelines

Types of Guidelines

Naming Guidelines

Ruby uses the first character of the name to help it determine it’s intended use.

  • Local Variables
Lowercase letter followed by other characters, naming convention states that it is better to use underscores rather than camelBack for multiple word names, e.g. mileage, variable_xyz
  • Instance Variables
Instance variables are defined using the single "at" sign (@) followed by a name. It is suggested that a lowercase letter should be used after the @, e.g. @colour
  • Instance Methods
Method names should start with a lowercase letter, and may be followed by digits, underscores, and letters, e.g. paint, close_the_door
  • Class Variables
Class variable names start with a double "at" sign (@@) and may be followed by digits, underscores, and letters, e.g. @@colour
  • Constant
Constant names start with an uppercase letter followed by other characters. Constant objects are by convention named using all uppercase letters and underscores between words, e.g. THIS_IS_A_CONSTANT
  • Class and Module
Class and module names starts with an uppercase letter, by convention they are named using MixedCase, e.g. module Encryption, class MixedCase
  • Global Variables
Starts with a dollar ($) sign followed by other characters, e.g. $global


Considering customer order information as the data being used for an application, below naming guidelines give an idea of good class/table/file names.

  • Model Naming Convention
Table: orders
Class: Order
File: /app/models/order.rb
Primary Key: id
Foreign Key: customer_id
Link Tables: items_orders
  • Controller Naming Convention
Class: OrdersController
File: /app/controllers/orders_controller.rb
Layout: /app/layouts/orders.html.erb
  • View Naming Convention
Helper: /app/helpers/orders_helper.rb
Helper Module: OrdersHelper
Views: /app/views/orders/… (list.html.erb for example)
  • Tests Naming Convention
Unit: /test/unit/order_test.rb
Functional: /test/functional/orders_controller_test.rb
Fixtures: /test/fixtures/orders.yml

Class Design Guidelines

Member Design Guidelines

Maintainability Guidelines

Performance Guidelines

  • Avoid nesting loops more than three levels deep
Nesting not only slows your code down but also can make maintenance of the codebase difficult if it goes too many levels deep. Limiting nesting of loops and functions to three levels or less is a good rule of thumb to keep your code performant.
  • Avoid unnecessary variable assignments
New programmers, tend to assign variables more than necessary. A great example is when someone defines a variable to store a return value and then returns that variable; just return the value directly.
  • Reduce usage of disk I/O
Disk I/O is one of the biggest bottlenecks remaining in computing. Read/write operations to disk are extremely slow and it’s best to avoid using the disk whenever possible. Many people are now using software such as memcached which allows data to be stored in memory and only periodically written to disk. The speed improvement while using a memory caching system is tremendous.
  • Use Ruby Enterprise Edition
Ruby Enterprise edition provides up to 33% lower memory usage. In order to take advantage of these performance gains though you must be sure to program according to their guidelines.
  • Avoid method calls as much as possible
Method calls are very expensive operations and should be avoided when necessary.
  • Use efficient Ruby idioms
Program into the language rather than in the language. Performance will suffer if you try to write your Ruby code like you would PHP, Perl, or any other language. Learn the Ruby way of doing things.
  • Use interpolated strings instead of concatenated strings
Interpolated strings are faster than concatenated strings in almost all interpreted languages; Ruby is no exception. Using the << operator makes a method call which and method calls should be avoided when possible.

put “Hello there, #{name}!” vs. puts “Hello there, ” << name = “!”

  • Destructive operations are faster
Ruby’s in-place methods that modify the actual value instead of working on a copy of it are much faster, but be careful as they sometimes behave strangely (i.e., for!)
  • Avoid unnecessary calls to uniq on arrays
In many cases methods are already calling uniq on an array and there’s no need for you to call it yet again.
  • For loops are faster than .each
When you use .each you encounter per-request execution; for loops avoid this expensive operation.
  • Use x.blank? over x.nil? || x.empty?
When using ActionPack there’s no need for x.nil? or x.empty?; x.blank? checks for both of these.
  • Avoid calls to parse_date and strftime
Both of these are very expensive operations. Use regular expressions when parsing out date/time components.
  • Don’t use unnecessary block parameters
If you won’t be using the parameter in the block don’t specify it in the parameter list. Go through your code and ensure that any parameters declared are used or removed.
  • Know your gems
Not all libraries are created with performance in mind. Many gems are slapped together to solve a particular problem that author was having. Before you introduce a new gem into your performance-oriented production codebase be sure to perform thorough benchmarking and testing against other gems that perform the same tasks.
  • Profile your code regularly
If you profile you code regularly you’ll be able to tell if the latest change to the code will have an adverse effect on performance. Integrate profiling into your testing process and make it automated to ensure that it’s not forgotten. Like unit testing and BDD profiling goes a long way.
  • Improve your algorithms before you try to improve your code
Algorithmic improvements are almost always going to have more of an impact on the performance of your code than tweaks to the way your code is written will. Make sure your algorithm is designed to be efficient and has no extraneous methods or calls. Also, test for most frequent cases first and exit loops as soon as possible.
  • Test the most frequently occurring case first
When using if statements or a case statement always test the cases in the order that they occur most frequently. This allows less code to run before a decision is made. It may not seem like much but over several hundred or thousand runs through the decision logic you’ll notice a definite performance gain.
  • Optimize the way you access global constants
Be sure to precede a global constant with it’s namespace and the double colon operator (Namespace::constant_name) to reduce the time needed to query the library.
  • Use explicit returns
Although Ruby will automatically return the result of the last completed operation if no return value is provided you should use explicit return values. Explicit returns are faster, especially in older Ruby versions such as 1.8.x.

Documentation Guidelines

Layout Guidelines

Designing the layout of any application determines the readability factor for other developers. Most followed order of code is as follows:

header block with author's name, Perforce Id tag and a brief description of what the program or library is for. require statements include statements class and module definitions main program section

Code Analysis Tools

Summary

See Also

References