What are the reasons for Java developers to consider giving Grails a try?

Java’s mature ecosystem has solidified its standing as a dependable platform. However, it falls short in terms of efficiency, especially for tasks like web application development. This often leads developers to gravitate towards languages and frameworks better suited for such purposes, like Ruby on Rails or Python’s Django. These alternatives offer a more streamlined approach to web application creation, unlike Java.

Why Should Java Developers Give Grails a Chance?
Java web developers: meet Grails and find out what you've been missing.

However, Java developers keen on building web applications have a superior option at their disposal: Grails. This article will explore how Grails, coupled with Groovy, presents a compelling alternative within the JVM landscape. We’ll delve into instances where Grails proves advantageous for Java developers and might entice others to give it a try.

The Story

This dilemma resonated with our experience at a startup I was part of. Our Spring application became increasingly cumbersome to manage, with refactoring and feature additions demanding an inordinate amount of time as it grew. Driven by this and other factors, we embarked on a rewrite of our core application, open to exploring new technologies. Grails emerged as a potential candidate due to its JVM compatibility and foundation upon familiar technologies. Utilizing Groovy while accommodating Java integration, we decided to take the leap.

Full Speed Ahead

Grails truly shines in simplifying project initiation. A single command sets up the project structure, complete with necessary folders for future classes. Adding models, controllers, services, and web pages is similarly effortless. The focus shifts solely to naming and organization, eliminating the boilerplate code often required in Java. This streamlined approach stems from its reliance on Spring and Hibernate, two of Grails’ cornerstones, along with its convention-over-configuration philosophy. Grails bundles Apache Tomcat as a development server, allowing for easy project execution and deployment within the IDE. Additionally, the Grails’ Object Relational Mapping (GORM) with Hibernate handles database creation, configurable via JDBC properties or defaulting to an in-memory instance. Once running, hot deployment keeps the debugging environment updated, except for entity classes.

While SQL scripts can populate the database, Grails offers a more efficient alternative. Every project includes a Bootstrap class, executed on application startup, which facilitates data storage, modification, and application state initialization. This proved invaluable for us in establishing immediate test cases during development.

In the Bootstrap class, we can also use “if” conditions to check the environment type (development, test, production, etc.) and modify the data accordingly.

Manipulating Data

Grails’ seamless data handling immediately grabbed our attention. Reading from databases, a recurring task often involving simple criteria-based entity retrieval and aggregation, becomes effortless with dynamic finders. These dynamically generated methods, adhering to a naming convention, simplify data querying.

1
def users = User.findAllByLastNameLikeOrAgeGreaterThan(‘Doe%’, 30)

This line fetches all User objects with last names starting with “Doe” or ages exceeding 30. While straightforward, it illustrates the concept.

Now, consider further filtering this list for users with “failedLogins” over 10, sorting them by creation date, concatenating their first names, or finding the maximum age.

1
2
3
4
users = users.findAll() { it.failedLogins > 10 }
users = users.sort { it.dateCreated }
def firstNamesString = users.firstName.join(‘, ‘)
def maximumAge = users.age.max()

These examples, while simple, demonstrate Grails’ prowess in querying, filtering, and manipulating data. While Java 8 offers similar capabilities in some cases, it still involves more verbose code compared to Grails.

Sometimes I Want to Create Differently

Dynamic or named argument constructors, a coveted feature by many Java developers, offer flexibility in object instantiation. Groovy addresses this by providing a special constructor for each entity, accepting a map-like input to elegantly set properties, as illustrated below:

1
def Person = new Person(name: 'Batman', age: 57)

This results in more expressive code and eliminates constructor boilerplate.

Groovy’s enhancements to maps further exemplify its elegance and conciseness:

1
2
3
4
def emptyMap = [:]
def map = [bread:3, milk:5, butter:2]
map[‘bread’] = 4
map.milk = 6

This showcases inline initialization and map value manipulation akin to object properties, obviating the need for traditional Java methods in many scenarios.

We Need More Power!

While no framework is all-encompassing, Grails leverages plugins to extend its functionality. Installing a plugin is as simple as adding a line to the BuildConfig class, a testament to its convention-driven approach.

1
compile ':spring-security-core:2.0-RC4'

This incorporates Spring Security Core into the application with minimal configuration.

It’s similar to using Maven dependencies (which you can also reference in the same config class), but the plugins are usually larger blocks that contain the whole functionality.

To illustrate, we needed to implement a search across multiple data entities. Grails’ Elasticsearch plugin proved invaluable. Referencing it in the configuration file was sufficient. Adding a static “searchable” property to an entity class enabled searching within that class, with the option to limit searchable properties.

1
2
3
4
5
class User { 
    static searchable = { only = name } 
    String name 
    Double salary 
}

Despite the minimal code, Grails and the Elasticsearch plugin automate user indexing and search functionality. The search call itself is equally concise:

1
User.search("${params.query}")

The plugin even handles search result display and match highlighting, abstracting away the complexities of Lucene index management. This exemplifies how plugins enhance efficiency by providing ready-made solutions.

We Still Need More Power

Beyond plugins, Groovy’s metaprogramming capabilities allow extending existing classes with methods and properties, even at the instance level. For instance, a formatting method can be added to java.util.Date, promoting consistent date formatting without cluttering code with static utilities or filters.

1
Date.metaClass.formatDate = { delegate.format("dd.MM.yyyy") }

Similarly, instance-specific properties can be added for ad-hoc sorting or filtering, avoiding unnecessary method additions to the class itself.

1
user.metaClass.computedProp = 312 * 32 * 3

Groovy already enhances core Java classes, like simplifying collection manipulation:

1
assert [1, 2, 3, 4, 4, 5] - [2, 4] == [1, 3, 5]

Date manipulation also becomes more intuitive with added methods:

1
2
3
def yesterdayAllMyTroublesSeemedSoFarAway = new Date() - 1
def myAwesomeAnniversaryYear = myAwesomeDate[Calendar.YEAR] + 1
myAwesomeDate.set(year: myAwesomeAnniversaryYear, second: 0)

For complex scenarios, Groovy’s TimeCategory class provides further expressiveness:

1
2
3
4
5
6
use (TimeCategory) { 
println 1.minute.from.now 
	println 10.hours.ago 
	def someDate = new Date() 
	println someDate - 3.months 
}

A Hammer and a Nail

IDEs like GGTS (Eclipse-based) and IntelliJ IDEA are tailored for Grails development. They understand its project structure, offer navigation aids, provide shortcuts for common commands (adding controllers, pages, running projects, etc.), and facilitate command execution and configuration management. Code completion in web template pages streamlines development. Other compatible IDEs include Netbeans, TextMate, and Emacs.

What About the Dark Side?

Grails, like any technology, has its drawbacks. Its “magic,” while often beneficial, can lead to unexpected outcomes. The lack of mandatory typing in Groovy, while flexible, requires discipline to avoid errors. Concise, powerful code might sacrifice clarity for brevity. Therefore, Grails demands greater programming discipline compared to more traditional frameworks.

Time is Money

Efficient coding is crucial, especially in today’s fast-paced startup environment. Grails allows developers to focus on essential tasks and expedite time to market. While achievable with Java, Spring MVC, and Hibernate, Grails offers a faster path to the same results, a critical advantage in today’s competitive landscape.

Licensed under CC BY-NC-SA 4.0