Friday, January 31, 2014

AutoMapper for Java

In a nutshell ordinary web service takes entities from datasource (our domain model) and transforms them into DTO objects (our view models) or vise versa. This is quite popular approach becase it allows evolving domain and view models separately. Also it is neutral because one entity might have more than one narrow view models depending on needs. This is direct way to CQRS approach where read and write models are different at least for consumer's perspective.

 I do not consider another approach here where domain entities are intended to be mapped directly into json or xml. It is inextensible and ugly from my perspective however is quite attractive and simple.

Well, as mentioned I prefer the first approach, and if you had used it as well  then you definetly had to face with developing convertors layer. This is the most annoying and dissapointing part and place where bugs live in prosperity.

Since .NET I liked well-known library AutoMapper, it is lightweight smart convertor which allows transparent and codeless converting between domain and view models. For many cases it was Holy Grail.
I expected similar lib for Java as well and yes found it:  ModelMapper.

Consider this  example:

class User { 
  String firstName;
  String email;
  String creditCard;
}
 
class UserDTO{  
  String firstName;
  String email;
}

And lets consider how it might be transformed:
User user = ...
ModelMapper modelMapper = new ModelMapper();
UserDTO userDTO = modelMapper.map(user, UserDTO.class);


Thinking it is trivial? Well, how about this?
class User {
  Date burthday;
  String firstName;
  Address address;
}
class Address {
  String country;
  String street;
}
 
class UserDTO{
  long burthday;
  String firstName;
  String addressStreet;
}

And solution:
Converter<Date, Long> timeConvertor = new AbstractConverter<Date, Long>() {
  protected Long convert(Date dt) {
    return dt.getTime();
  }
};
 
ModelMapper modelMapper = new ModelMapper();
 
modelMapper.addConverter(timeConvertor);
 
UserDTO userDTO = modelMapper.map(user, UserDTO.class);

Going further this library is smart enough to care about ambiguity, skipping, diffrent naming strategies, mapping in advance and so on.

Well the library is attractive, however there is no magic and reflection is used there, so be aware.


Saturday, January 25, 2014

Why I like scala (part 1)

I bet many developers hate way Java has been evolving for many years. For instance resource safe cleanup feature. Java committee still were discussing, to add or not to add while C# already had nice language keyword using. You might say, Hey, Java 7 already has it. Right, however there are many others pending features that still wait to be added.

However I think that the problem is not only in Java committee. The problem is in language evolution and key grammar rules. Java is not scalable language. Almost every feature requires changes in Java grammar. So many keywords, and it might be greater. Jast take a look on C#. I love C# however number of keywords makes me dissapointed.

Well, there is another set of languages where there is no needs to modify grammar to add something interesting, moreover, there are languages which might create so high-level abstraction  that even their creaters could not expect such usage.These languages are C++, Haskell and Scala (this list is not complete).

Scala has no resoure safe cleanup feature and never won't. Because you can build it on your own.
Let's  develop this feature ourselves.

Version 1. (through dediated trait)
Lets use some trait Closable with just one operation close. Thus implementation might look like this:


trait Closable{
  def close(): Unit 
}

object Using {
}  
  def apply[A <: Closable, B](closeable:A) ( task : => B)  = {
      try {
        task
      } finally { closeable.disconnect }
  }
}

This version is simple and stratforward (just uses curring and parameters by name) however requires inheritance from Closable trait.

Here is usage example:

val resource : Closable = ... // take closable resource

Using(resource){
  // doing something with resource 
  // being confident that it will be closed
}

//ha-ha you can use it even this way
val resource2 : Closable = ...

val ret = Using(resource2){
  // return something meaningful
}

This implementation is simple however requires supporting Closable contract from all involved resources . You  might think that this is serious limitation. Well it is not true. Thanks to implicit boxing we can substitute any external resource with proper boxing object:

implicit def transform(r : InputStream) = new Closable{
  override def close(){
    r.close();
  }
}

val resource = new FileInputStream("/myfile")

Using(resource ){
  // read from resource resource 
}

Version 2. (through Duck typing)
 Scala has quite interesting feature anonimous structural types. New implementation based on structural types can accept any resource of any type (!) with only one requirement -  it should contain just close method inside.
object Using {
  
  def apply[A<:{ def close(): Unit; }, B](closeable:A) ( task : => B)  = {
      try {
        task
      } finally { closeable.disconnect }
  }
}
However despite that this approach is pretty attractive please be aware structural types are implemented via reflection, so it might affect performance a bit.

One more amazing example is synchronized sections. Java has special keyword synchronized. However for scala it is just ordinary method of AnyRef class.
God bless functions and parameters by name.




Friday, January 24, 2014

Clustering Java applications

Trying to explain two so different approaches based on Terracotta and Hazelcast. Enjoy!

MongoDB Distilled

OMG- it was about one year ago.

Spring AOP Introduction

My presentation from Summer Odessa JUG


Continuous DB Migration

Моя презентация с последней встречи Одесской Java группы.

Полезное чтиво. Выпуск 2.

  • CQRS Journey - http://msdn.microsoft.com/en-us/library/jj554200.aspx 
Прекрасное путешествие с наглядным объяснением, что такое Domain Driven Development, CQRS и Event Sourcing. Книжка дает чистый и понятный способ того, как приложение со сложной бизнес логикой и составным доменом может быть разработано. 
  • Developing Multi-tenant Applications for the Cloud
Тема multitenant  приложений становится довольно популярной, и многие заказчики требуют для своих приложений поддержку tenants. Принимая во внимание высокую облачность в последнее время, работу с tenants можно действительно сделать элегантно и масштабируемо.

  • Microsoft Application Architecture Guide - http://msdn.microsoft.com/en-us/library/ff650706.aspx
Отличное описание того, о чем нужно говорить в Software Architecture документах. О каких ключевых решениях может идти речь перед началом проекта. Да и вообще. НЕсмотря на приставку Microsoft рекомендую книгу Java иноверцам, речь идет о фундаментальных вещах, ну а аналогичные технологии есть и в Java.
  • UI  patterns - http://ui-patterns.com/
Хорошее и систематичное собрание разных UI патернов.

  • Writing Great Unit Tests: Best and Worst Practices - http://blog.stevensanderson.com/2009/08/24/writing-great-unit-tests-best-and-worst-practises/
Довольно понятным языком объясняется разница между модульным и интеграционным тестированием. ПРоверьте себя, знаете ли вы какими должны быть качественные модульные тесты.