Neverending Groovy: map with default values

More and more Groovy openings for me every day!

Just today, I found that there is a way to setup default value for map entry, if absent. In some cases it may be very handy.

For example, I need to prepare a map with words counts. This simple task should be coded simple too, like:

def map = [:]
words.each { word -> map[word]++ }

But it's not working and fails with NPE exception. Why? Because it's hard to increment null.

Although, there is simple way to avoid this problem even using Groovy API:

def map = [:]
words.each { word -> map[word] = map.get('word', 0) + 1

Here 2nd parameter of map.get() method is the default value, returned if there is no value for key 'word'. And now it's working fine!
Still there is another way, and, as for me, it helps to make code clean and safe. Safe because default logic can be used elsewhere we want to use our map object.

def map = [:].withDefault { 0 }
words.each { word -> map[word]++ }


I bet there is a better way and I'm going to find it...

MySQL pager

I very liked to use psql command. Among different usability things, it uses less command to show query results. That was the thing I always wanted to have in mysql command. And was sure that's not possible, and till today was suffered in silence.

But today, quite unexpected for me, I found option pager for mysql command. This option let me set the program, I want to use to see query search results. So, to use less program, I was just need to start mysql with --pager parameter:

$ mysql --pager=less

or in mysql console:

mysql> pager=less

Now I'm happy to use it! And you should try too :)

Neverending Groovy

Вже кілька місяців коджу в основному на Groovy. Прекрасна мова, прекрасна підтримка від IntelliJIdea. Часто знаходжу все нові і кращі спрособи реалізації деколи тривіальних речей.

Для прикладу, необхідно отримати список із значень певного поля кожного елементу списку. Спочатку, я писав доволі простий і зрозумілий код, ясно ще під впливом Java:

List names = []
for (Person person : persons) {
names << person.firstName
}

З часом я удосконалювався і коду ставало менше:

def names = []
persons.each { names << it.firstName }

Виглядає дуже навіть зрозуміло, пишеться швидко і ще швидше читається.
Але і це не був край досконалості, і трохи пізніше я почав писати вже:

def names = persons.collect { it.firstName }

І цей кусок коду поражав мене тим, що був тільки 1 рядок, назва методу collect є зрозумілішою, ніж each у цьому конкретному випадку. І так, може, і писав би й дальше, якби не вирішив спробувати використати для цього spread оператора (*.). І тепер коду стало ще менше:

def names = persons*.firstName

Відмінністю від collect є не тільки простота написання, але і краща швидкодія.

І ось, в процесі написанні цієї статті, я відкрив для себе ще один спосіб. Коли починав писати цю статтю кілька хвилин тому, я вже не вірив, що може бути щось простіше, ніж використання spread оператора для вирішення моєї задачі. Але як виявилося, для отримання значення полів, використовувати spread оператор не є необхідним, і можна написати банально і просто:

def names = persons.firstName


Тож сиджу і думаю, а як можна ще простіше. Боюся зарікатися, що простіше вже бути не може, як вже зрозумів свою помилку кілька хвилин тому.

Groovy цікава мова, з якою все простіше і веселіше. Тож копати в Groovy, Python чи Ruby!

Book Review: 97 Things Every Software Architect Should Know

More then year ago I bought book 97 Things Every Software Architect Should Know for myself. I was expecting to get a book with some useful technical advices how to create cool software architecture,- that's what was always interesting for me.

Instead I've got the book with 97 small articles, each 2 pages long. No technical advices, no silver bullet, no advices on what and how use design patterns or modern technologies. Truly say, after reading few articles, I was upset. And leaved the book on my bookshelf and move on.

A year later, ie a month ago, I've took this book into my hands and decided that it's time to try to read it again. (Yes, I have a habit to re-read books again a year or two later, as found that it helps to understand much more and see the forest behind the trees).

I'm still reading this - few articles per week,- but decided to note my thoughts as review in this article.

In this attempt, book is very interesting. A year later my vision was changed cardinally again and now, I think, I can understand what those guys mean when they were writing their posts. These all can be said simply in one sentence:
Software Architects are bridges between business needs, software needs, technical needs and team needs.

Especially interesting were next articles for me (remember, I'm still reading):

  • Don't Put Your Resume Ahead of the Requirements

  • It Is All About The Data

  • Pattern Pathology

  • If You Design It, You Should Be Able to Code It

  • Empower Developers

  • Chances Are, You Biggest Problem Isn't Technical

  • Business Drives

  • Great Content Creates Great Systems

  • Start with a Walking Skeleton

  • Communication Is King; Clarity and Leadership, Its Humble Servants

I'm sure articles' titles are saying enough, so will not describe them. Want know more - just go and buy (as I did :)

A week ago I was reading "Business Drives" article. And especially remembered the summary of this article: "The long-term interests of the software development team are best served when business drives". And I agree with this summary. It's sad to know, that many software developers are still in the race for better skills and modern technologies if this is in damage for the project and business.

It's one of that books, that reminds that software is making by humans for humans.

So, my advise is to get and read this book; hope you're ready for it and hope I'm too :)

PS: Just found another review of this book http://dotnet.dzone.com/news/97-things-every-software

Groovy annotations

As I wrote in my last post Groovy 1.8 is still in progress. One of the new features I liked a lot is annotation support for AST transformations (i.e. @ToString, @Canonical etc.).

As I'm still acquainted with Groovy, I've decided to look what useful annotations it has already. So this post is about what was found.

There are next annotations in the groovy.lang package:

  • @Lazy
  • @Immutable
  • @Newify
  • @Singleton
  • @Mixin
  • @Category

Also want to describe them with few simple samples.

@Lazy

This annotation can be applied to class field. As result new instance for field value is created on get method call for field property. In this case Groovy generates getter method for you, that checks whether field is not initialized yet and initialize it in this case, otherwise returns its value:

@Lazy T x

generates next code:

private T $x

T getX() {
if ($x != null)
return $x
else {
$x = new T()
return $x
}
}

You also can do lazy field initialization with specified value, just assign this value for field with @Lazy annotation:

@Lazy T x = new T(code: 'S')

That will generate next code:

private T $x

T getX() {
T $x_local = $x
if ($x_local != null)
return $x_local
else {
synchronized(this) {
if ($x == null) {
$x = new T(code: 'S')
}
return $x
}
}
}

Absolutely useful thing with only a few of keypresses. That's awesome.

Read more in GroovyDoc

@Immutable

Used to mark classes and make them immutable. That's mean that your class becomes final and nobody can change value field value and you get tuple and map based constructors. Also Groovy generated toString(), hashCode() and equals() methods for you. You should also need to be sure that fields types are immutable, primitives, strings, enums or are annotated with @Immutable.

Read more in GroovyDoc

@Newify

This annotation is perfect for DSL expressions. With it you can change creating new objects expression, for example, use

def b = Book('The Best Book Ever')

instead of

def b = new Book('The Best Book Ever')

Read more in GroovyDoc

@Singleton

Well, another annotation that makes your life easier. As you maybe already understand, this annotation is for types and make them singletons.
getInstance() method is generated for you, so simply call it when you need new instance. If you set annotation lazy parameter to be true, your singleton instance will be created on first call to this method. As for this case method supports double checking locks, you may be sure that only one instance will be created. Here is some sample:

@Singleton
class Player {
def play() {}
def stop() {}
}

...

Player.instance.start()

Read more in GroovyDoc and Singleton transformation.

@Mixin

Used to mix one or few types into annotated type. As result, you can have a class that have members (fields and methods) from other classes, specified in the annotation. And here is sample:

class Book {
String name
String author

def find(text) {
....
}
}

@Mixing(Book)
class HardBookMetadata extends Metadata {
int pages
String publication
}

....
def metadata = new HardBookMetadata()
metadata.title = 'Some cool title'
metadata.author = 'Ruslan Khmelyuk'
metadata.pages = 400

println metadata.find('cool')

As you see, using variable metadata of HardBookMetadata type have access to Book members.
Yeah, this also can be used with @Category.

Read more in GroovyDoc.