DEV Community

Cover image for The Art of Initialising Objects
Hartmut B.
Hartmut B.

Posted on

The Art of Initialising Objects

Last week, I wrote about Composition in Ruby. A module was used to masquerade the initialization of an Object.

This post introduces another way to simplify programming.

Ruby class names, like their java counterparts, tend to be verbose. They are sometimes easy to remember. Programs -- on the other side -- are sometimes difficult to read.

In the other Post a cryptic Class.new was transformed to a speaking Object-call:

# Previously
> Order.new kind: price: 5, ordertype: :lmt, total_amount: 100
# result
> Limit.order price: 5, size: 100
Enter fullscreen mode Exit fullscreen mode

However, this approach requires some overhead.

A Remind to Stenography

A long time ago, mostly women had the capability to write as fast as one can talk. They substituted long phrases with something they mysteriously could translate to readable words later.

The same technique is useful to clarify ruby scripts, too

A few days ago, I had to write some queries for ActiveOrient. The query-generator is located in OrientSupport::OrientQuery.

For each subquery a new object is created.

In a script, its obvious that one can choose another constant to substitute the long name. This fails if used elsewhere and is truly bad practice.

Lamba's to the rescue

As many modern ruby-classes, OrientSupport::OrientQuery is initialized with a bunch of hash-items.

> query =  OrientSupport::OrientQuery.new  from: TheList, where: {name: 'Maria Hellweg' } )
Enter fullscreen mode Exit fullscreen mode

Define a Lamba

> q = -> (**args){ OrientSupport::OrientQuery.new **args }
Enter fullscreen mode Exit fullscreen mode

Then the simple query can be rewritten

> maria = q[ from: TheList, where: {name: 'Maria Hellweg' } ]
> maria.to_s
 => "select from the_list where name = 'Maria Hellweg' "
> maria.execute (...)
Enter fullscreen mode Exit fullscreen mode

This trick creates a new query-object just by typing q[].

This is must helpful to create standard-queries


> q[ projection: address, from: TheList, where: {name: 'Maria Hellweg' } ].execute
=> "Walddornweg 23"

Enter fullscreen mode Exit fullscreen mode

and it can be nested

>  q[ from: q[ from: TestQuery, where:{ a: 2 , c: 'ufz' } ], kind: 'traverse', projection: :day).to_s
 => "traverse day from ( select from test_query where a = 2 and c = 'ufz' ) "
Enter fullscreen mode Exit fullscreen mode

Conclusion

Commonly lamba's are used to introduce aspects of functional programming to ruby scripts. However, they can create objects as well.
This trick avoids assignments of simple constants to complicated class names. Its a strictly local solution with minimal overhead and without any side effects.

Top comments (0)