Archive

Archive for the ‘basic’ Category

GContracts: Inheritance of Pre- and Postconditions

June 15, 2010 1 comment


Flattr this
GContracts 1.1.0 [0] introduced inheritance for pre- and postconditions and optimized class invariant inheritance. If you want to know more about GContracts take a look at the wiki [1] or at blog-posts tagged with “gcontracts”.

What about postcondition inheritance?

Postconditions are used to specify what work is guaranteed by the supplier to be done in a specific method, under the condition that the precondition is satisfied. When inheritance comes into play, postconditions of a parent class are inherited by overridden methods of a descendant class.

Imagine a class Stack which provides methods for modifying objects kept in LIFO order.

import org.gcontracts.annotations.*

@Invariant({ elements != null })
class Stack {
    
    private List elements
    
    @Ensures({ is_empty() })
    public Stack()  {
        elements = []
    }
    
    @Requires({ preElements?.size() > 0 })
    @Ensures({ !is_empty() })
    public Stack(List preElements)  {
        elements = preElements
    }
    
    def boolean is_empty()  {
        elements.isEmpty()
    }
    
    @Requires({ !is_empty() })
    def last_item()  {
        elements.last()
    }
    
    def count() {
        elements.size()
    }
    
    @Ensures({ result == true ? count() > 0 : count() >= 0  })
    def boolean has(def item)  {
        elements.contains(item)
    }
    
    @Ensures({ last_item() == item })
    def put(def item)  {
       elements.push(item)
    }
    
    @Requires({ !is_empty() })
    @Ensures({ last_item() == item })
    def replace(def item)  {
        remove()
        elements.push(item)
    }
    
    @Requires({ !is_empty() })
    @Ensures({ result != null })
    def remove()  {
        elements.pop()
    }
    
    def String toString() { elements.toString() }
}

As you can see in the code sample @Requires and @Ensures is used to specify pre- and postconditions in certain methods. Whenever an object of type Stack is used at runtime those assertions will be checked due to hidden code segments injected by GContracts at compile-time (under the assertion that Java’s assert mechanism is activated via the command line argument -ea).

Let’s assume we need an extended Stack that provides us with changed method behavior. For example, we want to add a put method that adds inlining support for lists:

def stack = new Stack()
stack.push(['value1', 'value2', 'value3'])

In order to implement this feature we need to override the put method found in the parent class.

class GroovyStack extends Stack  {

    @Override
    def put(def item)  {
        if (item instanceof List) item.each { super.put(it) }
        else super.put(item)   
    
        return item
    }
}

If we create an instance of GroovyStack and call put with a list as actual parameter, the following assertion violation appears:

[inherited postcondition] in method <put(item:java.lang.Object)> violated. Expression: (this.last_item() == item). Values: item = [1, 2, 3, 4]

A look at the original postcondition shows that this is in fact the case, since our new put method in the descendant flattens the given parameter and for each item in the given list executes the put method once.

Maybe a new postcondition in the descendant will solve this issue:

class GroovyStack extends Stack  {

    @Override
    @Ensures({ item instanceof List ? item.last() == last_item() : item == last_item() })
    def put(def item)  {
        if (item instanceof List) item.each { super.put(it) }
        else super.put(item)   
    
        return item
    }
}

Execution again shows the following assertion:

[inherited postcondition] in method <put(item:java.lang.Object)> violated. Expression: (this.last_item() == item). Values: item = [1, 2, 3, 4]

This leads us to the most important point with rewritten postconditions in descendant classes: you can’t override them.

A postcondition in a descendant class is always joined with the postcondition of the super class, the postcondition of the parent class is said to be strengthened. That means, an overridden method has to implement the postcondition of its parent classes AND its self-defined postcondition.

This might seem awkward at first, but consider the following code:

Stack stack = StackFactory.getInstance()

stack.put([1,2,3,4])

The thing is, if we override the put method in the GroovyStack class the semantic of the code above would change with the type of Stack used at runtime: a Stack instance would push the complete list on the stack, a GroovyStack instance would push the single list items.

Indeed, changing the behavior of an overridden method does not conform to the assertion that inheritance always resembles an is-a relationship. If a GroovyStack should be a Stack, than it has to implement all postconditions of its parent class in overridden methods to conform to the contracts that were specified in the parent and on which clients already might rely on.

Due to inheritance of the parent postcondition we stumbled upon this circumstance and it made us think about how the Stack data-structure could already be used by its clients.

What about precondition inheritance?

Preconditions are used to specify certain conditions which must be fulfilled by a client so that a method call on an object succeeds. So far, GContracts did not support inheritance of preconditions, meaning that whenever a parent class defined a precondition on a method which has been overridden in a descendant, the precondition in the descendant had to be newly defined.

In contrast with postconditions, preconditions weaken the parent’s preconditions. Whenever a parent class defines a precondition on a method, an overridden method might define additional preconditions which might be fulfilled by a client, but don’t have to be.

If we would like to rewrite the replace method in GroovyClass we could specify an additional precondition:

   @Requires({ item != null })
    @Ensures({ item() == item })
    def replace(def item)  {
        super.replace(item)
    }

But that additional precondition weakens the original one, meaning that a call like remove(null) on GroovyStack would still suffice the precondition. In contrast, a put method call on an empty stack would still raise an AssertionError.

Conclusion

Inheritance of pre- and postconditions complements object-oriented mechanisms like polymorphism, dynamic binding and overriding methods and channels those concepts to correct uses. GContracts for Groovy finally supports precondition and postcondition with 1.1.0. Therefore it supports the main principles found in Design by Contract(tm) and allows to apply the full power of contracts to domain models in Groovy/Grails projects.

[0] GContracts Project – http://github.com/andresteingress/gcontracts
[1] GContracts Wiki – http://wiki.github.com/andresteingress/gcontracts/

Categories: basic, gcontracts, Intro

Domain Patterns in Enterprise Projects


If I had to separate projects I’ve been in, i would difference between data manipulation and enterprise projects.

Data manipulation projects mainly consist of a set of forms needed to alter data which is stored in some persistent store (most of the time a relational database). In these projects, there is not much domain logic to be found. There might be some validation logic, some jobs running in the background, but that’s mainly it with domain logic.

Enterprise projects are all about domain logic and integration of external systems. Most of the time a project starts with implementing all the views and domain classes which are considered to be simple, that is, not much domain knowledge has to be available in order to implement those views. But as time goes by, domain logic creeps in and classes which seemed pretty small and granular for data manipulation style grow to be oversized monsters.

Web frameworks like Grails make it easy to implement data manipulation style applications: if project members have a clear picture how to model the domain classes, they write the domain classes and all the view and controller stuff comes automatically with it.

If your project is moving towards being an enterprise project, there are some patterns that helped in my projects to deal with additional domain logic and complexity i want to share with this article.

The Birth of Objects

The birth of an object is a special event: it is the time the object’s data starts to exist in memory. In order to create an object, one of the object’s constructors is used. A constructor is a special creation procedure which encapsulates object initialization and which ensures that at the end of the constructor call an object is in a state that satisfies the class invariant.

Okay, that is rather academic you might think, which is true for classes which resemble active records [0] – but not for real domain classes found in larger projects. If you are writing an enterprise project with Grails, you have to know that Grails per se is not ment to be used in projects like that, but rather in data manipulation projects.

Let’s assume one of our domain classes is a Customer domain class. If we create a Customer class with

grails create-domain org.ast.domain.entity.Customer

we’ll get a class that looks like

class Customer {
	
	

	static constraints = {
		
	}
}

At this point we could add all the properties that resemble a customer and we could think we’re done. But what would happen?

We would build nothing more than a class that resembles the active record pattern – at runtime instances of that class mainly are treated like database records and all the domain logic will be put in Grails service classes. But service classes are not ment to be the place are central business logic happens, because we would distribute business logic over multiple service classes, where as each service holds several procedures that modify our active records – such a design screams for better object-orientation design enforcing information hiding, inheritance, dynamic binding and polymorphism.

Let us come back to our Customer domain class and add some properties to it:

class Customer {
	
	String name
	Status status
	Account account

	static constraints = {
		name(blank: false)
		status(nullable: false)
		account(nullable: false)
	}
}

Clients of that class could now create customer objects in arbitrary ways:

def c = new Customer()
def c = new Customer(name: 'Max')
def c = new Customer(status: null)
def c = new Customer(status: Status.NEW, account: null)
// ...

If we are serious about object-orientation and the role of creation procedures, we should not support creating objects in ways that generate objects which are in an invalid state after object creation, e.g. creating a customer without a state. In order to support a more object-oriented design we could modify the Customer class like this:

@Invariant({ name?.size() > 0 && status && account })
class Customer {
	
	String name
	Status status
	Account account
	
	def Customer(String name, Account account)  {
		this.name = name
		this.status = Status.NEW
		this.account = account
	}

	void setName(final String other) { name = other }
	void setStatus(final Status other)  { status = other }
	void setAccount(final Account other) { account = other } 


	// Grails Specific 
	private def Customer() {}

	static constraints = {
		name(blank: false)
		status(nullable: false)
		account(nullable: false)
	}
}

First of all, we’ve redeclared setter methods to be only visible in package scope. This comes in handy if you modularize your domain logic in separate packages and want e.g. services to change the state of customer objects.

In addition, a custom constructor was added which is a way to create a Customer object being in a valid state after the constructor call. As it turns out, more complex classes would be candidates for factory methods [1]

@Invariant({ name?.size() &gt; 0 && status && account })
class Customer {
	
	// ...
	
	def static Customer create(final String name, final Account account)  {
		return new Customer(name, account)
	}

	// ...
}

or the Builder pattern [2].

Well-defined creation procedures/constructors/factory methods/etc. are great, because there is a predefined way on how to create a fully initialized, valid object. If we should write an integration test for the Customer class and wanted some customer test instances, we would need to know what it takes to create a “valid” customer object – it might be simple in this case, but with more complex classes programmers could simply give up to write test-cases based on the simple fact that it is not obvious to them who to create instances of some type.

Domain Logic comes in…

In the previous section, the Customer class has been modified to be created with a custom constructor. Let as assume that the following business requirement comes in:

After 30 days, if the customer is in state REGISTERED, the application needs to send an e-mail to the customer, telling that the test-period ends in 5 days.

Is is pretty obvious that we need to have a job that checks for customer accounts existing >= 30 days. In addition, the application needs to have a way to integrate with an external SMTP server, which is a rather technological issue we don’t care about now (although I did in the last blog post [3]). What’s interesting in this place is where to put the additional domain logic.

A first naive approach would be to create a service class CustomerService which implements the business requirement:

class CustomerService {	
	
	static transactional = true
	
	def void sentTestPeriodEndsMail(final Customer customer)  {
		
		if (customer.state != State.REGISTERED) return
		if (!(customer.created + 30 &gt;= new Date()))  return
		
		customer.state = State.REGISTERED_WARNED
		customer.save()
		
		sendMailMessage(customer)
	}
	
	// ...
}

The code above exactly implements the business requirement, which is a good thing. But what if more domain logic creeps in? Let’s say there is a more privileged type of users, FriendOfMineCustomer from which instances should never receive those mails. We would have to change our service class method to something like:

class CustomerService {	
	
	static transactional = true
	
	def void sentTestPeriodEndsMail(final Customer customer)  {
		
		if (customer instanceof FriendOfMineCustomer) return // <-- more domain logic comes in...
		if (customer.state != State.REGISTERED) return
		if (!(customer.created + 30 &gt;= new Date()))  return
		
		customer.state = State.REGISTERED_WARNED
		customer.save()
		
		sendMailMessage(customer)
	}
	
	// ...
}

Now we start to feel that this is obviously not a good design. Just assume we need to check if a customer object is a candidate for receiving reminder messages in another service – we would need to duplicate the code above and put in that place. What is the reason that we slipped into this design? The reason was that we treated customers as active records and created a service procedure that implemented the business requirement in first place with pure procedural design.

A better approach would be to put the additional domain logic in the Customer class itself:

@Invariant({ name?.size() &gt; 0 && status && account })
class Customer {
	
	def boolean isTestPeriodEmailCandidate()  {
		return state == State.REGISTERED && created + 30 &gt;= new Date()
	}

	// ...
}

than we could simply modify FriendOfMineCustomer to:

class FriendOfMinCustomer extends Customer {
	
	def boolean isTestPeriodEmailCandidate()  {
		return false
	}

	// ...
}

and the CustomerService class would simply be the integrational glue between the core domain class and the messaging component:

class CustomerService {	
	
	static transactional = true
	
	def void sentTestPeriodEndsMail(final Customer customer)  {
		
		if (!customer.isTestPeriodEmailCandidate()) return
		
		customer.state = State.REGISTERED_WARNED
		customer.save()
		
		sendMailMessage(customer)
	}
	
	// ...
}

As you can see, code for the service class does not feel that complicated anymore. Changing the customer’s state should be externalized to another domain class like CustomerWorkflow:

class CustomerWorkflow {	
	
	State state
	Customer customer
	
	// ...
}

This would simplify the service class’ method code to:

class CustomerService {	
	
	static transactional = true
	
	def void sentTestPeriodEndsMail(final Customer customer)  {
		
		if (!customer.isTestPeriodEmailCandidate()) return
		
		customer.workflow.mailMessageSent()
		
		sendMailMessage(customer)
	}
	
	// ...
}

Keep in mind that there is no single best way on how to treat domain logic in enterprise applications, but one should at least know some basic patterns found in [4] or [5].

Entities vs. Value Objects

Another thing which is important for larger Grails projects is to recognize the difference between entities and simple value objects.

In Grails, each generated domain class is an entity – it can be uniquely identified. On the other side, value objects do not have an identity, are immutable and interchangeable. Value object classes could be enumerations, but also separate GORM domain classes. GORM supports embedding domain classes within other domain classes. The decision whether a certain class is a value object class or entity class can change from domain to domain. It could be that an address is a value object, but put in another context an address is an entity.

Defining value objects with domain classes is usually done with the static embedded property:

class Customer {	
	
	// ...
	Address homeAddress
	
	static embedded = ['homeAddress']
}

class Address  {
	
	String street
	// ...
}

Embedding classes has the advantage that developers don’t have to care about cascading CRUD operations, since data is directly embedded in the parent table at the database level. Therefore, value object classes simplify domain class relationships.

The Role of Repositories

A repository is responsible for loading persistent objects from arbitrary data stores. In Grails, this functionality is mostly encapsulated with GORM generated methods, available as static methods in each domain class:

def customers = Customer.findAllByState(State.NEW, [max: 10])
// ...

To be honest, outsourcing data accessing logic in a separate repository class does not seem to be reasonable with GORM. At least one use case would justify separate repository classes: complex data graph deletion.

If the domain model has complex relationships the best strategy is to define Aggregate objects. An aggregate object is the root object of a graph of associated objects. Clients of that class access objects in the aggregates graph only through accessor methods in the aggregate object. It is not possible to modify objects in the data graph directly without using aggregate methods.

This pattern simplifies relationships within the domain model and therefore reduces complexity to handle the object graphs and relationships between them. Overall, modification/deletion operations are hidden and encapsulated by the root entity of the aggregate.

Conclusion

This article does not claim to offer a complete overview of best practices in Grails enterprise projects, but reflects best-practices that i have found useful in projects i participated in.

I would be happy to discuss other views or other patterns in the comments section of this article.

[0] Active Record Pattern – http://martinfowler.com/eaaCatalog/activeRecord.html
[1] Factory Method Pattern – http://en.wikipedia.org/wiki/Factory_method_pattern
[2] Builder Pattern – http://en.wikipedia.org/wiki/Builder_pattern
[3] Integration and Grails – https://andresteingress.wordpress.com/2010/05/11/integration-and-grails/
[4] Domain Driven Design – Eric Evans
[5] Patterns of Enterprise Application Architecture – Martin Fowler

Categories: basic, grails, patterns

Logging by Convention

April 29, 2010 4 comments

Each Grails application uses a custom Log4J DSL [0] to configure logging settings. In a blank Grails application the grails-app/conf directory contains the Config.groovy file, which declares the log4j variable:

log4j = {
    // Example of changing the log pattern for the default console
    // appender:
    //
    //appenders {
    //    console name:'stdout', layout:pattern(conversionPattern: '%c{2} %m%n')
    //}


    error  'org.codehaus.groovy.grails.web.servlet',  //  controllers
	       'org.codehaus.groovy.grails.web.pages', //  GSP
	       'org.codehaus.groovy.grails.web.sitemesh', //  layouts
	       'org.codehaus.groovy.grails.web.mapping.filter', // URL mapping
	       'org.codehaus.groovy.grails.web.mapping', // URL mapping
	       'org.codehaus.groovy.grails.commons', // core / classloading
	       'org.codehaus.groovy.grails.plugins', // plugins
	       'org.codehaus.groovy.grails.orm.hibernate', // hibernate integration
	       'org.springframework',
	       'org.hibernate',
           'net.sf.ehcache.hibernate'

    warn   'org.mortbay.log'
}

Let me start my explanation of logging by convention by creating a new service class

grails create-service com.ast.service.Some

Leading to the following generated Groovy code:

package com.ast.service

class SomeService {

    boolean transactional = true

    def serviceMethod() {

    }
}

By default, each Grails artefact (services, controllers, domain classes and tag library classes) gets a getLog method injected on application bootstrap. The magic happens in LoggingGrailsPlugin which is currently part of the grails-core module:

// ...

def addLogMethod(artefactClass, handler) {
    // Formulate a name of the form grails.<artefactType>.classname
    // Do it here so not calculated in every getLog call 🙂
    def type = GrailsNameUtils.getPropertyNameRepresentation(handler.type)
    def logName = "grails.app.${type}.${artefactClass.name}".toString()

    def log = LogFactory.getLog(logName)

    artefactClass.metaClass.getLog << {-> log}
}

// ...

As you can see, Grails uses meta-programming to add a getLog method returning a log object of type org.apache.commons.logging.Log. But take a look at the log name which is used to create the log object with Apache Commons Logging LogFactory:

def logName = "grails.app.${type}.${artefactClass.name}".toString()

Grails prefixes the artefact’s class name with grails.app and its type (service, controller, taglib, domain). In fact, this is a pretty cool feature, since all artefacts are bundled in a common logging namespace.

E.g. to enable INFO logging on all application artefacts, developers just have to add the following line in Config.groovy:

log4j = {
    // ...
    info   'grails.app'
    // ...
}

Although this is a pretty cool feature, it can lead to confusion, and one can find multiple questions concerning this issue on mailing-lists, user groups etc.

Let’s assume that our application basically should use ERROR level and more detailed levels only for separate packages. We would modify the Log4J configuration to look like:

log4j = {
    // ...
    // maby defining additional appenders here
    // ...
    root {
        error()
    }
    // ...

If you want to fetch INFO logging output of com.ast.service.SomeService the following configuration snippet would not work:

log4j = {
    // ...
    info 'com.ast.service.MyService'
    // ...
}

The reason is that LoggingGrailsPlugin prefixes the artefacts type and class name with grails.app. The actual log instance’s log name in MyService was therefore configured to

grails.app.service.MyService

As a consequence, to enable logging on INFO level we should better use

log4j = {
    // ...
    info 'grails.app.service.com.ast.service.MyService'
    // ...
}

This is supposed to be a convenience feature, but can steal quite some time if you overlooked that section in the configuration documentation [0].

[0] Logging Configuration


Categories: basic, grails

Getting the Persistence Context Picture (Part III)

April 20, 2010 1 comment


Flattr this
Part 3 of this series deals with more advanced topics, requiring knowledge about persistence patterns and Hibernate APIs.

  • [0] Getting the Persistence Context Picture (Part I)
  • [1] Getting the Persistence Context Picture (Part II)

Conversational State Management

One advanced use case when using persistence frameworks is realization of conversations.

A conversation spans multiple user interactions and, most of the time, realizes a well-defined process. Best way to think of a conversation is to think of some kind of wizard, e.g. a newsletter registration wizard.

A Newsletter Registration Conversation

A newsletter registration wizard typically spans multiple user interactions, whereas each interaction needs user input and further validation to move on:

  1. a user needs to provide basic data, e.g. firstname, lastname, birthdate, etc.
  2. a user needs to register for several newsletter categories
  3. a user gets a summary and needs to confirm that information

Each user interaction is part of the overall newsletter registration process. Technically speaking, whenever the user aborts the process at some time, or an unrecoverable error occurs, this must have no consequence on the underlying persistent data structures. E.g. if a user registered for a newsletter (step 2) and stops its newsletter registration per closing the browser window and HTTP session runs out of time, the registration and the newly created newsletter user needs to be rolled back.

A first naive approach to realize conversations is to use a single database transaction. Modern applications hardly use that approach because its error-prone and not justifiable in terms of performance considerations. In order to really get a grasp of the problems we would face, let us take a look at some basics on database transactions.

A Small Intro to Database Transactions

Whenever a database transaction gets started, all data modification is tracked by the database. For example, in case of MySQL (InnoDB) databases, pages (think of a special data structure) are modified in a buffer pool and modifications are tracked in a redo log which is hold in synchronization with the disk. Whenever a transaction is committed the dirty pages are flushed out to the filesystem, otherwise if the transaction is rolled back, the dirty pages are removed from the pool and the changes are redone.

It depends on the current transaction level if the current transaction has access to changes done by transactions executed in parallel (more details on MySQL transactions can be found at [2]). MySQL’s default transaction level is “repeatable read”: all reads within the same transaction return the same results – even if another transaction might have changed data in the meantime. InnoDB (a transactional MySQL database engine, integrated in MySQL server) achieves this behavior by creating snapshots when the first query is created.

Other isolation levels (confirming to SQL-92 standard) are: “read uncommitted” > “read committed” > “repeatable read” > “serializable”. The order represents the magnitude of locking which is necessary to realize the respective transaction level.

A Naive Approach

Single DB Transaction

Back to conversational state management: as mentioned above, a naive approach would be to use a single database transaction for a single conversation. This approach apparently has many problems:

  • if data is modified and DML statements generated, usually locks are created, avoiding other transactions to change it.
  • databases are designed to keep transactions as short as possible, a transaction is seen as atomic unit and not a long living session, long-running transactions are typically discarded by the database management system.
  • especially in web applications, it is hard for an application to determine conversation aborts – when the user closes its browser window in the middle of a transaction, or kills the browser process, there is hardly a change for the application to detect that circumstance.
  • a transaction is typically linked to a database connection. the number of database transactions is typically limited to the application.

As you can see, spanning a conversation with a database transaction is not an option. But a pattern already known from the previous articles comes to rescue: the persistence context.

Extended Persistence Context Pattern

As we’ve already seen in the second part of this series [1] Grails uses a so-called Session-per-Request pattern.

Session per Request Pattern

Whenever a controller’s method is called, a new Hibernate session spans the method call and, with flush mode turned to manual, the view rendering. When the view rendering is done, the session is closed. Of course, this pattern is not an option when implementing conversations, since changes in a controller’s method call are committed on the method’s return. One could pass Grails standard behavior using detached objects, but let me tell you: life gets only more complicated when detaching modified objects – especially in advanced domain models.

What we will need to implement a conversation is a mechanism that spans the persistence context over several user requests, that pattern is called: the extended persistence context pattern.

Extended Persistence Context

An extended persistence context reuses the persistence context for all interactions within the same conversation. In Hibernate speak: we need to find a way to (re)use a single org.hibernate.Session instance for conversation lifetime.

Fortunately, there is a Grails plugin which serves that purpose perfectly: the web flow plugin.

Conversational Management with Web Flows

The Grails web flow plugin is based on Spring Web Flow [3]. Spring Web Flow uses XML configuration data to specify web flows:

<flow xmlns="http://www.springframework.org/schema/webflow"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://www.springframework.org/schema/webflow
  http://www.springframework.org/schema/webflow/spring-webflow-2.0.xsd">

  <view-state id="enterBasicUserData">
    <transition on="submit" to="registerForNewsletters" />
  </view-state>
	
  <view-state id="registerForNewsletters">
    <transition on="submit" to="showSummary" />
    <!-- ... -->
  </view-state>

  <view-state id="showSummary">
    <transition on="save" to="newsletterConfirmed" />
    <transition on="cancel" to="newsletterCanceled" />
  </view-state>  
	
  <end-state id="newsletterConfirmed" >
    <output name="newsletterId" value="newsletter.id"/>
  </end-state>

  <end-state id="newsletterCanceled" />		
</flow>	

Groovy uses its own DSL implemented in org.codehaus.groovy.grails.webflow.engine.builder.FlowBuilder. This approach has the advantage of being tightly integrated into the Grails controller concept:

// ...
def newsletterRegistrationFlow = {
  step1 {
    on("save")   {
      def User userInstance = new User(params)
      flow.userInstance = userInstance

      if (!userInstance.validate()) {
        log.error "User could not be saved: ${userInstance.errors}"
            
        return error()
      }
    }.to "step2"
  }

  step2 {
    on("save")  {
      def categoryIds = params.list('newsletter.id')*.toLong()
      // ...
      def User userInstance = flow.userInstance
      newsletterService.registerUserForNewsletterCategories(userInstance, categoryIds)
      // ...
   }.to "step3"
  }

  step3()  {
     on("save")  {
        def userInstance = flow.userInstance
        // ...
        userInstance.save()
     }
  }
}

In this case, the closure property newsletterRegistrationFlow is placed in a dedicated controller class and is automatically recognized by the web flow plugin. The plugin is responsible for instantiating a Grails web flow builder object which needs a closure as one of its input parameters.

Leaving the DSL aside, best thing about web flows is that it realizes the extended persistence context aka flow managed persistence context (FMPC). The HibernateFlowExecutionListener is the place where the Hibernate session is created and than reused over multiple user interactions. It implements the FlowExecutionListener interface.

The flow execution listener provides callbacks for various states in the lifecycle of a conversation. Grails HibernateFlowExecutionListener uses these callbacks to implement the extended persistence context pattern. On conversation start, it creates a new Hibernate session:

public void sessionStarting(RequestContext context, FlowSession session, MutableAttributeMap input) {
	// ...
	Session hibernateSession = createSession(context);
	session.getScope().put(PERSISTENCE_CONTEXT_ATTRIBUTE, hibernateSession);
	bind(hibernateSession);
	// ...
}

Whenever the session is paused, in between separate user requests, it is disconnected from the current database connection:

public void paused(RequestContext context) {
	if (isPersistenceContext(context.getActiveFlow())) {
		Session session = getHibernateSession(context.getFlowExecutionContext().getActiveSession());
		unbind(session);
		session.disconnect();
	}
}

Whenever resuming the current web flow, the session is connected with the database connection again. Whenever a web flow has completed its last step, the session is resumed and all changes are flushed in a single transaction:

public void sessionEnding(RequestContext context, FlowSession session, String outcome, MutableAttributeMap output) {
  // ...
  final Session hibernateSession = getHibernateSession(session);
  // ...
  transactionTemplate.execute(new TransactionCallbackWithoutResult() {
	  protected void doInTransactionWithoutResult(TransactionStatus status) {
	    sessionFactory.getCurrentSession();
	    }
	  });
  }
    
  unbind(hibernateSession);
  hibernateSession.close();
  // ...
}

A call to sessionFactory.getCurrentSession() causes the current session to be connected with the transaction and, at the end of the transaction template, committing all changes within that transaction. All changes which have been tracked in-memory so far, are by then synchronized with the database state.

The price to be paid for conversations is higher memory consumption. In order to estimate the included effort, we need to take a closer look at how Hibernate realizes loading and caching of entities. In addition to implementing conversations, memory consumption is especially important in Hibernate based batch jobs.

Using Hibernate in Batch Jobs

The most important thing when working with Hibernate is to remember: the persistence context references all persistent entities loaded, but entities don’t know anything about it. As long as the persistence context is alive it does not discard references automatically.

This is particularly important in batch jobs. When executing queries with large result sets you have to manually discard the Hibernate session otherwise the program is definitely running out of memory:

for (def item : newsletters)  {
  // process item...
  if (++counter % 50 == 0)  {
    session.flush()
    session.clear()
  }
  // ...
}

Session provides a clear method that detaches all persistent objects being tracked by this session instance. Invoked on specific object instances, evict always to remove selected persistent objects from a particular session.

In this context, it might be worth to take a look at Hibernate’s StatefulPersistenceContext class. This is the piece of code that actually implements the persistence context pattern. As you can see in the following code snippet, invoking clear removes all references to all tracked objects:

public void clear() {
	// ...
	entitiesByKey.clear();
	entitiesByUniqueKey.clear();
	entityEntries.clear();
	entitySnapshotsByKey.clear();
	collectionsByKey.clear();
	collectionEntries.clear();
	// ...
}

Another thing to notice when executing large result sets and keeping persistence contexts in memory is that Hibernate uses state snapshots to recognize modifications on persistent objects (remember how InnoDB realizes repeatable-read transaction isolation;-)).

Whenever a persistent object is loaded, Hibernate creates a snapshot of the current state and keeps that snapshot in internal data-structures:

// ..
EntityEntry entry = getSession().getPersistenceContext().getEntry( instance );
if ( entry == null ) {
	throw new AssertionFailure( "possible nonthreadsafe access to session" );
}
		
if ( entry.getStatus()==Status.MANAGED || persister.isVersionPropertyGenerated() ) {

TypeFactory.deepCopy(
		state,
		persister.getPropertyTypes(),
		persister.getPropertyCheckability(),
	        state,
		session
);
// ...

Whenever you don’t want Hibernate to create snapshot objects, you have to use readonly queries or objects. Marking a query as “readonly” is as easy as setting its setReadOnly(true) property. In read-only mode, no snapshots are created and modified persistent objects are not marked as dirty.

Newsletter.withSession {
        org.hibernate.classic.Session session ->

              def query = session.createQuery("from Newsletter").setReadOnly(true)
              def newsletters = query.list()

              for (def item : newsletters)  {
                // ...
              }
      }

If your batch accesses the persistence context with read-access only, there is another way to optimize DB access: using a stateless session. SessionFactory has an openStatelessSession method that creates a fully statless session, without caching, modification tracking etc. In Grails, obtaining a stateless session is nothing more than injecting the current sessionFactory bean and calling openStatelessSession on it:

def Session statelessSession = sessionFactory.openStatelessSession()
statelessSession.beginTransaction()

// ...

statelessSession.getTransaction().commit()
statelessSession.close()

In combination with stateless session objects, it is worth mentioning that if you want to modify data there is an interface to do that even when working with stateless sessions:

public void doWork(Work work) throws HibernateException;

Where interface Work has a single method declaration:

public interface Work {
	/**
	 * Execute the discrete work encapsulated by this work instance using the supplied connection.
	 *
	 * @param connection The connection on which to perform the work.
	 * @throws SQLException Thrown during execution of the underlying JDBC interaction.
	 * @throws HibernateException Generally indicates a wrapped SQLException.
	 */
	public void execute(Connection connection) throws SQLException;
}

As you can see execute gets a reference on the current Connection which, in the case of JDBC connections, can be used to formulate raw SQL queries.

If your batch is processing large chunks of data, paging might be interesting too. Again, this can be done by setting the appropriate properties of Hibernate’s Query class.

// ...
def Query query = session.createQuery("from Newsletter")
query.setFirstResult(0)
query.setMaxResults(50)
query.setReadOnly(true)
query.setFlushMode(FlushMode.MANUAL)
// ...

The code snippet above explicitly sets the flush mode to “manual”, since flushing does not make sense in this context (all retrieved objects are readonly).

A similiar API can be found in the Criteria class, being supported by Grails by its own Criteria Builder DSL [6].

Conclusion

As you can see, there are various options to use Hibernate even for batch processing of large data sets. Programmers are not restricted on using predefined methodologies, although understanding the fundamental patterns is a crucial point. Adjusting Hibernate’s behavior and generated SQL is a matter of knowing the right extension points.

I hope you had a good time reading that article series. I know, a lot of things have been unsaid but if you are missing something really much or want to gain more insights in a particular topic related to Hibernate, GORM, Grails etc. just drop a comment, i’ll try to take notice of it in one of the following blog posts.

[0] Getting the Persistence Context Picture (Part I)
[1] Getting the Persistence Context Picture (Part II)
[2] MySQL InnoDB Transactions
[3] Spring Web Flow Project
[4] Hibernate – Project Home Page
[5] Hibernate Documentation – Chapter: Improving Performance
[6] Criteria Builder DSL

Categories: basic, grails, hibernate, patterns

Getting the Persistence Context Picture (Part II)

April 8, 2010 2 comments


Flattr this
The first article of this series [0] took a look at the basic patterns found in todays persistence frameworks. In this article we will have a look at how Hibernate APIs relate to those patterns and how Hibernate is utilized in Grails.

A Closer Look at Hibernate’s Persistence Context APIs

All data creation, modification and altering has to be done in a persistence context. A persistence context is a concrete software element that maintains a list of all object modifications and, in a nutshell, at the end of the persistence context life-time or business transaction synchronizes them with the current database state.

When developing with a modern web framework – as Grails is – it is most likely you don’t even have to care about opening a persistence context or closing it, or even know about how this could be done.

But as application complexity raises, you have to know Hibernate’s persistence context APIs and understand how they are integrated within the web application framework of your choice. Let us take a look at the most import APIs and how they correspond to persistence patterns.

The Registry Pattern or org.hibernate.SessionFactory

The SessionFactory class implements the registry pattern. A registry is used by the infrastructure-layer to obtain a reference to the current persistence context, or to create a new one if not found in the current context.

Usually, as noted in SessionFactory’s Java documentation, a session-factory refers to a single persistence provider. Most of the time, application need just a single session-factory. Indeed, if an application wanted to work across multiple databases, it would have to maintain multiple SessionFactory instances, one for each database.

Imagine a session-factory to be a configuration hub – it is the place where all configuration settings are read and used for constructing persistence contexts.

In a Grails application, the application’s session-factory can be easily obtained by declaring a property of type org.hibernate.SessionFactory:


class SomeService {

    SessionFactory sessionFactory

    void myServiceMethod()  {
        def session = sessionFactory.getCurrentSession()
        // ...
    }
}

The Grails application’s session-factoy is than injected by dependency injection since every Grails service class is a Spring-managed component. Other components include controllers, domain-classes and custom beans (either in beans.groovy, beans.xml, other bean definition XMLs or annotated Groovy/Java classes).

A Grails application’s session-factory is set-up by the HibernatePluginSupport class, which is a utility class used by Grails hibernate plugin. When taking a look at the source code you’ll find out that the code uses Grails Spring builder DSL to declare a ConfigurableLocalSessionFactoryBean. This type of bean is usually used in Spring applications to create a Hibernate session-factory instance during application bootstrap and to keep track of it during the entire life-time of the application-context.

//...
sessionFactory(ConfigurableLocalSessionFactoryBean) {
    dataSource = dataSource
    // ...
    hibernateProperties = hibernateProperties
    lobHandler = lobHandlerDetector
}
//...

Btw, if we would have to create a session-factory within a plain Groovy application, it wouldn’t get much harder:


def configuration = new Configuration()
    .setProperty("hibernate.dialect", "org.hibernate.dialect.MySQLInnoDBDialect")
    .setProperty("hibernate.connection.datasource", "java:comp/env/jdbc/test")
    .setProperty("hibernate.order_updates", "true")
    // ...

def sessionFactory = configuration.buildSessionFactory()

The Configuration class can be used to configure a session-factory programatically, other options would be to use a properties-file or an XML file (named hibernate.properties or hibernate.cfg.xml). If using any of the file-based configurations, take care your configuration file can be loaded by the current class-loader, therefore put it in the class-path’s root directory.

Grails configuration of Hibernate’s session-factory is pretty much hided from application developers. In order to provide a custom hibernate.cfg.xml, just put it in the grails-app/conf/hibernate folder.

The Persistence-Context Pattern or org.hibernate.Session

The Session builds the heart of Hibernate: it resembles a persistence context. Thus, whenever the application needs to access object-mapping functionality in either form, it needs to work with an instance of type Session.

The Session interface provides a bunch of methods letting the application infrastructure interact with the persistence context:

        // ...
	public Query createQuery(String queryString) throws HibernateException;

	public SQLQuery createSQLQuery(String queryString) throws HibernateException;

	public Query createFilter(Object collection, String queryString) throws HibernateException;

	public Query getNamedQuery(String queryName) throws HibernateException;

	public void clear();

	public Object get(Class clazz, Serializable id) throws HibernateException;

	public void setReadOnly(Object entity, boolean readOnly);

	public void doWork(Work work) throws HibernateException;

	Connection disconnect() throws HibernateException;

	void reconnect() throws HibernateException;

	void reconnect(Connection connection) throws HibernateException;
        // ...

Whenever e.g. a query is created by one of the querying methods, all objects which are retrieved are automatically linked to the session. For each attached (Hibernate term for “linked”) object, the session holds a reference and meta-data about it. Whenever a transient Groovy object is saved, it gets automatically attached to the current session. Notice that this is a unidirectional relationship: the session knows everything whereas the attached object instances don’t know anything about being linked to a session.

Lazy and Eager Loading

In regard to attaching objects to the current session, you need to know the concepts of lazy and eager loading of object relationships.

Whenever a persistent class A references another persistent class B, A is said to have a relationship with B. Object relationships are mapped either with foreign keys or relationship tables in the underlying database schema. As default, Hibernate uses a lazy loading approach: whenever a root object with relations to other objects is loaded, the related objects are not loaded. The other approach would be eager loading, where the object relationship is loaded with the root object.

Lazy vs. Eager Loading

Lazy loading does not hurt as long as objects are attached to a persistence context. Although, if the persistence context is closed, there is no way to navigate over a lazy loaded relationship. Whenever application code needs to access lazy relationships this leads to a lazy loading exceptions.

Obtaining a Session

Per default, a session instance can be obtained using a session-factory instance:


def session = sessionFactory.openSession()
def tx = session.beginTransaction()

// ... work with the session

tx.commit()
session.close()

As it is the case with the code sample above, most of the time application code is working in a transactional context, that is, the current method is executed within a single transaction. Therefore, it is a common idiom to open a transaction with the beginning of a session, although this is not enforced by Hibernate’s API. If we would not use transaction boundaries, we could just omit the method call to beginTransaction:


def session = sessionFactory.openSession()

// ... work with the session

session.close()

You need to be careful in this scenario. If Hibernate obtains a JDBC connection, it automatically turns autocommit mode off by setting jdbcConnection.setAutoCommit(false). Indeed, this is the JDBC way to tell the database to start a new transaction. However, how the database driver reacts on pending transactions is not specified, an application runs into undefined behavior.

General Session-Handling in Grails

As manual session handling can get tricky, web frameworks like Grails hide most of these problems. The Grails’ Object Relational Mapping (GORM) layer is a thin layer above Hibernate 3. Grails uses this layer to enrich domain classes with a lot of DAO like functionality. E.g. to each domain class so-called dynamic finders are added, which most of the time completely replace the need for data access objects (DAOs). Handling of Hibernate sessions is mainly hidden by GORM which internally uses Spring’s Hibernate integration and Hibernate.

Whenever executing a GORM query Grails internally creates a HibernateTemplate. A HibernateTemplate is a neat way to get defined access to a Hibernate session. It completely hides getting the session-factory and retrieving a session. Clients only need to implement callback methods, which are than called on execution of that template. Let’s take a look how such templates are used when executing e.g. a dynamic finder method like findBy.


class SomeController {
  def myAction()  {
    def User user = User.findByLogin(params.id)
    // ...
  }
}

When invoking the static findBy dynamic finder method, the following code is executed:


// ...
return super.getHibernateTemplate().execute( new HibernateCallback() {
    public Object doInHibernate(Session session) throws HibernateException, SQLException {
        Criteria crit = getCriteria(session, additionalCriteria, clazz);
	// ... do some criteria building

        final List list = crit.list();
        if(!list.isEmpty()) {
            return GrailsHibernateUtil.unwrapIfProxy(list.get(0));
        }
        return null;
     }
});

As can be seen, Grails internally does nothing more than creating a Spring HibernateTemplate and in its doInHibernate callback, creates a plain Hibernate Criteria object which is used to specify object queries. Spring hides the code of finding the current session and setting properties according to the current program context, GORM adds this functionality and does all Groovy meta-programming stuff (adding static methods etc. to the domain’s meta class).

The same is true for saving domain objects using GORM’s save method:

protected Object performSave(final Object target, final boolean flush) {
        HibernateTemplate ht = getHibernateTemplate();
        return ht.execute(new HibernateCallback() {
            public Object doInHibernate(Session session) throws HibernateException, SQLException {
                session.saveOrUpdate(target);
                if(flush) {
                    // ...
                    getHibernateTemplate().flush();
                    // ...
                }
                return target;
            }
        });
}

Session Flushing

Since a session spans a business transaction (remember, not the same as a technical transaction) it might be left open by the infrastructure-layer over several user interaction requests. The application needs to ensure that a session is closed and its state synchronized with the database at some time, which is called flushing a session.

As we have already seen in the Grails source code above, flushing is mainly handled by the web framework, but programmers should know the point-cuts where it actually happens:

  • whenever a Transaction gets committed
  • before a query is executed
  • if session.flush() is called explicitly

Be aware that flushing is a costly operation in a persistence context, as Hibernate needs to synchronize the current object model in memory with the database. Programmers could change the default behavior described above by setting an alternate flush mode on the current session:

def session = sessionFactory.openSession()
session.setFlushMode(FlushMode.NEVER)

FlushMode.NEVER in this case means that session flushing is deactivated, only explicit calls to session.flush() triggers it.

In Grails, session flushing is done after each controller call, due to Spring’s OpenSessionInView interception mechanism. In order to access lazy-loaded properties in GSP pages, the session is not closed completely after a controller’s method call but after response rendering is done. Therefore, it sets session flushing mode to FlushMode.NEVER after a controller method call to avoid DB modifications caused by GSP page code.

Another place where sessions get flushed, is at the end of each service method call (as long as the service is marked as being transactional or is annotated with @Transactional):

class SomeService {
    static transactional = true

    def someMethod()  {
       // ... transactional code
    }
}
class SomeService {

    @Transactional
    def someMethod()  {
       // ... transactional code
    }
}

When doing integration tests on Grails classes, you need to remind these point-cuts where sessions get flushed. To make things even more complicated, there is one additional thing that is different in integration tests: each integration test method runs in its own transaction, which at the end is rollbacked by Grails testing classes. E.g. if testing a controller’s save method, chances are you can’t find an SQL INSERT or UPDATE statement in database logs. This is the intended behavior, but it causes confusion if bugs dealing with persistence issues need to be reproduced by test-cases.

If it is about transactions in integration tests, there is a way to deactivate transaction boundaries there:

class SomeTest extends GrailsTestCase {
    static transactional = false

    @Test
    def testWithoutTransactionBoundary()  {
       // ... transactional code
    }
}

Summary

In this article we took a look at how Grails and GORM handles Hibernate’s basic APIs: the SessionFactory and the Session. The next article in this series will deal with more advanced features: GORM in batch-jobs and conversational state management.

[0] Getting the Persistence Context Picture (Part I)
[1] Hibernate Project
[2] Spring Hibernate Integration
[3] Grails GORM Documentation

Categories: basic, grails, hibernate, patterns

Contracts in the Domain Model

This blog-post gives a brief introduction to contract-oriented programming aka design by contract in general and in relation to Groovy with gcontracts assertions.

The Problem

With each Grails application generation of test-cases is simply part of the game. Whenever you create a domain-class the corresponding unit-test is generated directly. With the test-first approach of Test-Driven Development (TDD) each iteration in the development process starts with the task of writing tests specifying the intended behavior of the targeted components.

E.g. use-case: a customer in the coffee-house might order several cups of coffee

class Customer {
    def Order createOrder() { ... }
}
class Order {
    def void addItem(Item someItem)  { ... }
}

When executing the test-first approach we would start with writing a unit-test for class Item, going on to class Order and finally writing one for class Customer.

e.g. ItemTests

class ItemTests  {
    @Test
    def void testCreateItem()  {
        def item = new Item(COFFEE_TYPE.Cappuccino, 1) // (type, amount)
        assertEquals COFFEE_TYPE.Cappuccino, item.coffee_type()
        assertEquals 1, item.amount()
    }
}

As you might have already noticed it is pretty hard to find tests that maximize the covering of business requirements. Most of the time, unit-tests are written in the first iteration, in subsequent iterations that tests are simply rewritten to “get green”. Your mileage may vary, but the main problem with test-cases are that each single test-case only tests a small fraction of the input domain, that is, the cartesian product of the current function:

e.g. the constructor call to new Item(COFFEE_TYPE.Cappuccino, 1) is nothing more than a function call that generates a new item object, with (COFFEE_TYPE, NUMBER) as parameters. Set theory would map that function to the following expression:

Mapping a Constructor Function Meaning that the overall set of parameter tuples is mapped by the cartesian product between all COFFEE_TYPE and all INTEGER values, the result is a single tuple out of all cartesian product tuples. Just imagine the cartesian product as a set that contains all possible combinations of this function’s parameter values. The unit-test tests exactly one single pair out of the cartesian product:

several pairs in the cartesian productIn this simple example it gets pretty obvious that even if tests have a high code coverage, they hardly never can satisfy testing a large portion of the problem domain.

That is where contracts come into play.

An Introduction to Contract-Oriented Programming

Contracts are the clue between the specification and the implementation of a certain software artifact, in object-oriented speak: classes. Formally, contracts are based on so-called Hoare rules which provide a formal system towards logical rules of reasoning on the correctness of computer programs [0]. The main feature of this formal system is the so-called Hoare triple:

Hoare Triplewhere P and Q are assertions and C represents a set of commands. A concrete Hoare triple states that before execution of C, the precondition P must be true, after the execution the postcondition Q must hold. Pre- and postconditions represent so-called assertion types.

In a gcontracts enabled Groovy program you might use pre- and postconditions by using either @Requires or @Ensures:

class Item {
    private CoffeeType coffee_type
    ...

    @Requires({ type != null && amount > 0 })
    def Item(final CoffeeType type, final Integer amount)  { ... }

    @Ensures({ old -> old.coffee_type != coffee_type })
    def void change_coffee_type_to(final CoffeeType type)  { ... }
}

As you can see pre- and postconditions are applied on constructors or methods only. In addition, there is the need to express assertions which must be preserved by all methods and every instance of that class; these assertion types are called class-invariants:

@Invariant({ coffee_type != null && amount > 0 })
class Item { ... }

A class-invariant must be preserved after every constructor call and before/after each method call. When executing a method with a precondition P, a postcondition Q and a class-invariant C, before a method call the assertion expression P AND C and after a method call expression Q AND C must be true.

When inheritance comes into play we’ll have to have a separate look at all assertion types:

  • Class-InvariantsWhenever a class B with an invariant B(iv) extends a class A with an invariant A(iv), B(iv) indeed is logically combined with A(iv), meaning that every class-invariant check in B is actually represented by the boolean expression B(iv) AND A(iv).
    class-invariant inheritance illustration
  • PreconditionsWhenever a method B with a precondition B(pre) overrides a method A with a precondition A(pre), B(pre) is logically combined with a boolean OR, resulting in B(pre) OR A(pre) assertions for all method calls of B. The precondition is said to be weakened for redeclared methods.
  • Postconditions Whenever a method B with a postcondition B(post) overrides a method A with a postcondition A(post), B(post) is logically combined with a boolean AND, resulting in B(post) AND A(post) for all method calls of B. The postcondition is said to be strengthened for redeclared methods.

Conclusion

Pre-, postconditions and class-invariants provide a great way of minimizing the parameter domain and ease testing of your domain model. Having instrumented your code with these assertions, you can concentrate on e.g. extreme boundaries of parameter values or obscure business cases when writing your tests. Indeed, a carefully instrumented domain-model has further advantages:

  • Tests are built-in – especially in complex object-oriented domain models, it is getting hard to (mentally) debug code and getting an impression of dependencies between components and side-effects between them. Contracts help to ensure that at least objects stay in a defined state that satisfies the intention of its supplier.
  • Implicit programmer assumptions are made explicit in the class’s or method’s contract – that’s just one step closer to get the domain documented in the source code.
  • Contracts enforce correctness – identifying contracts in the domain model is not an easy task and it is surely not done in a single iteration (of course), but once programmers get on it they really have to think about the specification and its mapping in the domain model and its contracts, thus enforcing correctness of understanding how business requirements shall be implemented.
  • Contracts allow for rapid changing of business requirements – rapid changing of business requirements is one of the most annoying facts for programmers. Given a set of components and related unit tests, a single business requirement might cause rewriting of all components and their corresponding unit-tests. Especially rewriting the unit-tests might introduce or slip through other bugs since, as we’ve seen, unit-tests usually cover only a small portion of the problem domain. When applying contract-oriented programming, you might change class-invariants etc. but at least those assertions already cover a large portion of the problem domain.
  • Contracts enforce readability – when writing code, a programmer always has a mind-map of all objects and assumptions on objects and their particular state in mind. Those assumptions are said to be implicit, since they are not explicitly stated in source-code. From my experience, when having to switch between multiple projects it gets even worse and the source-code owner itself forgets about its implicit assumptions – which is the best starting point of introducing new bugs.
  • Contracts enforce stability – dynamic languages are great for rapid application development, but when it comes to maintainability dynamic code can be hard to read and – due to its dynamic nature and other properties – pretty fragile. Changes in components lead to potential side-effects which might not be spotted by test-suites. Assertions provide a way to determine programming bugs at run-time (mostly in test and not in production-environments).

To be clear: if your task is to write e.g. a simple CRUD Grails application, you wont be dealing with this stuff. But, if you are dealing with complex domain models and throw moving business requirements in (what project lives without them?), you might give contract-oriented programming a try.

[0] An axiomatic basis for computer programming, C. A. R. Hoare
[1] GContracts – Contract-Oriented Programming with Groovy, Github

Categories: basic, gcontracts, grails, groovy