Tuesday, January 10, 2012

Xperiencing Xtend in a Java EE 6 Web Application

Just saying that to date I'm quite happy with using Xtend in a regular Java EE 6 web application.

It allows me to write this:

    def void reindexSlugs() {
        log.debug("Reindexing slugs")
        slugProvider.clear
        val slugList = userRepo.findAllSlugs.toList
        log.debug("Reindexing slugs for {} users", slugList.size)
        val slugMap = slugList.fold(new HashMap<String, String>(),
            [map, row | map.put(String::valueOf(row.get("slug")), String::valueOf(row.get("id"))); map ]
        )
        slugProvider.batchUpdate(slugMap)
        log.debug("Reindexing slugs")
    }

Instead of: (Xtend-generated Java)

  public void reindexSlugs() {
      this.log.debug("Reindexing slugs");
      this.slugProvider.clear();
      Iterable<Map<String,Object>> _findAllSlugs = this.userRepo.findAllSlugs();
      List<Map<String,Object>> _list = IterableExtensions.<Map<String,Object>>toList(_findAllSlugs);
      final List<Map<String,Object>> slugList = _list;
      int _size = slugList.size();
      this.log.debug("Reindexing slugs for {} users", Integer.valueOf(_size));
      HashMap<String,String> _hashMap = new HashMap<String,String>();
      final Function2<HashMap<String,String>,Map<String,Object>,HashMap<String,String>> _function = new Function2<HashMap<String,String>,Map<String,Object>,HashMap<String,String>>() {
          public HashMap<String,String> apply(final HashMap<String,String> map, final Map<String,Object> row) {
            HashMap<String,String> _xblockexpression = null;
            {
              Object _get = row.get("slug");
              String _valueOf = String.valueOf(_get);
              Object _get_1 = row.get("id");
              String _valueOf_1 = String.valueOf(_get_1);
              map.put(_valueOf, _valueOf_1);
              _xblockexpression = (map);
            }
            return _xblockexpression;
          }
        };
      HashMap<String,String> _fold = IterableExtensions.<Map<String,Object>, HashMap<String,String>>fold(slugList, _hashMap, _function);
      final HashMap<String,String> slugMap = _fold;
      this.slugProvider.batchUpdate(slugMap);
      this.log.debug("Reindexing slugs");
  }

I do miss Scala's syntax though. Xtend is more "Java-compatible" and works as CDI beans.

Closure support and type inference are the two most useful features in languages like Xtend, Scala, and Groovy. :)

To learn Modeling with Eclipse Modeling Framework (EMF), I highly recommend the book EMF: Eclipse Modeling Framework.

No comments:

Post a Comment