2.4. Understanding Rails' Main Principles

The Rails culture has adopted many of the good principles that derive from the world of Extreme Programming (XP) and the Agile movement in general. For example, though Rails doesn't force you to adopt Test-Driven Development (TDD), this is a popular practice in the Rails community. Also, Rails integrates, simplifies, and promotes testing. As briefly mentioned in the first chapter, YAGNI (You Ain't Gonna Need It) is also a principle that's been largely adopted by the community. There are, however, two mantras that characterize the Rails way of doing development above anything else: "Convention over Configuration" and "Don't Repeat Yourself (DRY)."

It can be said that Rails' strength comes from three components that fit together organically: the framework itself, its Agile philosophies and principles, and finally, the Ruby language. These Agile mantras are so important that it's worth spending some time to analyze them further; the next chapter takes care of providing you with all the essential Ruby skills that you'll need to understand and write Rails applications.

2.4.1. Convention over Configuration

Back in 2004, before Rails had garnered the popularity that it enjoys today, a nine-minute demo by David Heinemeier Hansson was recorded and placed online. The application he showcased was quick and simple: a bare-bones blog. Today, a second version (for Rails 1.0) is available online at http://rubyonrails.org/screencasts and, as you'll see for yourself if you decide to watch it for historical purposes (it's only 15 minutes long), there are no advanced features and even a few "whoops" here and there. Yet that seemingly plain video had a huge impact in contributing to Rails' popularity.

A third version covering Rails 2 has been recently released at the same URL.

Extreme Programming vs. Agile Programming

Agile development promotes iterations and incremental development, collaboration and adaptability to change. And so does XP. When talking about Rails' philosophy it's not unusual to see these two terms pop up almost interchangeably. So unless you're already familiar with the Agile world, you may be wondering what the difference between the two is.

Extreme Programming is a specific Agile method that predates the Agile Manifesto. Agile is an umbrella term that covers several, somewhat similar, lightweight methodologies, which include, among others, the very popular Extreme Programming and Scrum.

XP is by far the most applied Agile method and the one that includes software engineering practices such as Simple Design, Pair Programming, TDD, Continuous Integration, Refactoring, Coding Standards, and Collective Ownership. As a matter of fact, XP's engineering practices are often adopted within the context of Scrum, which acts in those cases as a management wrapper for XP.

It's also worth noting the emergence of the so-called post-Agilism, which I believe represents several Rails programmers. Post-Agile developers are well aware of Agile methodologies, but don't identify themselves with them. They haven't reverted back to a waterfall, heavily processed approach, but rather try to apply the good, fundamental Agile principles to other development techniques as they fit, doing what works best for them, without being dogmatic about the approach taken. To learn more about post-Agilism, you can read the FAQ at http://www.kohl.ca/blog/archives/000184.html.


The reason for its success was that in its simplicity, the video gave away the fact that Rails was extremely productive. It was more than just productive; it was magical. The application was only 58 lines (in the case of the video from 2005, referenced previously). In virtually no time at all, there it was, a working, albeit basic, Web log engine.

Admittedly, part of the magic was due to the fact that David employed dynamic scaffolding, a feature that allowed him to add columns to the tables and see the forms in the browser automatically update to accommodate the new columns. But from Rails 2.0 onward, this feature no longer exists. When it was included, it made for some great demos, but was usually not suitable and flexible at all for real-world projects. At the time, even the normal (static) scaffold wasn't a particularly good starting point for real applications, so when they wrote the new one, they got rid of dynamic scaffolding as well.

The point was that Rails brought productivity to a whole new level with its lack of configuration. David didn't have to write a connection string that was a few hundred characters long, he didn't have to use an IDE to pre-generate a lot of code for him, and he didn't have to specify the mapping between tables and the Ruby code anywhere either. He was just a guy with a text editor (TextMate), a command line, and a browser.

The only piece of configuration required was to add his password for the database to a file (config/database.yml) that was generated by the rails command at the beginning. In the video you can hear David point this out: "Look at all the things I'm not doing, look at all the configuration I'm not writing."

Developers (and their managers) love to hear that a new framework will make them much more productive. When the productivity claim is found to be true, as intuitively shown by David's demo, the effort and time investment required to learn a new framework becomes both justified and welcomed.

Rails tackles the problem of increasing productivity from several angles. But at its heart, the philosophical principle of favoring Convention over Configuration is fundamental to Rails' productivity and hassle-free development.

Frameworks are supposed to make your life easier, allow you to write better and more maintainable code, and improve your productivity by letting you focus on the logic of your application rather than repetitive, dreary details (for example, configuration). Far too many frameworks fall short of this goal, because they don't endorse the principle of Convention over Configuration nearly enough.

Frameworks need to have a set of sensible defaults straight "out of the box," and they should force you to resort to configuration only when strictly necessary, because their defaults are not suitable for your specific project requirements. When naming conventions fail, the framework should be flexible enough to allow you to add in your own configuration.

Ruby on Rails empowers developers to get started quickly by just learning a few naming conventions and, as they become more experienced, allows them to overrule these conventions through configuration for unconventional scenarios and edge cases. As such, it becomes particularly productive if you follow its conventions whenever possible, in order to reduce the amount of configuration required. In other words, try not to contradict Rails.

If you think about it, Convention over Configuration is a universally good software design paradigm. If you're defining an API, library, or framework of your own, always provide defaults that make sense and allow these conventions to be easily overwritten, if the need arises.

As mentioned a few times now, a model's identifier should be singular (for example, Project), and in turn it is automatically mapped to a table of the same name, only pluralized (for example, projects). Each table is supposed to have an auto-incrementing field called id. Associations between models assume that the naming convention for foreign keys is adopted. For example, the foreign key in the tasks table referencing the projects table will be called by convention project_id. You get the idea.

Understanding how ActiveRecord works is one of the most direct ways of experiencing the power of Convention over Configuration, so pay close attention to Chapters 5, 6, and 7. Rest assured that naming and other useful conventions, which you'll need to know, are explained throughout this book as they are introduced.

2.4.2. Don't Repeat Yourself (DRY)

Try to think about any software project you've worked on in the past. How long did it take before you had to go back and start making changes, essentially switching to maintenance mode programming? Contrary to popular belief, maintenance programming doesn't start after the first release is out. It usually begins much sooner: a few minutes after you wrote that initial line of code.

Programming is maintenance programming, even when you start with a fresh new project. The reality of this fact can be easily verified empirically if you sit down and try to come up with any program or Web application, no matter how small. You will start defining a few classes, some methods, and then you'll realize that something is not working right. You'll go back and make changes to the code to fix the bug that you just introduced a few minutes earlier. After a while you'll realize that certain portions of the code can be refactored and improved, and there you are, half an hour after you started writing your program, already doing maintenance work.

Maintenance and change can't be avoided, so why not embrace them? That's what Rails does by incarnating and promoting the Don't Repeat Yourself (DRY) principle, and the direct consequence is better applications that can easily accommodate change. DRY is about removing duplication and encouraging loosely coupled designs by ensuring that the ties between unrelated layers of an application are kept to a minimum (a concept sometimes referred to as orthogonality). The DRY principle promotes the localization of change, so that whenever requirements change (and that will definitely happen) the developer can respond to them by simply changing the application in one place rather than several.

What this means in practice is that you shouldn't repeat your code in several places, but rather find a single authoritative location in the application. For example, if several pages share a common element, you could "copy and paste" the code for that element onto each page, but if you ever need to change it, you'd have to go back to edit each applicable page. That's not DRY that's a mess. The proper way to do it would be to define a reusable component (for instance, using what Rails calls partials) that can be included on the desired pages, so that if you need to change it, you can do so in just one spot.

And the principle of not repeating yourself extends far beyond your application's code. A software project will typically have code, a database schema, tests, and documentation. If your coding style and the framework that you use don't endorse the DRY principle, you will find yourself juggling each of the components of your system, in an attempt to keep them all in sync.

Rails offers you plenty of tools to prevent this from happening. The MVC architecture neatly separates concerns; ActiveRecord's Object-Relational mapping creates a correspondence between your business and database objects; the migration system allows you to keep the database schema and its evolution under control; excellent testing capabilities are available "out of the box" so that you can have more confidence in accommodating changes; and the documentation can be automatically generated from the code, hence, if you change the code and its comments, this is automatically reflected when you generate the documentation.

When developing Rails applications you should always keep the DRY mantra in mind. Thankfully, Rails was designed from the ground up in a manner that allows you to espouse these philosophies. As you gain more knowledge about the framework, you'll realize how many options are available to keep things DRY and avoid the need to write similar code more than once.

That said, remember that the best tool against coupling and duplication is your brain. No matter how good a framework is at promoting superior development practices (and Rails is definitely excellent in this regard), there is no substitute for the developer actively pursuing the application of the principles illustrated to obtain productivity and code that is maintainable and easy to change.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.137.212.124