My technical – books backlog

21/05/2011

I have read several books about programming, testing and usability. They have influenced me so much in my professional career that I have decided to share them in a book backlog.

I started my career reading about patterns, refactorings, and XP best practices, and I am currently reading about testing, agile principles, and dynamic languages like Ruby. With every book I have learnt a lot, but If I have to select the books that have influenced me the most, I would list the followings:

  1. Writting Solid Code

    This extraordinary book taught my how to deal with preconditions, postconditions, invariants, and other technics to write solid code. It was written in C, but the ideas were cross-language.

  2. The inmates are running the asylum

    This book should be a must read book for all engineers. It explains you how the client has a differente mental model than yours, and how to fulfill user needs thinking about the applications as a way to provide big goals, and not as a powerful combination of functionalities (the natural design for an engineer)

  3. The RSpec book

    This book is fantastic. After reading this book you’ll be able to write expressive, readable and simple tests. Mocks and Stubs are explained on such an easy way, that you won’t be able to test without them. A really brilliant book.

  4. The Ruby programming language

    This books really changed my mind, and my mental model for programming. What’s the point of a Static Type Checking language? It has no sense nowadays. Ruby is simply amazing. It’s clean, expressive, concise, simple, and powerful. In my opinion static languages (like Java) are conceptually dead, and are only supported because it is difficult for a big industry (IT) to move to a more productive language. I’d recommend you this book, If you are having mental frictions coding Java.

Feel free to visit my books backlog

2 Comments

Extending Ruby to validate required keys in a Hash Table

28/03/2011

This post explains how to extend Ruby to validate the keys of a Hash Table.

The following piece of code is an example of our goal:

  a_hash_table.assert_required_keys(:required=>[:p1,:p2],:optional=>[:p5])
  1. Required keys => p1 and p2
  2. Optional Keys => p5

For example:

def do_operation(a_hash_table)
  a_hash_table.assert_required_keys(:required=>[:p1,:p2],:optional=>[:p5])
  # some_operations_with_hash_table
end

do_operation { :p1 => "v1" , :p2=> "v2" }
# => Passes

do_operation { :p1 => "v1" , :p2=> "v2", :p5 => "v5" }
# => Passes

do_operation { :p1 => "v1" , :p2 => "v2", :p4=> "v2" }
# => ArgumentError: Unknown key(s): prop4

do_operation { :p1 => "v1" , :p4=> "v2" }
# => ArgumentError: Unknown key(s): prop4

To support this funcionality, I first thought that Rail’s extension was a good option, but its semantic was completely different to what I needed. I expected this method to validate the required keys, and ignore the rest, but the method dealt with optional but fixed lists of params (i.e. when the keys are optional, but all keys has to be valid)

This is the extension I coded:

module ActiveSupport
  module CoreExtensions
    module Hash
      module Keys
        def assert_required_keys(params)
          params[:required] ||= []
          params[:optional] ||= []
          assert_valid_keys params[:required] + params[:optional]
          pending_keys = params[:required] - keys
          raise(ArgumentError, "Required key(s) not present: #{pending_keys.join(", ")}") unless pending_keys.empty?
        end
      end
    end
  end
end

I have to confess, that after a long time coding Java, I was looking forward to find a situation where I can get the most of Ruby (always with Golden Hammer or No Silver Bullet antipattern in mind); and it was last weekend, when I was working on a personal project, when I found it.

If you are new to Ruby on Rails, there are some expressions that may sound a bit weird when reading the code above, but they aren’t, as they are supported by the underlying dynamic nature of the language.

Possible question:

Q1: assert_required_keys is a Hash method and it isn’t supported in the API

  • Using Ruby on Rails you are able to extend the runtime code without altering its source code. So, as in Ruby new methods can be defined per class or Object, Rails extends Hash Class to support the method assert_required_keys and customize its behavior.

Q2. Where does Rails use this extension (assert_valid_keys)?

  • Rails uses this validation very often, for example, when invoking fresh_when method in Module ActionController::ConditionalGet. Here is the source
# File actionpack/lib/action_controller/metal/conditional_get.rb, line 26
def fresh_when(options)
  options.assert_valid_keys(:etag, :last_modified, :public)

  response.etag = options[:etag]  if options[:etag]
  response.last_modified = options[:last_modified] if options[:last_modified]
  response.cache_control[:public] = true if options[:public]

  head :not_modified if request.fresh?(response)
end

Conclusions

  • Coding Ruby is a difficult but extremely funny experience,  and coding this extensions improve my skills changing my mind from traditional Java programing to a dynamic Object Oriented  language

  • Coding with a dynamic language, allows you to decouple the dependencies between objects, as no interfaces, nor helper methods are needed, and new functionality can be added to its proper place without worrying about the impact in your whole application. You focus on what you want to do and not in how to accomplish it.

Other References:

  1. Ruby Quick Tipos
  2. Peter Marklund article

Hope it helps!

No Comments

Refactoring in Ruby, a really funny game!

12/07/2010

I’ve been studying Ruby for the last months. After all these time I’ve discovered a really productive way to face software development.

Ruby is incredibly expressive, clean, simple and powerful. Writing ruby code is so funny and relaxing, that refactoring code make me feel like playing a mental game (a game we play against ourselves trying to improve our own code)

Let’s refactor a very simple piece of code (just for fun):

a. Insert into source array a list of negative numbers from -20 to -1

# source <== [-10, -9, -8, -7, -6, -5, -4, -3, -2, -1]

b. Return an array with its absolute values

# target <== [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]

Ok, let’s start writting this functionality in its longest way… (as if we where coding in Java)

source = []
(-20..-1).each do |number|
  source << number
end
target = []
source.each do |number|
  target << number.abs
end

Lets use Ruby’s map function so, you don’t have to pre-build the response on target array

source = []
(-20..-1).each do |number|
  source << number
end
  target = source.map do |number|
number
.abs
end

Lets rewrite target closure using brackets (recommended with one line of code blocks)

source = []
(-20..-1).each do |number|
  source << number
end
target = source.map { |number|  number.abs}

Ranges are objets, so looking into RDoc documentation, you can find that every range can be converted into an array directly:

source = (-20..-1).to_a
target = source.map { |number|  number.abs}

Lets write it in one line

target = (-20..-1).to_a.map { |number|  number.abs}

Now, Ruby’s dynamic cohercion to simplify the closure…

target = (-20..-1).to_a.map(&:abs)

Let’s explain the last step:

& operator converts a Proc into a block, and passes it to map function. But :abs is not a Proc, so Ruby tries to convert it into a Proc (dynamic cohercion).

How is it converted?, :abs is converted invoking its to_proc method (:abs is a Symbol, and has a to_proc method)

to_proc method looks like the following:

def to_proc
proc { |obj, *args| obj.send (self, *args) }
end

In the code above

  1. self is the Symbol. The one with to_proc_ method
  2. object is an element of the collection (each element in the collection passed to the closure)
  3. send is the method invocation.

Can’t be easier.

Besides the last magic conversion, the simplification has been achieved because:

  1. Ruby is an expression-oriented language; as every expression returns a value, method calls may typically be chained or stacked. This means, for instance, that code becomes more compact as the common parts are factored out and repetition is removed (DRY)
  2. Variables do not have types (but objects, of course, do)
  3. Range are also Objects. Range literals are written by placing two or three dots between the start and the end value.
  4. Closures are written on a extremely expressive way (and map function is great!)

Hope it helps!!

2 Comments

DDL generation with Spring and Hibernate

11/07/2010

This post explains how to generate the Drop / Create / Update DDL for a Hibernate + Spring application

This is really a simple post, but I’ve found it very helpful in the project I’m working on.

In the first phase of a project, using hibernate.hbm2ddl.auto property, with validate | update | create | create-drop values, is more than enough, but when developers are able to work with different environments (using Maven profiles or ant), I feel insecure with automatically DDL executions that could affect to preproduction or even production environment in case of problems.

This is why I’ve been looking for a simple way to generate the update / create / drop DDL for my application.

The solution is quite simple:

import java.sql.Connection;
import java.sql.SQLException;

import org.hibernate.cfg.Configuration;
import org.hibernate.dialect.Dialect;
import org.hibernate.dialect.Oracle10gDialect;
import org.hibernate.tool.hbm2ddl.DatabaseMetadata;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean;

public class DDLGen {

  public static void main(final String[] args) throws SQLException {

    final String[] context = new String[] { "/applicationContext.xml", "/applicationContext-ds-test.xml" };
    final ApplicationContext apContext = new ClassPathXmlApplicationContext(context);
    AnnotationSessionFactoryBean sessionFactory = (AnnotationSessionFactoryBean) apContext.getBean("&sessionFactory");

    final Configuration configuration = sessionFactory.getConfiguration();
    final Connection connection = sessionFactory.getDataSource().getConnection();
    Dialect dialect = new Oracle10gDialect();
    DatabaseMetadata metaData = new DatabaseMetadata(connection, dialect);

    final String[] dropDDLs = configuration.generateDropSchemaScript(dialect);
    final String[] createDLLs = configuration.generateSchemaCreationScript(dialect);
    final String[] updateDDLs = configuration.generateSchemaUpdateScript(dialect, metaData);

    printDDL(dropDDLs);
    printDDL(createDLLs);
    printDDL(updateDDLs);
  }

  private static void printDDL(String[] ddls) {
    for (String ddl : ddls) {
      System.out.println(ddl.concat(";"));
    }
  }
}

After reading the code, you may find estrange the following:

1
2
AnnotationSessionFactoryBean sessionFactory =
  (AnnotationSessionFactoryBean) apContext.getBean("&sessionFactory");

As you can see, in the code above, &sessionFactory is obtained from Spring Context instead of sessionFactory just because we don’t want to get what the factory builds, we just need the factory.

Hope it helps!!

No Comments

Why Rework is a good choice if you are building a Business in Internet

15/05/2010

“Rework is a Common Sense Guide to Growing a Business (not necessary in internet)’. This book will inspire you and help you to feel more confident in your way”

Rework Front Cover

I finished reading Rework a few days ago, and I’ve found it very interesting and helpful; most of the ideas aren’t new, but it’s the union of all of them, and how they’re applied together, what turns rework into a must read book.

The book is written by Jason Fried and David Heinemeier. David Heinemeier is the creator of the web-application framework Ruby on Rails, and they both work at 37signals, a privately-held Chicago-based company which is famous for the simplicity and quality of theirs products.

The business philosophy of the book is very similar to how David Heinemeier designed Ruby on Rails language, and also to the philosophy behind 37signals software products:

  1. No complexity.
  2. No constraint rules.
  3. Result oriented.

The book is so easy and quick to read that, also if you don’t like it very much at the end, you won’t have wasted to much time. In some way reminds me to the brilliant book: Don’t make me think

If you are an entrepreneur, and you are about to start an MBA, it may be a good idea to add this book to the list of books you’ll have to read. It will possible give you another point of view that will help you in your way.

No Comments

Easy tools? No, they’re productive tools!

21/02/2010

“Software environment has completely changed in the last months… but it’s not the last one, it’ll change more times. Are we ready to face this process?, Will we get the most of it?, Will companies fail again with these new techologies?”

tools

Everybody talks about Spring ROO, Grails, Ruby on rails, Agile Methods and the message that’s being sold to managers and clients is that they are very easy tools, and that great results will be obtained within a few months. But, is it really true?

  1. From a technical point of view: of course they are very useful and productive tools, and of course, great results can be achieved very quickly.
  2. But, from a management point of view, most of the times, this information (great news) is translated into:
    • Ok, as we are using “easy tools” we could hire less expertise professionals and save money
    • Ok, as we are using “easy tools”, we’ll finish earlier as learning curve is short for all participants.
    • Ok, so If we use an agile methodology, we’ll have the release exactly on March 23th 2011 (without a cone of uncertainty)

If we turn back a couple of years, we find the same situation: new technologies and the same speech (MDAs for example). But, is there any difference between these old “productive” technologies and nowadays productive tools?. MDA tools were also sold as easy tools that let anybody be highly productive in any software project because they generate the code for you. Anyone can use them!! But sometimes MDAs have completely failed, and if we stop and think carefully about the following questions, we may realize what the problem is.

  1. What was our real problem? MDAs?
  2. What was the skills of professionals?, Was there a Technical Director for the project? (or his role wasn’t necessary because of easy tools)
  3. Did professionals master the underlying technologies to MDAs?
  4. How did they deal with problems?, How many time did they spend solving those problems?

Conclusions:

This post is a quick reflexion just to remind us that:

  1. The information doesn’t flow correctly among all the participants in a project, as it is transformed due to different mental models between technical and non technical professionals.
  2. “Easy tools” doesn’t mean: unexperienced professional can master the tools.
  3. We have to be careful with the words we use when describing new technologies, specially when we talk with non technical professionals and we say something is easy (they think on a different way!)
  4. “Easy” is a characteristic that is necessary but not sufficient for a tool to be productive. Professionals are the key point to develop a high quality product on time.
  5. Learning curve is short for experienced professionals; but it could take more time for junior programmers to be really productive in an experienced team. Sometimes they’ll be 100% productive in the next project (and will became key participants). In my opinion, the percentage of junior programmers / experienced programmers can’t be superior to 20%.
  6. Development teams has to change. Traditional functional documents has no sense nowadays; a reduce number of highly expertise professionals, using productive tools, mastering the underlying technologies and prototyping on an iterative and agile process are the best solution for a project to complete succeed.
No Comments

Increase your productivity with Evernote

7/02/2010

“Evernote makes it easy to remember things big and small from all parts of your life, using your computer, phone, and the web”

Ico Evernote

This entry is about using evernote in a development environment

When I first visit ThinkWasabi blog (brilliant spanish blog about productivity), I discovered an application that has completely changed the way I have to organize the huge amount of information I have to deal with in my every day work.

This application is really helpful in my personal life as I store and tag dozens of notes every week, but that’s not the key point of this entry, nor I’m trying to explain in detail its functionality (this screencast could be a good start point – spanish – )

What I’m trying to explain, is how I use Evernote in a development environment, how it improves my productivity when tasks that could take 5 minutes, could be reduced to 3-4 seconds, and how I’ve found an application that easily archive and find any kind of information within seconds.

My basic rules

  1. These are the tags I frequently use when archiving information in a development environment:
    • “server”: any kind of information about IP or DNS directions of servers: databases, subversion repositories, CVS repositories, Application Servers, etc
    • “config”: Information about how to configure: JDBC driver connections, JNDI properties, Maven dependencies, etc
    • “code”: Snippets of code. I also add the tag corresponding to the language (java, c++, sql, etc); and if it’s written by me I tag it with mine
  2. I always add a tag with the short name of the project. It’s the temporal context of the note, as it’s more easy for me to link notes and projects, than notes and years or months.
  3. I add notes with ebooks in PDF or CHM format just for quick reference searching. It’s also absolutely necessary for me to add the books I’ve already read in PDF format.

Conclusions

  1. The most important benefit is not the time I’m saving while searching information, in my opinion, the mayor improvement is: I’m not loosing the focus on what I’m doing (the main goal), because I don’t suffer from interruptions and I keep concentrated when trying to access to archived information

  2. As important as search time is the time we spent archiving and organizing the information. What is the cost of not archiving information because you feel terrible lazy with the process? What if you have a tool that allows you to tag any kind of information within seconds? Evernote is a great help and fill these gaps

  3. I don’t suffer from artificial conventions in my mind, nor complicated directory hierarchies because tag searching is completely natural for my human mental model.

  4. The last benefit is the comfort, control and security sensations when archiving the information with evernote, it’s similar to how gmail allows a user to archive emails and find them in seconds with its search engine.

Reference links

  1. Evernote
  2. Thinkwasabi
  3. Evernote wikipedia
2 Comments

Hello world!!

6/02/2010

Welcome to my professional page. I’ve started this blog just to share my ideas and experiences in development world where I’ve been involved as a professional since 2001 .

If you can’t guess why these are my first comments:

  /**
    First comments
  */
  //  Second comments

or why the title of this entry is Hello World I’m afraid you won’t feel very comfortable here, but anyway, you’re absolutely welcome!!

No Comments