Sunday, September 12, 2010

Convention over configuration

This is actually coding by conventions.This software design paradigm which ensures the following things
  • This decrease the number of decisions that developers need to make, gaining simplicity, but not necessarily losing flexibility
  • The developer only needs to specify unconventional aspects of the application for example if there is a class called user in the model then its curresponting table will be Users
General-purpose frameworks usually require one or more configuration files in order to set up the framework. A configuration file provides a mapping between a class and a resource (a database) or an event (a URL request). As the size and complexity of applications grow, so do the configuration files, making them harder to maintain.

A Valid example in rails is as below

An example should show you how the conventions work together: You have a database table called users with the primary key id. The matching model is called user and the controller, that handles all the logic is named users_controller. The view is split in different actions: if the controller has a new and edit action, there is also a new- and edit-view.

class NamesValidator

# Checks that first_name and last_name are within certain length
def self.valid_length?(name)
 name.first_name.length < 20 and name.last_name.length < 10
end

# Checks that first_name and last_name have the first character capitalized
# capitalize turns HELLO into Hello; hello into Hello; etc
def self.valid_case?(name)
 name.first_name == name.first_name.capitalize and
 name.last_name == name.last_name.capitalize
end

def self.non_conforming_method
 # This method will not be called during validation
end

end

class Name < Validatable

attr_accessor :first_name, :last_name # create getters and setters for instance variable name

def initialize(first_name, last_name)
 @first_name, @last_name = first_name, last_name
end

end

Name is just a simple class that has two fields: first_name and last_name. The NamesValidator has two class methods that check if the name is of valid length and if it has the right case. The method non_conforming_method is left there to show that our validation system does not call that method since it does not conform to the naming convention we agreed upon.

No comments:

Post a Comment