Archive

Archive for May, 2010

Vim for the win :)

May 16, 2010 4 comments

I have been using Vim a lot in the last few weeks, to edit CSS and HTML files. It might seem a bit awkward at first but once you get used to it, it becomes great!
What helps a lot too is to configure Vim properly to make it perfect for use.
Vim and Vi configurations are done by setting variables using :set or by editing the file .vimrc in your home folder.
I will share here my Vim configurations and some of the commands I use more often. It also works as a Vim cheat sheet for my own future reference.

So, my ~/.vimirc looks like this:

set tabstop=2 expandtab autoindent smartindent shiftwidth=2 number

 
Here’s what each of them does

Configuration Effect
tabstop=N Sets the tab size to N spaces. The default is 4.
expandtab Tabs are expanded, when you press tab, N characters will be inserted instead of a tab character (where N is the amount of spaces set for tabstop).
autoindent Will keep the same indentation when you press enter in the end of a line.
smartindent Vim will try to automatically detect indentations. For instance, if you go to a new line and enter a ‘}’, Vim will go back one indentation level.
shiftwidth=N The number of spaces used for one indentation level.
number Shows lines numbers.

And here are some of the commands I use more often:

Command What it does..
:N goes to line N
/foo searches for ‘foo’
:%s/foo/bar/g replaces all occurrences of ‘foo’ with ‘bar’ in the current file
:s/foo/bar/g Same as above, but replaces only on the current line
:s/foo/bar/gc Same as above, but prompts for confirmation before replacing each occurrence of ‘foo’. Can also be used with ‘%’ to replace all occurrences in the file
Shif + G goes to the end of the file
v enter select mode
<< moves the current line one indentation level backwards;
>> moves the current line one indentation level forward;
yy copies current line to the buffer
dd removes the current line out and place it on the buffer
p pastes the text from the buffer on the next line

Also remember that many of these commands may be used with a different number of lines.
For instance, pressing 1, 0, d, d will delete he next 10 lines.

Any other cool commands for Vim? Let me know on the comments!

Categories: English, Linux, Programming

Grails: Separating the database access from the domain classes

May 8, 2010 4 comments

Some days ago I started working on my second project involving Groovy & Grails.
Grails is my first contact with server side development with dynamic languages, and, despite some small problems (mostly due to the fact that the framework is still not so mature compared to others out there), I really, really enjoy it.

One of the things that I like is how using Groovy’s dynamic features the framework injects database access technicalities into our domain classes.
The domain is therefore smart enough to retrieve/update its relationships and even to find/update itself, all without the need to pass around repositories dependencies whatsoever, or to force the domain classes to extend any other classes.

But sometimes we need to write HQL (or criterias) ourselves, and then in our first project we ended up having some domain classes quite bloated with custom queries and a lot of other database related operations mixed with pure domain-specific logic operations.

Something like this:

  class Book {
    // properties, mappings, constraints
    // domain methods

    def findAllBooksFromTheSameAuthor() {
      return findAll("some HQL")
    }

    def findSimilarPurchasedBooks() {
      return findAll("some HQL")
    }
  }

This code is just a silly example to illustrate the problem.
Of course we could have used Grails’ dynamic finders for those queries too, but we would be externalizing the internals of our domain class so we like this approach of adding custom query methods better.
One thing we didn’t like though, is that we had many methods like the ones above, mixed with the domain logic and properties.
So we decided to move these methods somewhere else and inject them into our domain classes, like Grails does with its dynamic generic finders.

A very nice way to do it seemed to be using Groovy’s Delegate annotation, having something similar to:

  class Book {
    @Delegate BookQueries bookQueries = new BookQueries(this)

    // properties
    // mappings, constraints, domain methods
  }

  class BookQueries {
    Book book

    BookQueries(Book book) {
      this.book = book
    }

    def findAllBooksFromTheSameAuthor() {
      return Book.findAll("some HQL")
    }

    def findSimilarPurchasedBooks() {
      return Book.findAll("some HQL")
    }
  }

We have to pass the book object to BookQueries because we are gonna need its properties to build our queries.
For instance, we need its author to find all books from the same author.
And using the delegate we can call methods from BookQueries with a Book object:

  book.findSimilarPurchasedBooks()

The only problem with this is that we also had some static methods to first retrieve our objects.
These are queries that are not related to any relationship or similarities between objects, so they are static methods in the Book class:

  static def findBestSellersInMonth() {
    findAll("some HQL")
  }

The problem is that static methods are not delegated.

In our project we decided to scrap the @Delegate for good, move all custom query methods to BookQueries, including the static ones, transform them into closures and inject them manually, one by one, into the Book class during the application BootStrap, using Groovy’s Expando metaclass.

But I didn’t really like this approach.
I think I’d rather keep the @Delegate, and then move the static methods to a BookRepository class:

  class BookRepository {
    def findBestSellersInMonth() {
      return Book.findAll("some HQL")
    }
  }

It might seem as a step backwards.. “why do you need repositories if you have your rich domain that can retrieve itself?”
But the static modifier already tells that these methods don’t belong to our domain *objects*.
They are there to initialize the objects, retrieve them from somewhere (the database).
And, well, isn’t this part of the definition of repositories? =P

Update — May 10th ———————————

Peter Ledbrook suggested using Grails’ named queries (see comments). It looks indeed very nice, but we really wanted to move our queries out of our domain class, to make it more readable and, well, prettier :D

With the named queries we could move a static block containing the static queries to the BooksQueries class and assign this static block to a static nameQueries block in the Book class, and this would import the static queries.

Today I was messing with this a bit more and I realized that I could just inject the static methods into my domain class from inside my delegate itself.
It’s so simple I don’t understand how come I didn’t think about that before :D
So, if you don’t like the repository approach, you can always have something like:

  class Book {
    @Delegate BookQueries bookQueries = new BookQueries(this)
    // all Book properties, constraints, domain methods, etc
  }

  class BookQueries {

    static {
      BookQueries.metaClass.methods.each {
        if (it.static) {
          Book.metaClass.static."$it.name" = owner.&amp;"$it.name"
        }
      }
    }

    Book book

    BookQueries(Book book) {
      this.book = book
    }

    def findAllBooksFromTheSameAuthor() {
      return Book.findAll("some HQL")
    }

    static def findBestSellersInMonth() {
      return Book.findAll("some HQL")
    }
  }

Follow

Get every new post delivered to your Inbox.