<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	xmlns:georss="http://www.georss.org/georss" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#" xmlns:media="http://search.yahoo.com/mrss/"
	>

<channel>
	<title>Connecting to the World</title>
	<atom:link href="http://guptavikas.wordpress.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://guptavikas.wordpress.com</link>
	<description>My Impressions on technology and business</description>
	<lastBuildDate>Thu, 13 Oct 2011 15:22:48 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.com/</generator>
<cloud domain='guptavikas.wordpress.com' port='80' path='/?rsscloud=notify' registerProcedure='' protocol='http-post' />
<image>
		<url>http://s2.wp.com/i/buttonw-com.png</url>
		<title>Connecting to the World</title>
		<link>http://guptavikas.wordpress.com</link>
	</image>
	<atom:link rel="search" type="application/opensearchdescription+xml" href="http://guptavikas.wordpress.com/osd.xml" title="Connecting to the World" />
	<atom:link rel='hub' href='http://guptavikas.wordpress.com/?pushpress=hub'/>
		<item>
		<title>AspectJ PointCut Expressions</title>
		<link>http://guptavikas.wordpress.com/2010/04/15/aspectj-pointcut-expressions/</link>
		<comments>http://guptavikas.wordpress.com/2010/04/15/aspectj-pointcut-expressions/#comments</comments>
		<pubDate>Thu, 15 Apr 2010 09:25:39 +0000</pubDate>
		<dc:creator>Vikas Gupta</dc:creator>
				<category><![CDATA[AspectJ]]></category>
		<category><![CDATA[Spring]]></category>
		<category><![CDATA[apsectj]]></category>
		<category><![CDATA[spring framework]]></category>

		<guid isPermaLink="false">http://guptavikas.wordpress.com/?p=279</guid>
		<description><![CDATA[The intention of this blog is to explain AspectJ Pointcut Expressions in Spring Applications. In Aspect Oriented Programming, a pointcut is a set of joinpoints. A joinpoint is a point in program execution where you can add additional behavior. Spring applications only support method based joinpoints. So, you can use AspectJ pointcut expressions to define [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=guptavikas.wordpress.com&amp;blog=7715205&amp;post=279&amp;subd=guptavikas&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>The intention of this blog is to explain <a href="http://en.wikipedia.org/wiki/AspectJ">AspectJ</a> Pointcut Expressions in <a href="http://www.springsource.org/">Spring</a> Applications. In <a href="http://en.wikipedia.org/wiki/Aspect-oriented_programming">Aspect Oriented Programming</a>, a pointcut is a set of joinpoints. A joinpoint is a point in program execution where you can add additional behavior. Spring applications only support method based joinpoints. So, you can use AspectJ pointcut expressions to define method pointcuts in Spring 2.x applications. Lets discuss some AspectJ pointcut expressions patterns.</p>
<h3><strong>Method Signature Patterns</strong></h3>
<p>The most typical pointcut expressions are used to match a number of methods by their signatures. A common method based pointcut expression is something like</p>
<pre><strong>expression(&lt;method scope&gt; &lt;return type&gt; &lt;fully qualified class name&gt;.*(parametes))</strong></pre>
<ol>
<li>method scope: Advice will be applied to all the methods having this scope. For e.g., public, private, etc. Please note that Spring AOP only supports advising public methods.</li>
<li>return type: Advice will be applied to all the methods having this return type.</li>
<li>fully qualified class name: Advice will be applied to all the methods of this type. If the class and advice are in the same package then package name is not required</li>
<li>parameters: You can also filter the method names based on the types. Two dots(..) means any number and type of parameters.</li>
</ol>
<p><span id="more-279"></span><strong>Examples</strong></p>
<ul>
<li>execution(* com.aspects.pointcut.DemoClass.*(..)) : This advice will be applied to all the methods of DemoClass.</li>
<li>execution(* DemoClass.*(..)): You can omit the package if the DemoClass and the advice is in the same package.</li>
<li>execution(public * DemoClass.*(..)): This advice will be applied to the public methods of DemoClass.</li>
<li>execution(public int DemoClass.*(..)): This advice will be applied to the public methods of DemoClass and returning an int.</li>
<li>execution(public int DemoClass.*(int, ..)): This advice will be applied to the public methods of DemoClass and returning an int and having first parameter as int.</li>
<li>execution(public int DemoClass.*(int, int)): This advice will be applied to the public methods of DemoClass and returning an int and having both parameters as int.</li>
</ul>
<h3><strong>Type Signature Patterns</strong></h3>
<p>These pointcut expressions are applied to all joinpoint of certain types. A common type signature patterns looks like</p>
<pre><strong>within(type name)  </strong></pre>
<p>Here type name is either the package name or the class name.</p>
<p><strong>Examples</strong></p>
<ul>
<li>within(com.aspects.blog.package.*) : This will match all the methods in all classes of com.aspects.blog.package.</li>
<li>within(com.aspects.blog.package..*) : This will match all the methods in all classes of com.aspects.blog.package and its sub packages. The only difference is the extra dot(.) after package.</li>
<li>within(com.aspects.blog.package.DemoClass) : This will match all the methods in the DemoClass.</li>
<li>within(DemoClass) : Again, if the target class is located in the same package as this aspect, the package name can be omitted.</li>
<li>within(DemoInterface+) : This will match all the methods which are in classes which implement DemoInterface.</li>
</ul>
<h3><strong>Bean Name Patterns</strong></h3>
<p>Spring 2.5 supports a new pointcut type that is used to match bean names. For example, the following pointcut expression matches beans whose name ends with Service.</p>
<pre><strong>bean(*Service) </strong></pre>
<p>This pointcut is not supported by AspectJ annotation, hence you can declare them only in spring context files.</p>
<h3><strong>Combining Pointcut Expressions</strong></h3>
<p>Pointcut expressions can be combined using &amp;&amp; (and), ||(or), and !(not). For example,</p>
<pre><strong>within(DemoInterface1+) || within(DemoInterface2+)</strong></pre>
<p>The above patterns will match all join point in all classes which implement DemoInterface1 or DemoInterface2</p>
<h3><strong>Declaring Pointcut Parameters</strong></h3>
<p>One way to access join point information is by reflection (i.e., via an argument of type org.aspectj.lang.JoinPoint in the advice method). Besides, you can access join point information in a declarative way by using some kinds of special pointcut expressions. For example,</p>
<p><pre class="brush: java;">
@Aspect
public class SomeAspect {

  @Before(&amp;quot;execution(* *.*(..)) &amp;amp;&amp;amp; target(target) &amp;amp;&amp;amp; args(a,b)&amp;quot;)
  public void someMethod(Object target, int a, int b) {
    log.info(&amp;quot;Target class : &amp;quot; + target.getClass().getName());
    log.info(&amp;quot;Arguments : &amp;quot; + a + &amp;quot;, &amp;quot; + b);
  }
}
</pre></p>
<p>Here, target captures the target object and args captures the parameters.</p>
<h3><strong>Applying arbitrary patterns</strong></h3>
<p>Although the syntax of the AspectJ pointcut expressions is pretty rich, you may find some scenarios in which they are not sufficient to provide the necessary behaviour. In such scenarios, you may choose to create an annotation and use that to match joinpoints. This is done in the following manner</p>
<p>First create an annotation</p>
<p><pre class="brush: java;">
@Target(ElementType.Method)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @Interface ApplyAspect {
}
</pre></p>
<p>Once you have created this annotation, you can created pointcut expressions like</p>
<pre><strong>@annotation(ApplyAspect)</strong></pre>
<p>This will match those methods which are annotated with @ApplyAspect. You can also apply this to classes, for example</p>
<pre><strong>@within(ApplyAspect)</strong></pre>
<p>This will match all joinpoints in classes annotated with @ApplyAspect.</p>
<h3><strong>Conclusion</strong></h3>
<p>In this blog, I have discussed the expressions for AspectJ pointcuts, which are powerful mechanism to filter the joinpoints.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/guptavikas.wordpress.com/279/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/guptavikas.wordpress.com/279/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/guptavikas.wordpress.com/279/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/guptavikas.wordpress.com/279/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/guptavikas.wordpress.com/279/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/guptavikas.wordpress.com/279/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/guptavikas.wordpress.com/279/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/guptavikas.wordpress.com/279/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/guptavikas.wordpress.com/279/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/guptavikas.wordpress.com/279/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/guptavikas.wordpress.com/279/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/guptavikas.wordpress.com/279/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/guptavikas.wordpress.com/279/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/guptavikas.wordpress.com/279/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=guptavikas.wordpress.com&amp;blog=7715205&amp;post=279&amp;subd=guptavikas&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://guptavikas.wordpress.com/2010/04/15/aspectj-pointcut-expressions/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/58747853422550c061ac41ab764504d2?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">hivikas</media:title>
		</media:content>
	</item>
		<item>
		<title>Domain Driven Design : Making Implicit concepts Explicit</title>
		<link>http://guptavikas.wordpress.com/2010/01/06/domain-driven-design-making-implicit-concepts-explicit/</link>
		<comments>http://guptavikas.wordpress.com/2010/01/06/domain-driven-design-making-implicit-concepts-explicit/#comments</comments>
		<pubDate>Wed, 06 Jan 2010 04:20:16 +0000</pubDate>
		<dc:creator>Vikas Gupta</dc:creator>
				<category><![CDATA[DDD]]></category>
		<category><![CDATA[Design Patterns]]></category>
		<category><![CDATA[EA Patterns]]></category>
		<category><![CDATA[Domain Driven Design]]></category>
		<category><![CDATA[enterprise design patterns]]></category>

		<guid isPermaLink="false">http://guptavikas.wordpress.com/?p=254</guid>
		<description><![CDATA[In the previous post, I discussed about how to query the domain objects. That post completes the issues with domain object lifecycle management. In this post, I will discuss how to make implicit concepts explicit in order to make domain model more expressive Sometimes small details of the design get lost in the code. We [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=guptavikas.wordpress.com&amp;blog=7715205&amp;post=254&amp;subd=guptavikas&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p><em>In the previous post, I discussed about how to <a href="http://guptavikas.wordpress.com/2009/12/30/domain-driven-design-querying-domain-objects/">query the domain objects.</a> That post completes the issues with domain object lifecycle management. In this post, I will discuss how to make implicit concepts explicit in order to make domain model more expressive</em></p>
<p>Sometimes small details of the design get lost in the code. We tend to consider small business rules and constraints as implicit and these details are not given enough importance as they should be given.They are often coded as a bunch of if-else blocks in the code and this makes the identification of these business rules difficult and more importantly makes design less effective. Let see some of the concepts/design patterns which can be used to make these implicit concepts more explicit. <span id="more-254"></span></p>
<p><strong>Specification</strong></p>
<p>Most application have small rules which are evaluated as boolean value. Some of these can be simple. But, there are certain rules which are fairly complex. They are infact, a combination of one or more of such smaller business rules. Sometimes, these rules are applicable on multiple objects and can be complex enough to make their prescence felt and it is advisable to factor them out in a separate class or method. Such business rules can be termed as Specification as test any object to see whether it satisfies the specified criteria. Let&#8217;s see the example of a specification.</p>
<p><pre class="brush: java;">
class OverdueInvoiceSpecification extends InvoiceSpecification {
   private Date currentDate;

   public OverdueInvoiceSpecification(Date currentDate) {
      this.currentDate = currentDate;
   }

   public boolean isSatisfiedBy(Invoice invoice) {
      int gracePeriod = invoice.customer().getPaymentGracePeriod();
      Date deadline = invoice.dueDate() + gracePeriod;

      return currentDate.after(deadline);
   }
}
</pre></p>
<p>Now, we can simply apply the rules wherever, we want</p>
<p><pre class="brush: java;">
class CustomerAccount {
  boolean isOverDue() {
   Specification overDueSpec = new OverdueInvoiceSpecification(new Date());
   Iterator&amp;lt;Invoice&amp;gt; listInvoices = customer.getInvoices().iterator();
   for (Invoice invoice : listInvoices) {
     if (overDueSpec.isSatisfiedBy(invoice)) return true;
   }
   return false;
  }
}
</pre></p>
<p>There can be many places which warrant the use of specification pattern in an application. Mostly, they are used in</p>
<ul>
<li>Validations, as demonstrated above</li>
<li>In filtering data, based on business rules. For doing this we can combine <a href="http://guptavikas.wordpress.com/2009/12/30/domain-driven-design-querying-domain-objects/">Repositories</a> with Specifications and filter data returned from the persistent storage</li>
<li>In domain object security. We can check using specification whether a particular object is editable by a user with specified role. <a href="http://static.springsource.org/spring-security/site/">Spring security</a> provides a more sophisticated framework for this.</li>
</ul>
<p>There is no doubt that factoring out methods and classes for these business rules makes design more expressive, but, there can be numerous such rules in the code and factoring a separate places for each of them can be quite cumbersome. So, how to decide when to create a new method or class for a business rule or constraint.  I think the key lies in the word business. If a condition affects a business decision, it is a business rule and we can model them separately in a method or class. Moreover, if the specification code in itself is bit involved and can be applied as multiple places, it is better to separate them out of the domain object.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/guptavikas.wordpress.com/254/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/guptavikas.wordpress.com/254/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/guptavikas.wordpress.com/254/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/guptavikas.wordpress.com/254/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/guptavikas.wordpress.com/254/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/guptavikas.wordpress.com/254/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/guptavikas.wordpress.com/254/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/guptavikas.wordpress.com/254/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/guptavikas.wordpress.com/254/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/guptavikas.wordpress.com/254/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/guptavikas.wordpress.com/254/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/guptavikas.wordpress.com/254/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/guptavikas.wordpress.com/254/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/guptavikas.wordpress.com/254/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=guptavikas.wordpress.com&amp;blog=7715205&amp;post=254&amp;subd=guptavikas&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://guptavikas.wordpress.com/2010/01/06/domain-driven-design-making-implicit-concepts-explicit/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/58747853422550c061ac41ab764504d2?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">hivikas</media:title>
		</media:content>
	</item>
		<item>
		<title>Domain Driven Design : Querying Domain Objects</title>
		<link>http://guptavikas.wordpress.com/2009/12/30/domain-driven-design-querying-domain-objects/</link>
		<comments>http://guptavikas.wordpress.com/2009/12/30/domain-driven-design-querying-domain-objects/#comments</comments>
		<pubDate>Wed, 30 Dec 2009 12:29:44 +0000</pubDate>
		<dc:creator>Vikas Gupta</dc:creator>
				<category><![CDATA[DDD]]></category>
		<category><![CDATA[Design Patterns]]></category>
		<category><![CDATA[EA Patterns]]></category>
		<category><![CDATA[Domain Driven Design]]></category>
		<category><![CDATA[enterprise design patterns]]></category>

		<guid isPermaLink="false">http://guptavikas.wordpress.com/?p=234</guid>
		<description><![CDATA[After having discussed about object creation in the previous post, I would like to discuss the challenges of querying objects in a domain model. There is a well designed domain model with a rich set of associations between objects. How to get to a particular entity or value object inside the domain model? Since the [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=guptavikas.wordpress.com&amp;blog=7715205&amp;post=234&amp;subd=guptavikas&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p><em>After having discussed about <a href="http://guptavikas.wordpress.com/2009/12/21/domain-driven-design-creating-domain-objects/">object creation</a></em><em> in the previous post, I would like to discuss the challenges of querying objects in a domain model.</em></p>
<p>There is a well designed domain model with a rich set of associations between objects. How to get to a particular entity or value object inside the domain model? Since the domain model is well connected, if you have a reference to a root entity, you can get to the other members to which this root is associated. But, how to get to this root? Well, we can have a global root which contains the collections of all the root of the entities. For example, in a sales order application, you can have a global root containing the collection of order and customer objects.</p>
<p>One drawback of the above solution is that it will perform badly in a distributed system. For example, when a client asks the global root to return the list of customers, and there are millions of customers, we have to do a database query and it will return millions of records. This will cause a lot of data transfer on the network. With multiple clients, this solutions would not work at all.</p>
<p>In most situations, you would need only a subset of customers which meet a particular set of conditions. So, what are the options that we have to return a subset of customers to the client in a way which performs well and does swamp the domain model with the complexity of the query logic. The options that we have are<span id="more-234"></span></p>
<ul>
<li>Using a SQL query</li>
<li>Query Objects</li>
<li>Repository Objects</li>
</ul>
<p>Let&#8217;s look at these options in detail.</p>
<p><strong>Using an SQL query </strong></p>
<p>An SQL query is a powerful tool to get what we want from the database. Using an SQL query involves processing the resultset returned from the database and converting into object format. This data access code if coded inside the domain objects can result in obfuscating the domain model. Also, there is a tight coupling between domain objects and database.</p>
<p>This problem of translating between object world and the database world can partially be solved by using <a href="http://martinfowler.com/eaaCatalog/metadataMapping.html">metadata mapping</a>. Meta data mapping reduces the overhead of translating between java objects and sql resultsets. But, the problem of separating data access code from the domain model is still there if sql queries are employed.</p>
<p><strong>Query Objects</strong></p>
<p>A Query Object is a structure of objects that can form itself into a SQL query. You can create this query by referring to classes and fields rather than tables and columns. In this way those who write the queries can do so independently of the database schema and changes to the schema can be localized in a single place. A Query object is based on <a href="http://en.wikipedia.org/wiki/Interpreter_pattern">Interpreter</a> pattern. Hibernate, a leading framework for Object Relational mapping provides API for query Objects. Following is an example of data Access Code written using query objects</p>
<p><pre class="brush: java;">
List cats = sess.createCriteria(Cat.class)
    .add( Restrictions.like(&amp;quot;name&amp;quot;, &amp;quot;Fritz%&amp;quot;) )
    .add( Restrictions.between(&amp;quot;weight&amp;quot;, minWeight, maxWeight) )
    .list();
</pre></p>
<p>The advantages of Query Object come with more sophisticated needs: keeping database schemas encapsulated, supporting multiple databases, supporting multiple schemas, and optimizing to avoid multiple queries. Some projects with a particularly sophisticated data source team might want to build these capabilities themselves, but most people who use Query Object do so with a tool. There are a lot of tools available like Hibernate, Toplink, iBatis which provide APIs for creating queries using object oriented code.</p>
<p><strong>Repository Objects</strong></p>
<p>Query Objects help in cleaning up the domain model from the data access code. But, in most scenarios, it is advisable to separate the data access code from the domain model into a separate layer. A <strong>Repository</strong> mediates between the domain and data mapping layers, acting like an in-memory domain object collection.</p>
<p>Repository presents a simple interface. Clients create a criteria object specifying the characteristics of the objects they want returned from a query. For example, to find person objects by name we first create a criteria object, setting each individual criterion like so: criteria.equals(Person.LAST_NAME, &#8220;Gupta&#8221;), and criteria.like(Person.FIRST_NAME, &#8220;V&#8221;). Then we invoke repository.matching(criteria) to return a list of domain objects representing people with the last name Gupta and a first name starting with V. Under the covers, Repository combines Metadata Mapping with a Query Object to automatically generate SQL code from the criteria. An example involving repository is shown below</p>
<p><pre class="brush: java;">
public class Person { //domain object
   public List dependents() {
      return Registry.personRepository().dependentsOf(this);
   }
}

public class PersonRepository extends Repository {
   public List dependentsOf(aPerson) {
      Criteria criteria = new Criteria();
      criteria.equal(Person.parent, aPerson);
      return matching(criteria);
   }
}

abstract class Repository {
   private RepositoryStrategy strategy;
   protected List matching(aCriteria) {
      return strategy.matching(aCriteria);
   }
}

public class RelationalStrategy implements RepositoryStrategy {
   protected List matching(Criteria criteria) {
      Query query = new Query(myDomainObjectClass())
      query.addCriteria(criteria);
      return query.execute();
   }
}
</pre></p>
<p>Because Repository&#8217;s interface shields the domain layer from awareness of the data source, we can refactor the implementation of the querying code inside the Repository without changing any calls from clients. Indeed, the domain code needn&#8217;t care about the source or destination of domain objects. In we want to change the data to be picked up from the memory instead of the database, we can simply change the RepositoryStrategy from relational to in memory by creating an in memory relational strategy.</p>
<p>After having discussed about various methods of querying the domain objects, we can conclude that on a large project with complex domain we should not use queries directly from the domain model. Now, as far as query objects and repositories are concerned, I think they both resolve a separate problem. Query Objects help in abstracting the data access code in an object oriented way, whereas, Repository is used for separating the data access code from the query objects and providing for additional sophistication, id required. Moreover, if you are using sophisticated tools like Hibernate, they provide the APIs which implement these patterns.</p>
<p><em>So far in this series, we have discussed the basics of domain driven design. In the next part of this series, I will discuss about Specification pattern.</em></p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/guptavikas.wordpress.com/234/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/guptavikas.wordpress.com/234/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/guptavikas.wordpress.com/234/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/guptavikas.wordpress.com/234/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/guptavikas.wordpress.com/234/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/guptavikas.wordpress.com/234/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/guptavikas.wordpress.com/234/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/guptavikas.wordpress.com/234/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/guptavikas.wordpress.com/234/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/guptavikas.wordpress.com/234/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/guptavikas.wordpress.com/234/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/guptavikas.wordpress.com/234/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/guptavikas.wordpress.com/234/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/guptavikas.wordpress.com/234/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=guptavikas.wordpress.com&amp;blog=7715205&amp;post=234&amp;subd=guptavikas&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://guptavikas.wordpress.com/2009/12/30/domain-driven-design-querying-domain-objects/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/58747853422550c061ac41ab764504d2?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">hivikas</media:title>
		</media:content>
	</item>
		<item>
		<title>Domain Driven Design : Creating Domain Objects</title>
		<link>http://guptavikas.wordpress.com/2009/12/21/domain-driven-design-creating-domain-objects/</link>
		<comments>http://guptavikas.wordpress.com/2009/12/21/domain-driven-design-creating-domain-objects/#comments</comments>
		<pubDate>Mon, 21 Dec 2009 17:51:36 +0000</pubDate>
		<dc:creator>Vikas Gupta</dc:creator>
				<category><![CDATA[DDD]]></category>
		<category><![CDATA[Design Patterns]]></category>
		<category><![CDATA[EA Patterns]]></category>
		<category><![CDATA[Domain Driven Design]]></category>
		<category><![CDATA[enterprise design patterns]]></category>

		<guid isPermaLink="false">http://guptavikas.wordpress.com/?p=217</guid>
		<description><![CDATA[In one of the previous posts, I discussed about Aggregates and their design considerations. In this part of the series, I will discuss the issues in object creation with domain objects. The normal way of creating an object by it&#8217;s client is via it&#8217;s public constructor. This works well with a simple objects. But, when [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=guptavikas.wordpress.com&amp;blog=7715205&amp;post=217&amp;subd=guptavikas&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p><em>In one of the previous posts, I discussed about <a href="http://guptavikas.wordpress.com/2009/12/14/domain-driven-design-aggregates/">Aggregates</a> and their design considerations. In this part of the series, I will discuss the issues in object creation with domain objects.<br />
</em></p>
<p>The normal way of creating an object by it&#8217;s client is via it&#8217;s public constructor. This works well with a simple objects. But, when complex objects like Aggregates are concerned, their construction can be complex and the process of creation can become overwhelming for an object to handle. As part of it&#8217;s construction, an aggregate might have to</p>
<ul>
<li>create local entities within an aggregate.</li>
<li>check the invariant logic before adding a local entity.</li>
</ul>
<p>Object creation has nothing to do with the domain. Moreover, with complex object creation, an object tends break the <a href="http://en.wikipedia.org/wiki/Single_responsibility_principle">Single Responsibility Principle</a>(SRP). So, it is recommended to separate the object creation logic from the object. In Domain Driven Design(DDD), a program element whose primarily responsibility is to create complex domain objects and aggregates is called a Factory. Ideally, a factory should create the product atomically with all the safety checks, that is, with the all the invariants applied appropriately.<span id="more-217"></span></p>
<p>The DDD Factory pattern is different from the Gof Factory patterns, in that, the Gof patterns are on a technical level, whereas, DDD factory pattern is more on semantic domain model level. In fact, a DDD factory might make use of Gof <a href="http://en.wikipedia.org/wiki/Creational_pattern">creational patterns</a> to create the domain objects. From hereon, I will refer DDD factory as a factory and indicate appropriately whenever a Gof factory is referred.</p>
<p>Factories have several benefits over constructors, which are</p>
<ul>
<li>Factories can tell about the objects they are creating, while constructors cannot. Let&#8217;s take an example, an Order object can be created by passing params or by using an existing object to create a repeat order. So, in the Order class, two constructors for can be created as<br />
<pre class="brush: java;">
class Order{
  public Order(params) {}
  public Order(Order repearOrder) {}
}
</pre></p>
<p>where, if we use factory, we can make code more expressive, as shown below</p>
<p><pre class="brush: java;">
class OrderFactory{
  public static Order createOrder(params) {}
  public static Order createRepeatOrder(Order order) {}
}
</pre></li>
<li>Whenever we call a constructor, a new object is created, whereas, we can control object creation by using factory. We can create a pool of objects and we might not have to create new objects every time. This is more applicable in case of Value Objects factories since VOs are mostly immutable we can keep a pool of VOs and avoid new object creation every time.</li>
<li>Factories are polymorphic, in that, they can return the object or any subtype of the object being created, whereas, constructors do not provide such flexibility.</li>
<li>In cases where the object being created has a lot of optional parameters, we can have a Builder object as the Factory. <a href="http://en.wikipedia.org/wiki/Builder_pattern">Builder</a> is one of Gof&#8217;s creational pattern which is used when an object has to be created in steps or when there are large number of optional parameters. For example, If an object has 2 mandatory parameters and 8 optional parameters, then it is not advisable to use constructors as providing constructors for all the combinations would swamp the object with constructors.</li>
</ul>
<p>In this blog, we discussed about the Factory pattern and it&#8217;s advantages over constructors as a means for creating objects. In case of complex objects or aggregates, factories encapsulate object creation logic and make model more expressive. However, in case of simple objects which do not have a lot of optional parameters, it is advisable to avoid factories and stick to constructors.</p>
<p><em>Factories deal with early life of a domain object, but a domain object has a longer life cycle. A lot of time, we have to resurrect a domain object from storage. This part can be a little different from Factory and that&#8217;s why there is a separate pattern for it, which is know as Repository pattern. I will present that in the next part of the series.</em></p>
<div id="_mcePaste" style="overflow:hidden;position:absolute;left:-10000px;top:141px;width:1px;height:1px;">Let&#8217;s look at the</div>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/guptavikas.wordpress.com/217/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/guptavikas.wordpress.com/217/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/guptavikas.wordpress.com/217/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/guptavikas.wordpress.com/217/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/guptavikas.wordpress.com/217/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/guptavikas.wordpress.com/217/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/guptavikas.wordpress.com/217/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/guptavikas.wordpress.com/217/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/guptavikas.wordpress.com/217/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/guptavikas.wordpress.com/217/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/guptavikas.wordpress.com/217/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/guptavikas.wordpress.com/217/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/guptavikas.wordpress.com/217/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/guptavikas.wordpress.com/217/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=guptavikas.wordpress.com&amp;blog=7715205&amp;post=217&amp;subd=guptavikas&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://guptavikas.wordpress.com/2009/12/21/domain-driven-design-creating-domain-objects/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/58747853422550c061ac41ab764504d2?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">hivikas</media:title>
		</media:content>
	</item>
		<item>
		<title>Domain Driven Design : Aggregates</title>
		<link>http://guptavikas.wordpress.com/2009/12/14/domain-driven-design-aggregates/</link>
		<comments>http://guptavikas.wordpress.com/2009/12/14/domain-driven-design-aggregates/#comments</comments>
		<pubDate>Mon, 14 Dec 2009 14:11:57 +0000</pubDate>
		<dc:creator>Vikas Gupta</dc:creator>
				<category><![CDATA[DDD]]></category>
		<category><![CDATA[Design Patterns]]></category>
		<category><![CDATA[EA Patterns]]></category>
		<category><![CDATA[Domain Driven Design]]></category>

		<guid isPermaLink="false">http://guptavikas.wordpress.com/?p=176</guid>
		<description><![CDATA[Every object has a lifecycle. Some objects take birth and die in a single method while others have a more complex and longer life. Typically, Domain Objects falls into the second category. The lifecycle of a domain object is shown below As the lifecycle of a domain model is complex, it is advisable to separate [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=guptavikas.wordpress.com&amp;blog=7715205&amp;post=176&amp;subd=guptavikas&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Every object has a lifecycle. Some objects take birth and die in a single method while others have a more complex and longer life. Typically, <strong>Domain Objects</strong> falls into the second category. The lifecycle of a domain object is shown below</p>
<p><a href="http://guptavikas.files.wordpress.com/2009/12/lifecycle.png"><img class="aligncenter size-medium wp-image-179" title="lifecycle" src="http://guptavikas.files.wordpress.com/2009/12/lifecycle.png?w=300&#038;h=192" alt="" width="300" height="192" /></a>As the lifecycle of a domain model is complex, it is advisable to separate the domain logic from the lifecycle management logic. Furthermore, sometimes, grouping related objects to manage them as an entity is easier than managing each of them separately. <strong>Domain Driven Design(DDD)</strong> suggests to group related objects as <strong>Aggregates</strong> and to use <strong>Factories</strong> and <strong>Repositories</strong> to manage the lifecycle of the object. In this blog, I will discuss about the <strong>Aggregates</strong> and their design considerations.<span id="more-176"></span></p>
<p><strong>Aggregates</strong></p>
<p>In a software system, a common requirement can be to maintain the history of the changes to a user&#8217;s payment information, like credit card number, cvv number, etc. Typically, this is done by creating an object for user&#8217;s history and persisting it. This can be done as shown in the code below</p>
<p><pre class="brush: java;">
void updatePaymentInformation(params...) { //service class  method
  User user = User.get(id);

  UserHistory userHistory = new UserHistory(user); //copy constructor to copy auditable fields
  userHistory.save();

  user.setCreditCardNumber();
  user.setCvvNumber();
  user.save();
}
</pre></p>
<p>Above code seemingly easy, but logically, UserHistory does not have use without a user. The true identity of the UserHistory is the associated user. So, it is better to manage the UserHistory from the User object itself as shown in the code below.</p>
<p><pre class="brush: java;">
class User {
  Set&amp;lt;UserHistory&amp;gt; userHistories;
  void updatePaymentInformation(params..) { //user class method
    this.setCreditCardNumber(...);
    this.setCvvNumber(...)
    userHistories.add(new UserHistory(this));
  }
}
</pre></p>
<p>In above example, we can see that UserHistory cannot exist without User. So, we can enforce the access to UserHistory through User object only. This will minimize the dependencies between the classes and reduce complexity. The example mentioned in here in trivial, but in real world, there can be many other scenarios where one entity can also exist without another entity, like an Order item cannot exist without an Order, a Book cannot exist without a page. One important thing to note here is that in these examples, the reverse relation is also important, i.e., an Order does not have a meaning without a Order item and nobody will read a book without pages. Here, Book and Order represent a cluster of associated objects, which model something meaningful as a whole but lose importance when separated from each other.</p>
<p>In DDD, such cluster of associated objects is known as a <strong>Aggregate</strong>. Each aggregate has a <strong>root</strong> and a <strong>conceptual boundary</strong>. Root is a specific entity in the aggregate and is the only member of the aggregate visible(allowed to get referred from other objects) to rest of the world. Entities other than the Root entity are local entities, which have identities to distinguish them within the aggregate.</p>
<p>Other than managing the access to local entities of the aggregate, root of the aggregate can also enforce the <strong>invariants</strong>, which are consistency rules which needs to be maintained whenever data changes. For example, in most Purchase Orders(PO) there is a approval limit. So, whenever a new PO item is added to the PO, we can check whether adding the item will make PO exceed it&#8217;s approval limit.</p>
<p>Since aggregates model a concept which represent a meaningful whole, consistency of aggregates are very important. To maintain consistency of aggregates, we need to apply a set of rules, which are</p>
<ul>
<li>The root entity should be the only window to the aggregate to the outside world.</li>
<li>All local entities within the aggregate should be accessed by traversing the tree from the root entity.</li>
<li>Invariants, if any, should be applied only by the root entity. Invariants should be applied at all times, i.e, whenever a non root member of the aggregate is inserted, update or deleted, all applicable invariants should be satisfied.</li>
<li>Any object which is outside the aggregate should not have references to entity or value objects which are member of the aggregate. The only exception to this rule is root entity.</li>
<li>Any update to the non root member should we through root entity as it would help in satisfying the aggregates.</li>
</ul>
<p>In this blog, we discussed about the Aggregates and the set of rules to be applied while designing them. Although, an aggregate is a cluster of different objects, they represent a business concept as a unit. On the face of it, Aggregates seem to reduce the complexity of the model and make the model clean. But, we should avoid overuse of aggregates. We should avoid overuse of aggregates because</p>
<ul>
<li>Overuse would result in deep nested trees and this would require a longer traversal time to the local entities.</li>
<li>In a distributed environment, serialization and de-serialization would take time if we have deeply nested structures.</li>
</ul>
<p>Modelling aggregates judiciously would reduce the complexity and maintain consistency of the domain model.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/guptavikas.wordpress.com/176/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/guptavikas.wordpress.com/176/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/guptavikas.wordpress.com/176/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/guptavikas.wordpress.com/176/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/guptavikas.wordpress.com/176/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/guptavikas.wordpress.com/176/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/guptavikas.wordpress.com/176/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/guptavikas.wordpress.com/176/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/guptavikas.wordpress.com/176/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/guptavikas.wordpress.com/176/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/guptavikas.wordpress.com/176/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/guptavikas.wordpress.com/176/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/guptavikas.wordpress.com/176/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/guptavikas.wordpress.com/176/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=guptavikas.wordpress.com&amp;blog=7715205&amp;post=176&amp;subd=guptavikas&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://guptavikas.wordpress.com/2009/12/14/domain-driven-design-aggregates/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/58747853422550c061ac41ab764504d2?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">hivikas</media:title>
		</media:content>

		<media:content url="http://guptavikas.files.wordpress.com/2009/12/lifecycle.png?w=300" medium="image">
			<media:title type="html">lifecycle</media:title>
		</media:content>
	</item>
		<item>
		<title>Domain Driven Design : Expressing Concepts</title>
		<link>http://guptavikas.wordpress.com/2009/12/08/domain-driven-design-expressing-concepts/</link>
		<comments>http://guptavikas.wordpress.com/2009/12/08/domain-driven-design-expressing-concepts/#comments</comments>
		<pubDate>Tue, 08 Dec 2009 14:26:18 +0000</pubDate>
		<dc:creator>Vikas Gupta</dc:creator>
				<category><![CDATA[DDD]]></category>
		<category><![CDATA[Design Patterns]]></category>
		<category><![CDATA[EA Patterns]]></category>
		<category><![CDATA[Domain Driven Design]]></category>
		<category><![CDATA[enterprise design patterns]]></category>

		<guid isPermaLink="false">http://guptavikas.wordpress.com/?p=140</guid>
		<description><![CDATA[Object oriented analysis and design(OOAD) is essentially an activity to model a system as an interaction between objects. Each object, which is an instance of a class and has state and behaviour, represents an entity with in the system. These entities invoke other entities to perform certain activities and are often associated with each other [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=guptavikas.wordpress.com&amp;blog=7715205&amp;post=140&amp;subd=guptavikas&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p><a href="http://en.wikipedia.org/wiki/Object-oriented_analysis_and_design">Object oriented analysis and design(OOAD)</a> is essentially an activity to model a system as an interaction between objects. Each object, which is an instance of a class and has state and behaviour, represents an entity with in the system. These entities invoke other entities to perform certain activities and are often associated with each other to model a system. <strong>Domain driven design(DDD)</strong> recommends guidelines which tend to optimize/enhance the process of identifying entities and defining relationship between them. It advocates to classify objects as <strong>Entities</strong> and <strong>Value objects</strong> based on certain criteria, to model <strong>Services,</strong> which abstract behaviour which is not specific to a particular entity, to divide application into <strong>Modules</strong>, and to minimize and constrain <strong>Associations</strong> between objects. In this blog, I will discuss these recommendations.<br />
<span id="more-140"></span><br />
<strong>Associations</strong></p>
<p><strong><a href="http://guptavikas.files.wordpress.com/2009/12/association1.png"><img class="aligncenter size-medium wp-image-164" title="association" src="http://guptavikas.files.wordpress.com/2009/12/association1.png?w=254&#038;h=150" alt="" width="254" height="150" /></a></strong>An association is basically a relationship between two entities. There can be a variety of relationships between objects. <strong>(Unified Modelling Language)UML </strong>specifies a notation for many of them. A succinct list of UML associations can be referred from <a href="http://www.shrinkrays.net/articles/uml-cheat-sheet.aspx">here</a>. DDD does not add any specific relationship of it&#8217;s own but instead suggests to optimize them by</p>
<ul>
<li>Imposing a traversal direction</li>
<li>Adding a qualifier to reduce multiplicity</li>
<li>Eliminating non-essential associations</li>
</ul>
<p>An order is placed for a customer, and over a period of time, a customer can have many orders. So, there is a bi-directional one-to-many relationship between a customer and an order. But, a deeper insight might reveal that most of the times we need to know the customer to whom a particular order belongs. But, only in some cases, we need to find out the orders of a customer. So, for simplicity, this relationship can be modelled as a uni-directional one-to-many relationship between a customer and an order and the traversal direction from order to customer. If we need the ability to find orders by customer, this can be done through a database query.</p>
<p>A brokerage account can have many investments. So, there is a one to many relationship between a brokerage account and it&#8217;s investments. But most investment are against a stock. So, a one-to-many relationship can be reduced to a one-to-one relationship by adding a qualifier, which in this case would be a stock symbol. This is shown in the following code segment</p>
<p><pre class="brush: java;">
public class BrokerageAccount {
  Set&amp;lt;Investment&amp;gt; Investments;
  public Set getInvestments() {
    return investments;
  }
}
</pre></p>
<p>The above code can be changed to</p>
<p><pre class="brush: java;">
public class BrokerageAccount {
  Map&amp;lt;String stockSymbol, Investment&amp;gt; investments;
  public Set getInvestment(String stockSymbol) {
    return (Investment) investments.get(stockSymbol);
  }
}
</pre></p>
<p>The fact that an investment is against a stock symbol is made more explicit by adding a qualifier which in this case is a stock symbol.<br />
<strong><br />
Entities</strong></p>
<p><strong><a href="http://guptavikas.files.wordpress.com/2009/12/identity.png"><img class="aligncenter size-full wp-image-145" title="identity" src="http://guptavikas.files.wordpress.com/2009/12/identity.png?w=123&#038;h=160" alt="" width="123" height="160" /></a></strong>An entity is something which has an identity and is clearly distinguishable from other entities of same or other type. It can be a person, place, ticket, or anything else which can be distinguished from other entities. The identity of an entity can either be a computer generated number or it can be a combination of the attributes.</p>
<p><strong>Value Objects</strong></p>
<p>Values object are something which represent concepts but does not have an identity of their own. When you care only about the attributes of an object, classify it as value objects. Value objects can</p>
<ul>
<li>be an assembly of other objects: For example, in a building plan, a wall consists of window. Both these objects does not have an identity of their own because it may not be required to identify them.</li>
<li>refer to entities: For example, in an online map service, a route object consists of source and destination city, both of which may be an entity.</li>
</ul>
<p><a href="http://guptavikas.files.wordpress.com/2009/12/voexpr.png"><img class="aligncenter size-medium wp-image-154" title="voexpr" src="http://guptavikas.files.wordpress.com/2009/12/voexpr.png?w=300&#038;h=177" alt="" width="300" height="177" /></a>Values object makes domain model expressive. For example, the fact that Customer has an Address is made more explicit by modelling Address an a value object.</p>
<p>It is recommended to model VOs as immutable objects. This makes them thread safe and easily shareable. Making a value object immutable also open the doors for some optimization. We can use patterns like <a href="http://en.wikipedia.org/wiki/Flyweight_pattern">Flyweight</a>, which replaces large number of unshared objects with smaller number of shareable objects.</p>
<p>Making a VO immutable seems to be an obvious choice. However, if the value of the VO changes frequently and the creation of a new VO is expensive, then making it mutable seems to be a better choice. Despite all this, always design a VO as immutable and, if required, make it mutable.</p>
<p><strong>Services</strong></p>
<p><strong><a href="http://guptavikas.files.wordpress.com/2009/12/services1.png"><img class="aligncenter size-full wp-image-147" title="services" src="http://guptavikas.files.wordpress.com/2009/12/services1.png?w=140&#038;h=140" alt="" width="140" height="140" /></a></strong></p>
<p>In some<strong> </strong>cases, a particular behaviour does not belong to a particular entity or value object. So, instead of bloating an object with the behaviour it does not intends to do, it is better to model it as a Service. A service provides a behaviour through an interface. The behaviour can be an action, or an activity. A service should not have a state of it&#8217;s own so that it can be shared easily and it&#8217;s behaviour can be reused easily.</p>
<p>A service can be classified as an <strong>application</strong> service which is involved with services like transactions, security, logging, etc., and a <strong>domain</strong> service which encapsulate behaviour not specific to any object. Although, application services provide very important services to an application, but in DDD, domain services are primary concerns while modelling behaviour.</p>
<p><strong>Modules</strong></p>
<p>Modules is a less talked about topic of DDD because the reasons to divide an application into modules are fairly obvious and we have been doing that for a long time. I will reiterate those reasons here once again</p>
<ul>
<li>Modules help in breaking down the complexity of an application.</li>
<li>Modules acts as a communication aid because when we discuss a functionality by associating it with modules, the discussion context is narrowed down.</li>
<li>Modules facilitate parallel development.</li>
</ul>
<p><strong>Conclusion</strong></p>
<p>In this blog, we discussed various elements of DDD which makes domain modelling expressive. Constrained associations reduces the complexity of the domain models, whereas  adding directions to relationships makes it more expressive. The idea of having immutable value objects seems to add expression to models by making concepts more expressive. Services take the load off the entities, and since they are interface based, we can change the implementation without affecting the domain object. Modules break the story of domain model into chapters. Applying these concepts judiciously will surely help in expressing a deep insight into the domain of the software.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/guptavikas.wordpress.com/140/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/guptavikas.wordpress.com/140/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/guptavikas.wordpress.com/140/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/guptavikas.wordpress.com/140/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/guptavikas.wordpress.com/140/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/guptavikas.wordpress.com/140/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/guptavikas.wordpress.com/140/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/guptavikas.wordpress.com/140/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/guptavikas.wordpress.com/140/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/guptavikas.wordpress.com/140/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/guptavikas.wordpress.com/140/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/guptavikas.wordpress.com/140/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/guptavikas.wordpress.com/140/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/guptavikas.wordpress.com/140/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=guptavikas.wordpress.com&amp;blog=7715205&amp;post=140&amp;subd=guptavikas&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://guptavikas.wordpress.com/2009/12/08/domain-driven-design-expressing-concepts/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/58747853422550c061ac41ab764504d2?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">hivikas</media:title>
		</media:content>

		<media:content url="http://guptavikas.files.wordpress.com/2009/12/association1.png?w=300" medium="image">
			<media:title type="html">association</media:title>
		</media:content>

		<media:content url="http://guptavikas.files.wordpress.com/2009/12/identity.png" medium="image">
			<media:title type="html">identity</media:title>
		</media:content>

		<media:content url="http://guptavikas.files.wordpress.com/2009/12/voexpr.png?w=300" medium="image">
			<media:title type="html">voexpr</media:title>
		</media:content>

		<media:content url="http://guptavikas.files.wordpress.com/2009/12/services1.png" medium="image">
			<media:title type="html">services</media:title>
		</media:content>
	</item>
		<item>
		<title>Domain Driven Design : An Introduction</title>
		<link>http://guptavikas.wordpress.com/2009/12/01/domain-driven-design-an-introduction/</link>
		<comments>http://guptavikas.wordpress.com/2009/12/01/domain-driven-design-an-introduction/#comments</comments>
		<pubDate>Tue, 01 Dec 2009 15:21:59 +0000</pubDate>
		<dc:creator>Vikas Gupta</dc:creator>
				<category><![CDATA[DDD]]></category>
		<category><![CDATA[Design Patterns]]></category>
		<category><![CDATA[EA Patterns]]></category>
		<category><![CDATA[Domain Driven Design]]></category>
		<category><![CDATA[Enterprise Integration pattens]]></category>

		<guid isPermaLink="false">http://guptavikas.wordpress.com/?p=73</guid>
		<description><![CDATA[Introduction The primary purpose of most software projects is to add value to the customer&#8217;s business. This is done by abstracting the complex web of thoughts inside a human mind in the form of a software program. Most software projects cater to a particular domain, and in many software projects, the domain of a software project [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=guptavikas.wordpress.com&amp;blog=7715205&amp;post=73&amp;subd=guptavikas&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p><strong>Introduction</strong></p>
<p><strong><span style="font-weight:normal;">The primary purpose of most software projects is to add value to the customer&#8217;s business. This is done by abstracting the complex web of thoughts inside a human mind in the form of a software program. Most software projects cater to a particular domain, and in many software projects, the domain of a software project is not technical. Unfortunately, majority of the technical people do not give enough importance to the domain of the software, and hence, they lack the required domain knowledge. This lack of domain knowledge leads to a situation where <strong>What</strong>(to do?) takes over <strong>Why</strong>(to do?). Generally, in such a scenario, it might be possible to deliver a usable product, but the primary purpose of adding business value is often neglected.</span></strong></p>
<p>The above mentioned situation is quite common and there is a continual influx of thoughts, which intend to provide a solution, by various experts. <a href="http://domaindrivendesign.org/about">Eric Evans</a> is one of such experts, who based on his experience, gained by working on complex projects, epitomized his findings in the form of tips, suggestions, patterns and guidelines, and coined a term <strong>Domain Driven Design</strong>, better known as <strong>DDD</strong>. In this blog, I intend to present various aspects of DDD and how it suggests to tackle the complexity of the domain.<br />
<span id="more-73"></span><br />
<strong>What is DDD?</strong></p>
<p><strong><a href="http://guptavikas.files.wordpress.com/2009/12/picture_1000_words.jpg"><img class="aligncenter size-medium wp-image-113" title="picture_1000_words" src="http://guptavikas.files.wordpress.com/2009/12/picture_1000_words.jpg?w=300&#038;h=300" alt="" width="300" height="300" /></a><br />
</strong></p>
<p>A picture is worth a thousand words and, sometimes, is better suited to convey a message. Similarly, a domain model is a simplification of the domain of the software and it abstracts the elements of domain which are relevant to the problem the software intends to solve. A domain model is representation agnostic, i.e., it can be represented as an UML diagram, as written code, as simply plain English, or as a simple diagram. The decision to choose an option depends upon the situation and complexity of the problem. The process of creating, maintaining and enhancing highly expressive domain model by applying objected oriented principles, design patterns is known as <strong>Domain Driven Design(DDD)</strong>. One important point to understand is that DDD is not a one time activity. It is an iterative process and model evolves with the project.</p>
<p>We all know that the process of creating domain model by abstracting from the complexities of a domain is not an easy job. Experienced programmers/thought leaders often compare this job with that of an artist. Few would disagree with them. But, with any art, there are certain principles and practices, which make the process of identifying and representing abstractions simpler. DDD also suggests to employ certain principles and practices, which we may already be doing intuitively, to work with highly expressive domain models. Let&#8217;s have a look at some of the principles and practices of DDD.</p>
<p><strong>Getting Started with DDD</strong><br />
There might be several questions, which may be taking shape in the mind right now. Let&#8217;s see which DDD principles and practices applies to specific question</p>
<p><strong>Q:</strong> I don&#8217;t have the domain knowledge. How will I communicate effectively with the domain experts?<br />
<strong>A:</strong> In most projects, there is an interface between the technical people and the domain experts. We may call this expert a Business Analyst, a Product Owner, or with some other name. Sometimes, this interface is not effective to transform the messages between two parties and in the process of message transformation, some relevant details are missed. This leads to a situation where <strong>WHAT</strong> takes over <strong>WHY</strong>.</p>
<p>To overcome this problem, DDD emphasizes to have a close relationship between the domain experts and the developers. Even when a modeler is working with domain experts(DE), he should be hands-on enough to think about design issues while brainstorming with the DE. DDD also suggests DDD developers to pick up key concepts while having conversation with the DE and also educate them about their terminology. This leads to the development of a <strong>Ubiquitous Language(UL)</strong> which forms the basis of development domain model. UL is basically a medium of communication which is used to develop a domain model. It is also used to validate a domain model periodically. The development of UL is an iterative process and is based on mutual agreement between DE and technical people.</p>
<p><strong>Q:</strong> How will I represent my domain model?<br />
<strong> A:</strong> Domain model should be represented in a way which best communicates the intent of the domain knowledge. It can be in the form of a diagram, a UML diagram, plain English, or simply code. Now, when there is freedom to represent something in multiple forms, how to maintain the sanctity of the domain model. I think that&#8217;s the job of the skilled developers or domain modelers. It is difficult to provide a rule for everything and we all know that real world is like that. Sometimes we have to break the rules and take pragmatic decisions. DDD realizes that and promotes developers to take pragmatic decisions instead of being bound by the rules.</p>
<p><strong>Q:</strong> How will I layout the architecture of the application with DDD?<br />
<strong> A:</strong> The focus of DDD is to create domain models that are rich in behavior. Typically, an application has several other issues as well which are not concerned with the domain. To work effectively with DDD, we need to isolate those issues from the domain modelling. In order to do so, we can use layered architecture to isolate and group the problems.</p>
<p><a href="http://guptavikas.files.wordpress.com/2009/12/layering.png"><img class="aligncenter size-full wp-image-99" title="layering" src="http://guptavikas.files.wordpress.com/2009/12/layering.png?w=371&#038;h=209" alt="" width="371" height="209" /></a>In a layered architecture, each layer is aware of the layers below it. In general, a layer at the lower level cannot make calls to the layer above it.</p>
<p><strong>Q:</strong> How will I represent concepts in a domain model?<br />
<strong> A:</strong> Most concepts in domain can be classified into</p>
<ul>
<li>Something which has an identity: <strong>Entities</strong>. Entities, which are essentially objects, identified by an identity, which does not change. The identity can be a surrogate key or a composite key.</li>
<li>Something which has an important meaning in larger picture but does not have an identity of it&#8217;s own: <strong>Value Objects(VOs)</strong>. VOs represent meaningful concepts and abstracts the details of those concepts but does not have their own entity. For example, a phone number is one such thing, which represent certain information, but does not make any sense if not associated with a person, place, etc.</li>
<li>Something which relate various concepts with each other: <strong>Cardinality</strong>. Cardinality represents relationship between various entities. DDD advocates to have minimum cardinality between entities.</li>
<li>Behavior common to various concepts: <strong>Services</strong>. Services are components which provides behavior which is not specific any particular entity. These services are different from the application service, in that, they provide services to the domain layer and not callable from the application layer.</li>
</ul>
<p>Apart from the above, DDD also introduces the concept of <strong>Aggregates</strong>, which are essentially small group of related objects. Aggregates have a common root and act as an entry point for outer world to the constituents of the aggregate. This helps in managing the complex web of associations in a domain model.</p>
<p>Also, since in many cases, entities will be persisted and again constructed back, DDD advocates the use of <strong>Factories</strong> and <strong>Repositories</strong>. Factories are generally used to create complex objects and Repositories are used to reconstruct an already persisted object. Here, Factories is not something which refers to only Factory pattern. We are free to choose from Factory, Builder or any other that we are aware of based on our judgement and something which conforms to <strong>UL</strong>.</p>
<p><strong>Q:</strong> How will I model behavior in domain model?<br />
<strong> A: </strong>In domain modelling, majorly, we have following kinds of behavior</p>
<ul>
<li>One which validates the domain model against certain rules: Specification Pattern. Specification pattern is employed to validate domain model against certain rule. For example, The logic to check whether the project is overdue can be put in the Project object, as in the following listing</li>
<p><pre class="brush: java;">
class Project {
  public boolean isOverdue() { … }
}
</pre></p>
<p>or, it can be abstracted as a Specification, as shown in the following code</p>
<p><pre class="brush: java;">
public interface ProjectSpecification {
  public boolean isSatisfiedBy(Project p);
}
public class ProjectIsOverdueSpecification implements ProjectSpecification {
  public boolean isSatisfiedBy(Project p) { … }
}
If (projectIsOverdueSpecification.isSatisfiedBy(theCurrentProject) { … }
</pre></p>
<li>One which is algorithmic in nature, like calculations, rules: Strategy/Policy Pattern. Strategy pattern is essentially employed to abstract out algorithms or business rules out of domain model. For example, if there is a business rule to allow Voyage overloading with 10% overloading. Then, without strategy pattern, code might look like<br />
<pre class="brush: java;">
 public int makeBooking(Cargo cargo, Voyage voyage) {
   double maxBooking = voyage.capacity() * 1.1;
   if ((voyage.bookedCargoSize() + cargo.size()) &amp;gt; maxBooking)
       return –1;
   int confirmation = orderConfirmationSequence.next();
   voyage.addCargo(cargo, confirmation);
   return confirmation;
}
        </pre></p>
<p>After applying Strategy pattern, the code might look like</p>
<p><pre class="brush: java;">
public int makeBooking(Cargo cargo, Voyage voyage) {
if (!overbookingPolicy.isAllowed(cargo, voyage)) return –1;
   int confirmation = orderConfirmationSequence.next();
   voyage.addCargo(cargo, confirmation);
   return confirmation;
}

public OverBookingPolicy {
public boolean isAllowed(Cargo cargo, Voyage voyage) {
   return (cargo.size() + voyage.bookedCargoSize()) &amp;lt;=
         (voyage.capacity() * 1.1);
}
}
        </pre></p>
<p>This helps in making code/model more expressive and flexible.</li>
</ul>
<p><strong>Q:</strong> How will I maintain the integrity of the model in a large team with complex domain?<br />
<strong> A: </strong>While working on large projects and large teams, it is difficult to express the intent of the domain with a single model. DDD advocates the use separate models to model the entire system. The patterns to handle the complexity of working with separate models and communicating between them are grouped as <strong>Strategic Design Patterns</strong> in DDD. Various strategic design patterns are their relationships are shown in the following diagram.</p>
<p><a href="http://guptavikas.files.wordpress.com/2009/12/strategic_design1.png"><img class="aligncenter size-full wp-image-124" title="strategic_design1" src="http://guptavikas.files.wordpress.com/2009/12/strategic_design1.png?w=376&#038;h=255" alt="" width="376" height="255" /></a></p>
<ul>
<li><strong>Bounded Context:</strong> DDD suggests to separate multiple domain models based on contexts. For example, in above figure domain model expressing project model is bound by project context, where as, billing model is bound by billing context. Contexts are generally created based on team structure and domain concepts.</li>
<li><strong>Context Maps:</strong> Different models in an application cannot work in isolation. There will be some data sharing among them. DDD provides some patterns based on experience. Theses pattens have specific applicability which are explained below.
<ul>
<li><strong>Shared Kernel:</strong> In this pattern, another domain model is created which models the shared data. For example, in the above example, shared data can be Customer and that would be part of Shared Kernel.</li>
<li><strong>Customer/Supplier:</strong> This pattern is applied when one context has dependency on another pattern. In this scenario, customers models can discuss their concerns with suppliers and raise their concerns and get the supplier model modified.</li>
<li><strong>Conformist:</strong> This pattern is similar to above pattern but customer model has no control over supplier model and customers are forced to deal with whatever suppliers dish out.</li>
<li><strong>Anti Corruption(AC) Layer: </strong>When the supplier model is third party and legacy code, there is high probability that the legacy code is developed not using domain modelling techniques. There might be chance of theses bad practices to creep into your own domain model. To insulate your domain model, DDD advocates the use of an AC layer, which is essentially a collection of services and adapters which translate the communication between the two models.</li>
<li><strong>Separate Ways:</strong> When the cost of integration between various model becomes overwhelming, we can decide not to integrate them at all. Instead, we can decide to break the application into smaller application which have little or nothing in common from modeling perspective.</li>
</ul>
</li>
</ul>
<p><strong>Q:</strong> How do I learn more about DDD?<br />
<strong> A:</strong> To get started with DDD, I recommend following approach</p>
<ol>
<li>Download <a href="http://www.infoq.com/minibooks/domain-driven-design-quickly">Domain Driven Design Quickly</a>, a brief and concise guide about DDD from InfoQ to get started.</li>
<li>Go through, <a href="http://www.amazon.com/Domain-Driven-Design-Tackling-Complexity-Software/dp/0321125215">Domain-Driven Design: Tackling Complexity in the Heart of Software</a> by Eric Evans.</li>
<li>You can also join <a href="http://groups.yahoo.com/phrase/domain-driven-design">Domain driven design group on Yahoo</a> to get connected with the latest in DDD.</li>
</ol>
<p><strong>Conclusion</strong><br />
<strong><span style="font-weight:normal;">In this blog, we discussed about what is DDD and looked at the various pattens suggested by DDD. DDD is not only object orientation done right but also understanding the domain of the application. DDD does not lay down any rules and only suggests to do certain things, which have worked on various projects. Any developer can benefit from it because it is merely a thought process which has evolved based on experience and not is not a figment of anyone&#8217;s imagination. DDD, along with </span><span style="font-weight:normal;">Agile</span><span style="font-weight:normal;"> practices like </span><span style="font-weight:normal;">TDD, Continuous Integration and Refactoring</span><span style="font-weight:normal;">, is a potent weapon in any designer&#8217;s armor.</span></strong></p>
<p>As promising it may be, DDD&#8217;s applicability has major challenges. Based on my experience in IT industry, I have summarized majority of them below:</p>
<ul>
<li>Poor quality of requirements: As already discussed in the blog, most projects have a translation layer which translates the requirements between business and technical people. Some may call them Business Analysts, whereas some call them Product Owner. So, quality of communication, and hence the requirements, depend upon this translation layer. On top of that, if this translation layer is bureaucratic, they would not like developers to work directly with the business as it would dilute their role in the project. So, apart from skills, DDD requires people with right mindset at the top and the team.</li>
<li>Simple Domain: The application/domain may be simple enough to yield any significant ROI of using DDD. The effect of DDD might be visible once the project becomes complex.</li>
<li>Motivation: DDD is all about making pragmatic decisions and it requires a lot of skill, but more importantly, a lot of motivation to make those decisions.</li>
</ul>
<p>In summary, DDD is a promising concept, which is gaining momentum in recent years. Although, it may not be applicable to every project directly, but learning these principles would certainly enhance design skills of a developer.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/guptavikas.wordpress.com/73/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/guptavikas.wordpress.com/73/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/guptavikas.wordpress.com/73/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/guptavikas.wordpress.com/73/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/guptavikas.wordpress.com/73/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/guptavikas.wordpress.com/73/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/guptavikas.wordpress.com/73/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/guptavikas.wordpress.com/73/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/guptavikas.wordpress.com/73/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/guptavikas.wordpress.com/73/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/guptavikas.wordpress.com/73/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/guptavikas.wordpress.com/73/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/guptavikas.wordpress.com/73/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/guptavikas.wordpress.com/73/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=guptavikas.wordpress.com&amp;blog=7715205&amp;post=73&amp;subd=guptavikas&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://guptavikas.wordpress.com/2009/12/01/domain-driven-design-an-introduction/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/58747853422550c061ac41ab764504d2?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">hivikas</media:title>
		</media:content>

		<media:content url="http://guptavikas.files.wordpress.com/2009/12/picture_1000_words.jpg?w=300" medium="image">
			<media:title type="html">picture_1000_words</media:title>
		</media:content>

		<media:content url="http://guptavikas.files.wordpress.com/2009/12/layering.png" medium="image">
			<media:title type="html">layering</media:title>
		</media:content>

		<media:content url="http://guptavikas.files.wordpress.com/2009/12/strategic_design1.png" medium="image">
			<media:title type="html">strategic_design1</media:title>
		</media:content>
	</item>
		<item>
		<title>Organizing Domain Logic</title>
		<link>http://guptavikas.wordpress.com/2009/11/24/organizing-domain-logic/</link>
		<comments>http://guptavikas.wordpress.com/2009/11/24/organizing-domain-logic/#comments</comments>
		<pubDate>Tue, 24 Nov 2009 17:07:48 +0000</pubDate>
		<dc:creator>Vikas Gupta</dc:creator>
				<category><![CDATA[DDD]]></category>
		<category><![CDATA[Design Patterns]]></category>
		<category><![CDATA[EA Patterns]]></category>
		<category><![CDATA[design]]></category>
		<category><![CDATA[Domain Driven Design]]></category>
		<category><![CDATA[enterprise design patterns]]></category>

		<guid isPermaLink="false">http://guptavikas.wordpress.com/?p=35</guid>
		<description><![CDATA[Introduction Most enterprise applications use Layering as the primary technique to break the complexity of the software projects. Layering involves breaking down the applications in various layers where each layer lie above the other and provide services to the higher layer. Layering provides following benefits You can understand about a layer without knowing about other [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=guptavikas.wordpress.com&amp;blog=7715205&amp;post=35&amp;subd=guptavikas&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p><strong>Introduction</strong></p>
<p>Most enterprise applications use Layering as the primary technique to break the complexity of the software projects. Layering involves breaking down the applications in various layers where each layer lie above the other and provide services to the higher layer. Layering provides following benefits</p>
<ul>
<li>You can understand about a layer without knowing about other layers. For example, if you know how <a href="http://en.wikipedia.org/wiki/Transmission_Control_Protocol">TCP</a> works you can create your own <a href="http://en.wikipedia.org/wiki/File_Transfer_Protocol">FTP</a> service without actually knowing about the internals of the ethernet.</li>
<li>It is easy to substitute the layers with alternative implementation. For example, if DAO layer is designed properly, if should be easy to change the ORM solution from <a href="https://www.hibernate.org/">Hibernate</a> to <a href="http://ibatis.apache.org/">iBatis</a> easily.</li>
<li>Layering also helps in standardization and extensibility.</li>
</ul>
<p>But the downsides of layering applications include cascading changes, performance overhead of converting data from one representation into another and it is not often easy to decide the later of a particular component. Considering the benefits of layering and it&#8217;s applicability to almost any sort of computer application, it is used widely and successfully.</p>
<p>Three primary layers of an enterprise application can broadly be categorized into</p>
<ol>
<li>Presentation Layer: Information display, HTTP requests, command line invocations, batch API, etc.</li>
<li>Domain Layer: Here lies the &#8220;Heart of the software&#8221;</li>
<li>Datasource Layer: Provides access to external resources like databases, messaging, mail server, etc.</li>
</ol>
<p>In this blog, we will discuss various patterns of organizing domain logic and specific pros and cons of each. We will also discuss how these approaches compare with each other.<br />
<span id="more-35"></span><br />
<strong>Domain Login Patterns</strong><br />
In his book, <a href="http://www.amazon.com/Patterns-Enterprise-Application-Architecture-Martin/dp/0321127420">PoEEA</a>, <a href="http://martinfowler.com/">Martin Fowler</a> has classified domain logic patterns into three primary patterns: Transaction Script, Domain Model and Table Module. He also discussed introducing an additional layer, Service Layer, which is useful in providing horizontal services. Let&#8217;s look at each of these in detail.</p>
<p><strong>Transaction Script (TS)</strong><br />
Transaction script is essentially a procedure that takes input from the presentation, processes it with validations and calculations, stores data in the database, send emails, etc. It may also fetch the data and send to the UI. It&#8217;s more like coding a C program in Java. Typically, in transaction script method of organizing domain logic, the code is segregated into various services and each service has methods that perform a particular business functionality. A method of a transaction service might look like this</p>
<p><pre class="brush: java;">void tsmethod(params) {
   // get data
   // process data
   if () {
   } else if {
   } else {
   }
   // insert/update/delete data
   //send email
}</pre></p>
<p>As you can see from the above, most of the of the above code is procedural. Here, the services act on the entities. A typical example would be an interaction between session bean and entity bean. Another similar pattern not mentioned in the PoEEA is <a href="http://martinfowler.com/bliki/AnemicDomainModel.html">Anemic Domain Model</a> (ADM) which works on the same principle where domain objects have attributes and relationships but does not have behaviour. Behaviour is provided by the services. The different between TS and ADM is that in former we do not have domain objects but rather have something which Fowler describe as <a href="http://martinfowler.com/eaaCatalog/tableDataGateway.html">Table Data Gateway</a>, which essentially is a wrapper for SQL queries.</p>
<p><strong>Domain Model (DM)</strong><br />
In domain model approach, both behaviour and data are encapsulated inside the domain objects. Domain model looks different from the database design and utilizes inheritance, strategies, and other design patterns to create complex webs of small interconnected objects. A typical domain model code might look like</p>
<p><pre class="brush: java;">class Bar {
  private BarAdmissionPolicy = new BarAdmissionPolicy();
  public void admit(Person person) {
     if (BarAdmissionPolicy.isAllowed(person)) {
         this.add(person)
     }
  }
}
public class BarAdmissionPolicy {
   public boolean isAllowed(Person person) {
     if (person.age &amp;gt; 18) {
        return true;
     }
     return false;
   }
}</pre></p>
<p>A well designed domain model provides an abstraction of the domain logic. It encapsulates complex business logic as interactions between domain objects.</p>
<p><strong>Table Module (TM)</strong><br />
It is essentially a singleton instance that handles the business logic for all the rows in a database table. There is no concept of identity in a Table Module. It is designed to operate on entire table data. A typical domain might look like</p>
<p><pre class="brush: java;">class Product {
 void insert(name, type, etc) {
 }
 void insertAll(List) {
 }
 void calculateProductCost(List productIds) {
 }
}</pre></p>
<p>As you can see, a table module encapsulates the data and behaviour of the entire table. It is most commonly used in places where UI widgets are data-aware like Oracle Forms or .Net environment which has Visual Studio, which provides tools like <a href="http://en.wikipedia.org/wiki/Recordset">RecordSet</a>.</p>
<p><strong>Service Layer (SL)</strong><br />
A Service Layer defines an application&#8217;s boundary and its set of available operations from the perspective of interfacing client layers. It encapsulates the application&#8217;s business logic, controlling transactions, applying security and coordinating responses in the implementation of its operations. Service Layer can be thick or thin depending upon whether you are using transaction scripts or domain model.</p>
<p>Now, we have understanding of the various domain logic patterns, let&#8217;s discuss how they compare with each other.</p>
<p><strong>Comparison</strong><br />
Essentially, if you are using one of DM, TM or ADM pattern, the domain layer can be split into two layers: SL + DM/TM/ADM. SL is essential in providing horizontal services like security, transactions, etc. With TS in practice, it is difficult to identify the difference between SL and TS since TS can double up as a SL also.</p>
<p>Since, TM emphasizes one class per table, there are issues in implementing OO concepts while inheritance. There are no direct relationships between objects. For example, if you want to get a List of Products and Categories separately then it is easy to define where to put the code, but it is not clear where to put the code if you need a RecordSet which contains both Products and Categories.</p>
<p>TS is more like a service class which makes implementing domain logic difficult when the complexity of the application increases, but works well for simple applications.</p>
<p>There is a tough competition between ADM and DM. DM is essentially a Rich Domain Model (RDM). Common things between them includes data and relationships. But things specific to RDM is behaviour of the domain model. There has been a heated debate between designers to prove the dominance of one over the other. Suprisingly, the wiki page for ADM lists why should be avoid them. I reiterate them here</p>
<ul>
<li> Logic cannot be implemented in a truly object-oriented way unless wrappers are used, which hide the anemic data structure.</li>
<li> Violation of the principals information hiding and encapsulation.</li>
<li> Necessitates a separate business layer to contain the logic otherwise located in a domain model. It also means that domain model&#8217;s objects cannot guarantee their correctness at any moment, because their validation and mutation logic is placed somewhere outside (most likely in multiple places).</li>
<li> Necessitates a global access to internals of shared business entities increasing coupling and fragility.</li>
<li> Facilitates code duplication among transactional scripts and similar use cases, reduces code reuse.</li>
<li> Necessitates a service layer when sharing domain logic across differing consumers of an object model.</li>
<li> Makes a model less expressive and harder to understand.</li>
</ul>
<p>The difference between ADM and RDM is the focus of control. In the former, the services has the control and in the later domain objects controls the services. It is shown in the following diagram.<br />
<a href="http://guptavikas.files.wordpress.com/2009/11/domain-modelling1.png"><img class="aligncenter size-medium wp-image-42" title="domain-modelling" src="http://guptavikas.files.wordpress.com/2009/11/domain-modelling1.png?w=573&#038;h=360" alt="" width="573" height="360" /></a><br />
Another benefit that differentiates ADM and RDM is that in ADM a developer has to understand two layers, service layer and domain layer but in RDM once you get the grasp of domain model, which is essentially a model of the domain logic, you get a grasp of the business and can work productively to enhance the software. RDM also makes code cohesive.</p>
<p>Experts also advocate to consider maintainability while deciding to choose between various approaches. In his book PoEEA, Fowler explains this with the help of a diagram which is shown below<br />
<a href="http://guptavikas.files.wordpress.com/2009/11/maintainability.png"><img class="aligncenter size-medium wp-image-42" title="maintainability" src="http://guptavikas.files.wordpress.com/2009/11/maintainability.png?w=530&#038;h=373" alt="" width="530" height="373" /></a><br />
The source of the above diagram is not known. But, according to this diagram, it takes time to pick up speed with the domain model. Of course, with skilled developers the initial startup time reduces. But, as the complexity of the application increases, it becomes increasingly difficult to maintain the application if it is coded with TS pattern. TM pattern delays the cutoff point where DM takes over, but TM is advocated for .Net environments as Visual Studio provides tools which work well with TM.</p>
<p><strong>Conclusion</strong><br />
In this blog, we discussed various patterns for organizing domain logic in enterprise applications. Clearly, there is no silver bullet which fits all scenarios. Since, we work with object-oriented programming languages, it is advisable to work with approaches like DM to encapsulate business logic. Also, it makes working with complex applications easier as the complexity of the application increases. DM helps in abstracting a model of the real world domain logic in the code which once understood can make working on the applications more productive and fruitful. For simple applications, TS/ADM meets the requirements.</p>
<p>But, how to decide whether the application is complex or easy. Most of the metrics talk about the complexity once the software has been coded by analyzing if-else statements, cyclomatic complexity, etc. But, here, we are talking about predicting complexity, and there is no known metric which can objectively tell that. However, it can be subjectively predicted by knowledge of the domain of the software, which is gained by experience.</p>
<p>Another and most important factor which must be taken into consideration is maintainability. Although it cannot be quantitatively measured, but since we work in to the objective oriented world, DM seems to have an edge over other approaches and it employs inheritance, polymorphism, etc to encapsulate the domain logic.</p>
<p>As a final word, all the above domain model patterns are not mutually exclusive and an understanding of all of above might help us decide an approach for developing a particular software.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/guptavikas.wordpress.com/35/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/guptavikas.wordpress.com/35/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/guptavikas.wordpress.com/35/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/guptavikas.wordpress.com/35/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/guptavikas.wordpress.com/35/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/guptavikas.wordpress.com/35/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/guptavikas.wordpress.com/35/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/guptavikas.wordpress.com/35/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/guptavikas.wordpress.com/35/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/guptavikas.wordpress.com/35/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/guptavikas.wordpress.com/35/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/guptavikas.wordpress.com/35/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/guptavikas.wordpress.com/35/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/guptavikas.wordpress.com/35/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=guptavikas.wordpress.com&amp;blog=7715205&amp;post=35&amp;subd=guptavikas&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://guptavikas.wordpress.com/2009/11/24/organizing-domain-logic/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/58747853422550c061ac41ab764504d2?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">hivikas</media:title>
		</media:content>

		<media:content url="http://guptavikas.files.wordpress.com/2009/11/domain-modelling1.png?w=300" medium="image">
			<media:title type="html">domain-modelling</media:title>
		</media:content>

		<media:content url="http://guptavikas.files.wordpress.com/2009/11/maintainability.png?w=300" medium="image">
			<media:title type="html">maintainability</media:title>
		</media:content>
	</item>
		<item>
		<title>Captcha usage pattern to prevent bot attack</title>
		<link>http://guptavikas.wordpress.com/2009/11/21/how-to-make-client-ip-behind-a-proxy/</link>
		<comments>http://guptavikas.wordpress.com/2009/11/21/how-to-make-client-ip-behind-a-proxy/#comments</comments>
		<pubDate>Sat, 21 Nov 2009 15:13:37 +0000</pubDate>
		<dc:creator>Vikas Gupta</dc:creator>
				<category><![CDATA[Site Improvement]]></category>
		<category><![CDATA[Usability]]></category>
		<category><![CDATA[web security]]></category>
		<category><![CDATA[Website Improvement]]></category>

		<guid isPermaLink="false">http://guptavikas.wordpress.com/?p=21</guid>
		<description><![CDATA[In one of the projects, we had﻿ a requirement of preventing bot attacks without captcha. After hitting the wall on freely available solutions, I thought of staying with captcha, but in a different way. To devise a solution, I thought that most users would not register account on the same website again at least with [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=guptavikas.wordpress.com&amp;blog=7715205&amp;post=21&amp;subd=guptavikas&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>In one of the projects, we had﻿ a requirement of preventing bot attacks without <a title="catcha" href="http://en.wikipedia.org/wiki/CAPTCHA">captcha</a>. After hitting the wall on freely available solutions, I thought of staying with captcha, but in a different way.</p>
<p>To devise a solution, I thought that most users would not register account on the same website again at least with in a day, may be a year also. So, using this fact, the proposed solution was to display the captcha only when the user is registering again on the website. In this way, we could avoid irritating the user by showing the captcha, but if needed, we can again activate captcha for second or subsequent captcha.</p>
<p>The proposed solution brought an interesting challenge. How would we determine whether the request is coming from the same machine? HttpServletRequest.getRemoteAddr() gives you the client local IP. But, if you are behind <a title="NAT" href="http://www.howstuffworks.com/nat.htm">NAT</a>, you might not get different IPs for different machine.</p>
<p>In order to resolve the above mentioned issue, we can use ﻿﻿﻿﻿﻿﻿X-FORWARDED-FOR, which is a HTTP header that is inserted by proxies to identify the IP address of the client. It can also be added to requests if application servers are proxied by proxy servers. In this case, the request IP address is always a local address and the client IP address must be extracted from the request. Since proxies can be chained – for example if the client’s request is already made through a proxy – the X-FORWARDED-FOR header can contain more than one IP address, separated by commas. In this case, the first one should be used.</p>
<p>The solution is still not full proof, because headers can be tampered easily. To rescue comes a module of Apache http server, which is <a title="mod_remoteip" href="http://httpd.apache.org/docs/trunk/mod/mod_remoteip.html">mod_remoteip</a>,<br />
Thanks to this, request.getRemoteAddr(), request.getRemoteHost(), request.isSecure(), request.getScheme() and request.getServerPort() will expose the values transmitted by X-Forwarded-For and X-Forwarded-Proto rather than the values of the preceding proxy / load balancer.</p>
<p>The above mentioned Apache module works on an open source project, ﻿<a title="RemoteIpValve" href="http://code.google.com/p/xebia-france/wiki/RemoteIpValve">RemoteIpValve</a>, and, <a title="XForwardedFilter" href="http://code.google.com/p/xebia-france/wiki/XForwardedFilter">﻿﻿﻿XForwardedFilter</a>. The RemoteIpValve and the XForwardedFilter have been integrated in the Tomcat Project. The RemoteIpValve will be available in the forthcoming Tomcat 6.0.21 version, whereas, XForwardedFilter has been renamed RemoteIpFilter and will be integrated in Tomcat 7.</p>
<p>Thanks to all those who worked on RemoteIpValve and RemoteIpFilter.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/guptavikas.wordpress.com/21/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/guptavikas.wordpress.com/21/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/guptavikas.wordpress.com/21/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/guptavikas.wordpress.com/21/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/guptavikas.wordpress.com/21/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/guptavikas.wordpress.com/21/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/guptavikas.wordpress.com/21/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/guptavikas.wordpress.com/21/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/guptavikas.wordpress.com/21/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/guptavikas.wordpress.com/21/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/guptavikas.wordpress.com/21/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/guptavikas.wordpress.com/21/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/guptavikas.wordpress.com/21/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/guptavikas.wordpress.com/21/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=guptavikas.wordpress.com&amp;blog=7715205&amp;post=21&amp;subd=guptavikas&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://guptavikas.wordpress.com/2009/11/21/how-to-make-client-ip-behind-a-proxy/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/58747853422550c061ac41ab764504d2?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">hivikas</media:title>
		</media:content>
	</item>
		<item>
		<title>Inter Portlet Coordination with JSR 286</title>
		<link>http://guptavikas.wordpress.com/2009/09/09/inter-portlet-coordination-with-jsr-286/</link>
		<comments>http://guptavikas.wordpress.com/2009/09/09/inter-portlet-coordination-with-jsr-286/#comments</comments>
		<pubDate>Wed, 09 Sep 2009 15:34:11 +0000</pubDate>
		<dc:creator>Vikas Gupta</dc:creator>
				<category><![CDATA[Portal]]></category>
		<category><![CDATA[Websphere]]></category>
		<category><![CDATA[JSR 286]]></category>

		<guid isPermaLink="false">http://guptavikas.wordpress.com/?p=3</guid>
		<description><![CDATA[Coordination between portlets is a very common requirement. An example of information sharing between portlets can be a weather portlet displaying the weather information of a city and a map portlet displaying the location of the city. Since, both the portlets would be using the same zip code for a user, there should be mechanism [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=guptavikas.wordpress.com&amp;blog=7715205&amp;post=3&amp;subd=guptavikas&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p style="text-align:left;">Coordination between portlets is a very common requirement. An example of information sharing between portlets can be a weather portlet displaying the weather information of a city and a map portlet displaying the location of the city. Since, both the portlets would be using the same zip code for a user, there should be mechanism provided by the portlal containers to allow portlets to share the zip code.</p>
<p>Prior to JSR 286, the support for inter portlet communication was rather minimal and information sharing between different portlets was accompalished primarily using application scoped session objects or vendor specific APIs. Both of above methods were rather problematic as in the former maintaining the uniqueness of the session attribute over a complex aaplication was a concern and in the later portability of the portlet was hampered.  In order to provide coordination between portlets the Java Portlet Specification v2.0 (JSR 286) introduces the following mechanisms:</p>
<ol>
<li>public render parameters in order to share render state between portlets.</li>
<li>portlet events that a portlet can receive and send.</li>
</ol>
<p>Let&#8217;s have a look how to use the above features.<br />
<span id="more-3"></span><br />
<strong>Public Render Parameters</strong></p>
<p>In JSR 168, the render parameters propagated by one portlet were only available in the render method of the same portlet. This is explained in the following figure.<br />
<img class="alignnone size-full wp-image-1140" title="jsr-168-render" src="http://blog.xebia.com/wp-content/uploads/2009/04/dia1.png" alt="jsr-168-render" width="604" height="399" /></p>
<p>In JSR 286, the render parameters propagated by one portlet can be made available to the render methods of other portlets. This is explained in the following figure.<br />
<img class="alignnone size-full wp-image-1141" title="jsr-286-render" src="http://blog.xebia.com/wp-content/uploads/2009/04/dia2.png" alt="jsr-286-render" width="604" height="398" /></p>
<p>In order to allow coordination of render parameters with other portlets, within the same portlet application or across portlet applications, in JSR 286 portlets, the portlet can declare public render parameters in its deployment descriptor using the public-render-parameter element in the portlet application section.  In the portlet section each portlet can specify the public render parameters it would like to share via the supported-public-render-parameter element. The supported public-ender-parameter element must reference the identifier of a public render parameter defined in the portlet application section in a public-render-parameter element. The portlet should use the defined public render parameter identifier in its code in order to access the public render parameter.</p>
<p>Let&#8217;s see how it works..<br />
Consider the following example..</p>
<p>1. Set the public render parameters at the portlet application level.<br />
<pre class="brush: xml;">   
&amp;lt;public-render-parameter&amp;gt;
    &amp;lt;identifier&amp;gt;id1&amp;lt;/identifier&amp;gt;
    &amp;lt;qname xmlns:x=&amp;quot;http://sun.com/params&amp;quot;&amp;gt;x:param1&amp;lt;/qname&amp;gt;
&amp;lt;/public-render-parameter&amp;gt;
&amp;lt;public-render-parameter&amp;gt;
    &amp;lt;identifier&amp;gt;id2&amp;lt;/identifier&amp;gt;
    &amp;lt;qname xmlns:x=&amp;quot;http://sun.com/params&amp;quot;&amp;gt;x:param2&amp;lt;/qname&amp;gt;
 &amp;lt;/public-render-parameter&amp;gt;
</pre><br />
2. Specify the render parameter the portlet would like to share in the portlet section.<br />
<pre class="brush: xml;">&amp;lt;portlet&amp;gt;
&amp;lt;portlet-name&amp;gt;PortletA&amp;lt;/portlet-name&amp;gt;
  &amp;lt;supported-public-render-parameter&amp;gt;id1&amp;lt;/supported-public-render-parameter&amp;gt;
  &amp;lt;supported-public-render-parameter&amp;gt;id2&amp;lt;/supported-public-render-parameter&amp;gt;
&amp;lt;portlet&amp;gt;
&amp;lt;portlet&amp;gt;
&amp;lt;portlet-name&amp;gt;PortletB&amp;lt;/portlet-name&amp;gt;
  &amp;lt;supported-public-render-parameter&amp;gt;id1&amp;lt;/supported-public-render-parameter&amp;gt;
&amp;lt;/portlet&amp;gt;
&amp;lt;portlet&amp;gt;
&amp;lt;portlet-name&amp;gt;PortletC&amp;lt;/portlet-name&amp;gt;
  &amp;lt;supported-public-render-parameter&amp;gt;id2&amp;lt;/supported-public-render-parameter&amp;gt;
&amp;lt;portlet&amp;gt;</pre><br />
The public render paramters declared above are processed as explained in the figure below.<br />
<img class="alignnone size-full wp-image-1146" title="parameter-sending" src="http://blog.xebia.com/wp-content/uploads/2009/04/dia4.png" alt="parameter-sending" width="606" height="310" /><br />
Now, since the public render parameters are encoded in the URL, the values that can be shared between portlets are restricted to String and String arrays. Since, public render parameters are available only in the render method, the information shared by the portlets should be used for rendering the view rather than for processing the shared information.</p>
<p><strong>Portlet Events</strong><br />
Portlet events could be generated as a result of a user interaction with other portlets. The portlet event model is a loosely coupled, brokered model that allows creating portlets as stand-alone portlets that can be wired together with other portlets at runtime. Portlet programmers should therefore not make any specific assumptions about the environment of portlets they are running together with. The means of wiring different portlets together is portal implementation specific. An example where a portlet may want to offer receiving events is for state changes triggered by simple user interactions, e.g. adding an item to a shopping cart. By offering this as an event to other portlets these can trigger adding items to the shopping cart based on the user interactions happing inside these portlets.</p>
<p><em>EventPortlet Interface</em><br />
In order to receive events the portlet must implement the <em>EventPortlet</em> interface in he <em>javax.portlet</em> package. The portlet container will call the <em>processEvent</em> method for each event targeted to the portlet with an <em>EventRequest</em> and <em>EventResponse</em> object.</p>
<p>Events are targeted by the portal / portlet container to a specific portlet window in the current client request.  Events are a lifecycle operation that occurs before the rendering phase. The portlet may issue events via the setEvent method during the action processing which will be processed by the portlet container after the action processing has finished. As a result of issuing an event the portlet may optionally receive events from other portlets or container events. A portlet that is not target of a user action may optionally receive container events, e.g. a portlet mode changed event, or events from other portlets, e.g. an item was added to the shopping cart event.</p>
<p>The JSR 286 event processing is explained in the following figure.<br />
<img class="alignnone size-full wp-image-1142" title="jsr-286-event-processing" src="http://blog.xebia.com/wp-content/uploads/2009/04/dia32.png" alt="jsr-286-event-processing" width="659" height="399" /></p>
<p>To create portlets that use the eventing feature, follow these steps<br />
1. Declare the events in the portlet.xml<br />
(i) Set the event definition at the portlet application level. This specifies the event name and the object type.</p>
<div class="code panel">
<div class="codeContent panelContent">
<pre class="brush: xml;">&amp;lt;portlet-app ...&amp;gt;
&amp;lt;portlet&amp;gt;
 . . .
 . . .
 &amp;lt;/portlet&amp;gt;
 
 &amp;lt;event-definition&amp;gt;
   &amp;lt;qname xmlns:x=&amp;quot;http:xebia.com/address&amp;quot;&amp;gt;x:Address&amp;lt;/qname&amp;gt;
   &amp;lt;value-type&amp;gt;com.xebia.Address&amp;lt;/value-type&amp;gt;
 &amp;lt;/event-definition&amp;gt;
&amp;lt;/portlet-app&amp;gt;
</pre><br />
<pre class="brush: java;">  @XmlRootElement
  public class Address implements Serializable {
      public Address() {
      }
      private String street;
      private String city;
      private String country;

      //getters and setters
   }</pre><br />
Note: The object must be serializable and must be instrumented with valid JAXB annotation. This might be required to ensure that portlets can send events to and receive events from remote portlets. However, in case of local communication, portal containers, for optimization purposes, might not serialize event payload.</p>
</div>
</div>
<p>(ii) In the portlet section, specify the event name defined above for those portlets that want to publish this event.<br />
<pre class="brush: xml;">&amp;lt;portlet&amp;gt;
  &amp;lt;description&amp;gt;ContinentPortlet&amp;lt;/description&amp;gt;
&amp;lt;portlet-name&amp;gt;ContinentPortlet&amp;lt;/portlet-name&amp;gt;
    .................
   &amp;lt;supported-publishing-event&amp;gt;
     &amp;lt;qname xmlns:x=&amp;quot;http:xebia.com/address&amp;quot;&amp;gt;x:Address&amp;lt;/qname&amp;gt;
   &amp;lt;/supported-publishing-event&amp;gt;
&amp;lt;/portlet&amp;gt;</pre><br />
(iii) In the portlet section, specify the event name defined above for those portlets that want to process this event.<br />
<pre class="brush: xml;">&amp;lt;portlet&amp;gt;
  &amp;lt;description&amp;gt;ContinentMapPortlet&amp;lt;/description&amp;gt;
&amp;lt;portlet-name&amp;gt;ContinentMapPortlet&amp;lt;/portlet-name&amp;gt;
  &amp;lt;supported-processing-event&amp;gt;
    &amp;lt;qname xmlns:x=&amp;quot;http:xebia.com/address&amp;quot;&amp;gt;x:Address&amp;lt;/qname&amp;gt;
  &amp;lt;/supported-processing-event&amp;gt;
&amp;lt;/portlet&amp;gt;
&amp;lt;portlet&amp;gt;
  &amp;lt;description&amp;gt;ContinentInfoPortlet&amp;lt;/description&amp;gt;
&amp;lt;portlet-name&amp;gt;ContinentInfoPortlet&amp;lt;/portlet-name&amp;gt;
  &amp;lt;supported-processing-event&amp;gt;
    &amp;lt;qname xmlns:x=&amp;quot;http:sun.com/events&amp;quot;&amp;gt;x:Address&amp;lt;/qname&amp;gt;
  &amp;lt;/supported-processing-event&amp;gt;
&amp;lt;/portlet&amp;gt;</pre><br />
2. Issue an event in the portlet that was specified as supported-publishing-event in the portlet.<br />
<pre class="brush: java;">public class ContinentPortlet extends GenericPortlet {
   public void processAction(ActionRequest request, ActionResponse response)
   throws PortletException,IOException {
	QName qname = new QName(&amp;quot;http:xebia.com/address&amp;quot; , &amp;quot;Address&amp;quot;);
        Address add = new Address();
        //set values in address
        response.setEvent(qname, add);
    }
}</pre><br />
3. Process the event in the portlet that has specified as supported-processing-event in the portlet<br />
<pre class="brush: java;">public class ContinentInfoPortlet extends GenericPortlet {
  public void processEvent(EventRequest request, EventResponse response) {
    Event event = request.getEvent();
    if(event.getName().equals(&amp;quot;Address&amp;quot;)){
      Address payload = (Address )event.getValue();
      //process payload here
    }
  }
}</pre><br />
Portlet events provide more sphisticated way of exchanging information between portlets as compared to public render paramters as they can be used to share objects rather than simple string values. They also provide an additional callback method, processEvent, which can be used to process the event information before the view for the portlet in rendered. Also, portlet events share the information in a type safe manner as the event payload id bound to a type which we declare in the portlet.xml. Also, portlet specification does not standardizes how to wire the portlets, so, portal containers are free to choose convenient mechanisms to wire the portlets together.</p>
<p>However, as per the portlet specification, portlet events are not as reliable means of communication as is JMS, since the specification does not mandate the portal containers to persist the portlet event data. So, in case of server failures, the portlet events can be lost.</p>
<p><strong>Summary</strong><br />
In this blog, we discussed about the JSR 286 inter portlet communication features. First, we discussed about the public render parameters and how it works. Secondly, we discussed about the portlet events, and it&#8217;s working. So, how to decide when to choose either of the above two portlets. I would use the following principle</p>
<blockquote><p>In case, the receiver portlet, does not need to do any processing/businees logic, it is advisable to use public render parameters as they avoid the overhead for portlets event creation and wiring the portlets together, which is required in case of portlet events. As already discussed, wiring portlets together is portal container specific and is an addtional overhead. However, to allow receiver portlets to process the shared information and sending type safe values, we need to use portlet events.</p></blockquote>
<p>Overall, JSR 286 portlet coordination features make complex portal applications modular and manageable.</p>
<p>Note: The source code for the portlet event can be downloaded from <a href="http://www.4shared.com/file/157023697/6d872a6f/RAD75PortletEvent.html">here</a>.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/guptavikas.wordpress.com/3/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/guptavikas.wordpress.com/3/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/guptavikas.wordpress.com/3/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/guptavikas.wordpress.com/3/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/guptavikas.wordpress.com/3/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/guptavikas.wordpress.com/3/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/guptavikas.wordpress.com/3/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/guptavikas.wordpress.com/3/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/guptavikas.wordpress.com/3/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/guptavikas.wordpress.com/3/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/guptavikas.wordpress.com/3/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/guptavikas.wordpress.com/3/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/guptavikas.wordpress.com/3/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/guptavikas.wordpress.com/3/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=guptavikas.wordpress.com&amp;blog=7715205&amp;post=3&amp;subd=guptavikas&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://guptavikas.wordpress.com/2009/09/09/inter-portlet-coordination-with-jsr-286/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/58747853422550c061ac41ab764504d2?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">hivikas</media:title>
		</media:content>

		<media:content url="http://blog.xebia.com/wp-content/uploads/2009/04/dia1.png" medium="image">
			<media:title type="html">jsr-168-render</media:title>
		</media:content>

		<media:content url="http://blog.xebia.com/wp-content/uploads/2009/04/dia2.png" medium="image">
			<media:title type="html">jsr-286-render</media:title>
		</media:content>

		<media:content url="http://blog.xebia.com/wp-content/uploads/2009/04/dia4.png" medium="image">
			<media:title type="html">parameter-sending</media:title>
		</media:content>

		<media:content url="http://blog.xebia.com/wp-content/uploads/2009/04/dia32.png" medium="image">
			<media:title type="html">jsr-286-event-processing</media:title>
		</media:content>
	</item>
	</channel>
</rss>
