Red Code, Green Code
The Performance Zone is presented by AppDynamics. Scalability and better performance are constant concerns for the developer and operations manager. Try AppDynamics' fully-featured performance tool for Java, .NET, PHP, & Node.js.
This post comes from Merlyn Albery-Speyer at the New Relic Blog.
I’ve got an idea I want to share with you. It’s the concept of Red Code and Green Code. Now, this doesn’t have anything to do with the red / green / refactor cycle, code coverage or testing. You’ll know Green Code when you see it. It’s code that’s made elegant due to some cleverly written supporting Red Code.
Here’s an example of Green Code in Ruby:
class Customer < ActiveRecord::Base has_many :orders end
In this code snippet,
has_many is ActiveRecord’s Red Code. There’s a lot of machinery backing the
has_many code that the Green Code doesn’t need to concern itself with.
You’ll often find Red Code in frameworks, APIs and DSLs. There are numerous examples including Gradle, Geb, jQuery, Mocha, Rake, Rails, RSpec, and Spock. And depending on the language, Red Code typically makes heavy use of some of the more powerful language features (e.g. meta programming in Ruby, byte code manipulation in Java).
However, the Red Code / Green Code concept isn’t a new one. In his book On Lisp, Paul Graham referred to this as Bottom-Up Programming. Graham encouraged his readers to increase the expressiveness of the language (Red Code) in order to make their code shorter and more readable (Green Code).
Depending on the task you’re trying to solve, you’ll probably want to be careful about writing any Red Code as it is apt to violate the principle of least surprise. For example, in Java you may come up with a clever solution using reflection. But reflection is unusual enough that it will likely trip up unsuspecting navigators of the code. As a good rule of thumb, candidates for Red Code are areas of your code that would make good open source libraries. To be worthwhile, the benefit of the Red Code has to outweigh the cost of discovering the unusual behavior, learning its proper usage and maintaining the more complex solution.
To illustrate this, take a look at the code behind Backbone.js. It’s very much Green Code and there are no big surprises. Then compare it with Angular, where there’s clearly Red Code under the hood. When you use the frameworks, you’ll notice the difference, too. Backbone.js is easier to get into, but you need to write a fair amount of boiler place code. On the other hand, Angular has ‘magic’ conventions that take time to get use to. But once you’ve adjusted to how it work, you’ll benefit from the reduced boiler plate code.
Do you have experiences working with or writing Red Code and Green Code? Tell us about your experiences in the comments below.