<?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/"
	>

<channel>
	<title>JTeam Blog &#187; Application Design</title>
	<atom:link href="http://blog.jteam.nl/tag/application-design/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.jteam.nl</link>
	<description>Keep updated on what we&#039;re doing!</description>
	<lastBuildDate>Fri, 23 Jul 2010 07:32:56 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0</generator>
		<item>
		<title>Rethinking architecture with CQRS</title>
		<link>http://blog.jteam.nl/2009/12/21/rethinking-architecture-with-cqrs/</link>
		<comments>http://blog.jteam.nl/2009/12/21/rethinking-architecture-with-cqrs/#comments</comments>
		<pubDate>Mon, 21 Dec 2009 11:07:13 +0000</pubDate>
		<dc:creator>Allard Buijze</dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[Application Design]]></category>
		<category><![CDATA[Architecture]]></category>
		<category><![CDATA[CQRS]]></category>
		<category><![CDATA[Domain Driven Design]]></category>

		<guid isPermaLink="false">http://blog.jteam.nl/?p=1580</guid>
		<description><![CDATA[Many applications use some form of persistent storage to store its state. However, important information about this state is lost: why is the state as it currently is. Furthermore, a single model is used to store information that is retrieved for many different purposes, often resulting in extremely complex and bog-slow SQL queries. Command Query [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://blog.jteam.nl/wp-content/uploads/2009/12/question_and_answer.png"><img style="margin: 5px 10px 0px 0px; display: inline; border-width: 0px;" title="question_and_answer" src="http://blog.jteam.nl/wp-content/uploads/2009/12/question_and_answer_thumb.png" border="0" alt="question_and_answer" width="64" height="64" align="left" /></a> Many applications use some form of persistent storage to store its state. However, important information about this state is lost: why is the state as it currently is. Furthermore, a single model is used to store information that is retrieved for many different purposes, often resulting in extremely complex and bog-slow SQL queries.</p>
<p>Command Query Responsibility Segregation (CQRS) is an architectural style that makes a clear distinction between commands that change the application state and queries that expose the application state.</p>
<p><span id="more-1580"></span></p>
<h2>Background</h2>
<p>My interest in CQRS was triggered when I saw Greg Young explain “<a href="http://www.infoq.com/interviews/greg-young-ddd" target="_blank">State Transitions in Domain-Driven Design</a>” on InfoQ. In this interview, Greg explains how he sees that application would benefit from using separate models for state validation and transition on one side and maintaining a view on the current state on the other.</p>
<p>One of the problems that Greg describes is the fact that a single model is often used for different purposes. It is nicely illustrated by the SQL query below. It shows how the model chosen in the application is not suited for the purpose of providing certain information (messages between users, in this case).</p>
<pre class="brush: java;">queryBuilder.append(
  &quot;m.*, &quot; +
  &quot;m.origin_participant_id as message_origin_participant_id, &quot; +
  &quot;po.first_name as message_origin_participant_first_name, &quot; +
  &quot;po.avatar as message_origin_participant_avatar, &quot; +
  &quot;po_ua.username as message_origin_participant_username, &quot; +
  &quot;CASE WHEN !isnull(po.fieldworker_project_id) THEN 'fieldworker' WHEN !isnull(po_ap.project_id) THEN 'fundraiser' ELSE 'player' END AS message_origin_participant_type, &quot; +
  &quot;po.city as message_origin_participant_city, &quot; +
  &quot;c.name as message_origin_participant_country, &quot; +
  &quot;pd.first_name as message_destination_participant_first_name, &quot; +
  &quot;pd.avatar as message_destination_participant_avatar, &quot; +
  &quot;pd_ua.username as message_destination_participant_username, &quot; +
  &quot;CASE WHEN !isnull(pd.fieldworker_project_id) THEN 'fieldworker' WHEN !isnull(pd_ap.project_id) THEN 'fundraiser' ELSE 'player' END AS message_destination_participant_type, &quot; +
  &quot;m.destination_participant_id as message_destination_participant_id &quot; +
  &quot;from internal_message m  &quot; +
  &quot;left join player po on m.origin_participant_id = po.id &quot; +
  &quot;left join (select player_id, project_id from ambassador_project where enabled = true group by player_id) po_ap on po_ap.player_id =  po.id &quot; +
  &quot;left join user_account po_ua on po.user_account_id = po_ua.id &quot; +
  &quot;left join country c on po.country_id = c.id &quot; +
  &quot;left join player pd on m.destination_participant_id = pd.id &quot; +
  &quot;left join (select player_id, project_id from ambassador_project where enabled = true group by player_id) pd_ap on pd_ap.player_id =  pd.id &quot; +
  &quot;inner join user_account pd_ua on pd.user_account_id = pd_ua.id &quot; +
  &quot;where m.destination_participant_id = ? &quot;
);
</pre>
<p>Wouldn’t it be a lot nice to have a query such as the one below instead?</p>
<pre class="brush: sql;">&lt;/pre&gt;
SELECT * FROM messages WHERE receiving_participant = ?
&lt;pre&gt;</pre>
<p>Achieving such queries is very easy, but doing so without making your model impossible to use for maintaining state integrity and guarding invariants is a lot harder. Well, unless you apply CQRS.</p>
<h2>Architecture</h2>
<p>The diagram below shows an overview of a typical CQRS architecture.</p>
<p><a href="http://blog.jteam.nl/wp-content/uploads/2009/12/cqrs_architecture.jpg"><img style="border-width: 0px; display: block; margin-left: auto; margin-right: auto;" title="cqrs_architecture" src="http://blog.jteam.nl/wp-content/uploads/2009/12/cqrs_architecture_thumb.jpg" border="0" alt="cqrs_architecture" width="404" height="281" /></a></p>
<p>When a command comes in, it will load an <a href="http://dddstepbystep.com/wikis/ddd/aggregate.aspx" target="_blank">aggregate</a> from the <a href="http://dddstepbystep.com/wikis/ddd/repository.aspx" target="_blank">repository</a> and execute certain operations on it. As a result of these operations, the aggregate produces events, which are picked up for storage by the repository and for dispatching by the event bus. The event bus will dispatch each event to all (interested) event handlers. Some of these event handlers will perform actions on other (related) aggregates, some others will update the database tables they manage.</p>
<p>Having handlers update the data in the database means that your tables do not have to be normalized anymore. Instead, CQRS allows you to optimize your tables for the way you want to query them. This makes the data layer processing your queries really simple, and maintainable.</p>
<p>Furthermore, since all state changes are initiated by events, these events become a reliable source for an audit trail. By storing these events, you have an audit trail that you can use to replay the entire application history. Instead of just seeing “current application state” only, you can see all the changes that have led to the current state, providing valuable information trying to find bugs or deal with customer complaints.</p>
<h2>Benefits</h2>
<p><strong>Matches the natural language used</strong></p>
<p>At first glance, such an architecture might look very complex and over-engineered. However, after taking the first implementation steps, it felt pretty natural. In fact, when you explain the behavior of an application, you use a style that fits CQRS quite nicely: “when an order is approved, we send a confirmation email to the customer”.</p>
<p><strong>Extensibility</strong></p>
<p>Imagine an order management application. With CQRS, you could have an “OrderApproved” event, which is caught by a database updating event handler as well as one that sends an email to the customer with order information. If you later on decide to store the order information in an accounting tool as well, all it takes is adding an event handler that does the accounting integration. And since you can reload historic events as well, you can even reconstruct historic information to put in the accounting table.</p>
<p><strong>Reliable audit trail</strong></p>
<p>As I said above [see section Architecture], the model that is used to process command will generate events. These events are the sole source of state changes for the domain classes. If you want to load an aggregate from persistent storage, it will actually load all the past events of that aggregate. This process is called Event Sourcing. When events become too numerous, you can combine a number of historic events into a single snapshot event. The events that have been combined can then be archived for auditing purposes.</p>
<p>Event Sourcing turns your event storage into an extremely reliable audit trail. The events do no only show what happened and when, but they will also reveal the intention a user had. Not only is it an audit trail that will never move out-of-sync with your application, you can use the audit trail to actually replay all actions in the application. Events are not just a notification of state change, they are also the source of state change.</p>
<p><strong>Transparent distributed processing</strong></p>
<p>When using events as the trigger for state changes, you can easily distribute your application over multiple processing units (servers, JVM’s, whatever). Events can easily be serialized and sent from one server to another over JMS, via the file system or even email. The Spring Integration framework –a messaging framework – fits nicely with the event processing concept.</p>
<p>You could even let certain types of aggregates live on dedicated machines. This allows you to choose different SLA’s for different parts of you application, such as giving order creation a higher priority than sales reporting.</p>
<p><strong>Performance and Scalability</strong></p>
<p>Since event handling is done asynchronously, a user does not have to wait for all changes to be applied. Especially when integrating with external systems, this can improve liveness of an application significantly.</p>
<p>Another aspect of CQRS is that it heavily builds upon BASE (<strong>B</strong>asic <strong>A</strong>vailability, <strong>S</strong>oft-state, <strong>E</strong>ventual consistency) transactions. Although the “eventual” part scares a lot of customers and developers, the price of distributed ACID transactions is one that customer typically resent. In most cases “eventual” is just a matter of several milliseconds. But you’re free to make that seconds, minutes or even hours if your SLA permits it (think of management reports that are only read once a week or month).</p>
<p><strong>Asynchronous analysis</strong></p>
<p>When you build a CQRS style application, all activity in your application is processed using events. This makes it easy to catch these events and monitor them for inconsistent behavior. Event analysis tools like <a href="http://esper.codehaus.org/" target="_blank">Esper</a> allow you to monitor event streams for patterns that indicate possible fraud.</p>
<p>For example, when you detect that a sudden large number of users has an increased amount of failed login attempts, you could decide to block these accounts for a small period of time. In one of our projects, we use <a href="http://www.rsa.com/node.aspx?id=3018" target="_blank">RSA Adaptive Authentication</a> to increase the level of authentication required when someone tries to login on an account that might be the subject of dictionary attacks.</p>
<h2>cqrs4j – an open source CQRS Framework</h2>
<p><a href="http://code.google.com/p/cqrs4j" target="_blank"><img style="display: inline; margin-left: 0px; margin-right: 0px; border-width: 0px;" title="cqrs4j logo" src="http://blog.jteam.nl/wp-content/uploads/2009/12/logo_large.png" border="0" alt="cqrs4j logo" width="100" height="100" align="left" /></a> A few days ago, I published the source code of a CQRS framework – <a href="http://code.google.com/p/cqrs4j" target="_blank">cqrs4j</a> – on Google code. This framework aims at reducing the amount of “plumbing” and boilerplate code to a minimum. It also provides integration support for Spring Integration and transactional event processing.</p>
<p>You can find project information, source code and documentation at <a href="http://code.google.com/p/cqrs4j/">http://code.google.com/p/cqrs4j/</a>.</p>
<p>[Update: cqrs4j has been renamed to Axon Framework. You can find more information on www.axonframework.org].</p>
<h2>Upcoming presentations and events</h2>
<p>JTeam organizes monthly Tech Meetings, where interesting technologies are discussed. The January 2010 edition will contain a presentation about CQRS. Registration is required, but free of charge. The tech meeting is held on January 7th in our office in Amsterdam [<a href="http://www.jteam.nl/contact.html" target="_blank">directions</a>] and starts at 16:00. It includes dinner.  Send us an <a href="mailto:techmeeting@jteam.nl?subject=I%20want%20to%20join%20the%203rd%20Dec%20Tech%20meet%20%40%20JTeam&amp;body=Name%3A%0AOrganization%3A%0Aemail%3A%0ATel.%23%0A" target="_blank">email</a> if you like to attend.</p>
<p>The DDDnl user group organizes a presentation and discussion session on March 9th, starting at 18:00. It is also held at the JTeam office in Amsterdam [<a href="http://www.jteam.nl/contact.html" target="_blank">directions</a>]. Attendance requires <a href="http://www.dddnl.org/user/register" target="_blank">registration</a> with the DDDnl user group, which is completely free of charge. Visit <a href="http://www.dddnl.org" target="_blank">dddnl.org</a> for more information.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jteam.nl/2009/12/21/rethinking-architecture-with-cqrs/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Battling complexity in large web applications</title>
		<link>http://blog.jteam.nl/2009/10/20/battling-complexity-in-large-web-applications/</link>
		<comments>http://blog.jteam.nl/2009/10/20/battling-complexity-in-large-web-applications/#comments</comments>
		<pubDate>Tue, 20 Oct 2009 10:15:48 +0000</pubDate>
		<dc:creator>Allard Buijze</dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[Application Design]]></category>
		<category><![CDATA[Architecture]]></category>
		<category><![CDATA[Productivity]]></category>

		<guid isPermaLink="false">http://blog.jteam.nl/2009/10/20/battling-complexity-in-large-web-applications/</guid>
		<description><![CDATA[Nowadays, companies are hardly ever satisfied with a mere web-presence. No, websites have become true applications in their own right. Instead of being a by-product, most businesses acknowledge that the web offers them a nice channel to do business. However, the demands from the business keeps growing as each company want to be better than [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://blog.jteam.nl/wp-content/uploads/2009/10/spaceshuttleendeavourlaunch2.jpg"><img style="border-right-width: 0px; margin: 0px 5px 5px 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="space-shuttle-endeavour-launch-2" border="0" alt="space-shuttle-endeavour-launch-2" align="left" src="http://blog.jteam.nl/wp-content/uploads/2009/10/spaceshuttleendeavourlaunch2_thumb.jpg" width="71" height="104" /></a> Nowadays, companies are hardly ever satisfied with a mere web-presence. No, websites have become true applications in their own right. Instead of being a by-product, most businesses acknowledge that the web offers them a nice channel to do business. However, the demands from the business keeps growing as each company want to be better than its competitors. </p>
<p>The increasing demands from the business have a direct influence on the applications complexity. Each time, especially when joining external projects, I am amazed by the way complexity is dealt with in most applications. “Building software isn’t rocket science”, but sometimes we do seem to make it just as complex.</p>
<p>In this article, I provide some insight in different forms of complexity, and how software development teams can design their application in order to deal with the ever growing demands from the business.</p>
<p> <span id="more-1245"></span>
<p>At the dawn of each software development project, the sky is blue and the grass is green. That’s the type of project most developers like to do. However, as time progresses and features are added and changed (they are hardly ever removed, for some reason), the developers become entangled by their own code. Concepts –in which lots of time was invested to get them defined- become muddled and intentions of methods and services become vague. Eventually, the application will evolve into a <a href="http://en.wikipedia.org/wiki/Big_ball_of_mud" target="_blank">Big Ball of Mud</a>.</p>
<p><strong>Causes of complexity</strong></p>
<p>The degree in which the project team deal with complexity significantly influences the speed at which a codebase evolves into a ball of mud. There are numerous sources for complexity, that can be separated into three categories. </p>
<p align="center"><a href="http://geekandpoke.typepad.com/geekandpoke/2007/10/complexity.html" target="_blank"><img style="border-right-width: 0px; display: block; float: none; border-top-width: 0px; border-bottom-width: 0px; margin-left: auto; border-left-width: 0px; margin-right: auto" title="complexajax" border="0" alt="complexajax" src="http://blog.jteam.nl/wp-content/uploads/2009/10/complexajax.jpg" width="302" height="420" /></a><em>It is important to distinguish the different causes of complexity</em></p>
<p><u><em>Project Environment</em></u></p>
<p>The first source is the project environment itself. This mainly includes the availability of resources (e.g. people, money, knowledge) and the management style of the project manager and customer. Some project managers truly believe that when a developers estimates a piece of work at 1 week, that the sentence “I’ll give you 3 days” will actually do good to the project on the long term. Although an interesting topic, it is not the type of complexity I want to deal with in this post.</p>
<p><u><em>Technical Complexity</em></u></p>
<p>Another aspect influencing complexity is the technical environment of the project. What are the frameworks and platforms used in the development and deployment of the software. As with any technology, it is important to know the powers and limitations of each framework. If a framework requires expert knowledge to interact with it, then try to abstract that knowledge away into separate modules.</p>
<p>Every development team contains a couple of developers that is very well capable of solving these technical solutions. However, once solved and abstracted away, this technical complexity is mitigated and hardly a risk to the project. Of course there are extremes, where project heavily rely on bleeding edge technology. On those projects, you’re likely to keep a high level of technical complexity in the project. But no matter what, it should be clearly separated from the other type, discussed in the next paragraph.</p>
<p><u><em>Business Complexity</em></u></p>
<p>The third aspect is the one I will be focusing on in this post: the business domain. It is the sum of the knowledge, rules and activities of your customer that makes them survive. Solving the problems in this domain is often highly complex, but not unsolvable.</p>
<p>The majority of the business complexity is composed of the business rules. In contrast to the technological environment, the business environment is continuously in motion. And for some reason, this always means the addition of new rules and the changing of old ones, hardly ever removing them. The result of this process is an ever-growing application with increasing complexity.</p>
<p>The next sections cover a few guidelines that help you manage complexity and maintain it in acceptable ranges. In the end, people have to be able to understand the code.</p>
<p><strong>Application Layering</strong></p>
<p>The use of layers in software engineering is a concept I encounter in almost any project I join. The boundaries and definitions of these layers, though, are often fuzzy or undefined. The result is that, as the project progresses, different types of concerns leak into layers of the application where those concerns do not belong.</p>
<p>When correctly defined, layers can help developers make a clear separation between different types of complexity. Solve technical issues in another layer (e.g. the infrastructure layer) than the business complexity (e.g. application or service layer). Define clear boundaries between these layers and make sure each developer understands and respects them.</p>
<p><strong>Use a model</strong></p>
<p>The real world as a whole is useless when it comes to solving problems in software engineering. If you’re in the theatre ticket selling business, you don’t care that seats come in different styles, different colors and that some types of seats have legs. In other words, you don’t care what a seat is in the real world. I don’t expect to be telling new stuff here, but for some reason, I see it go wrong many times.</p>
<p>A common mistake I encounter in programs is that there is no real model at all. Well, there is a modules in the project called model, and it contains classes with getters and setters. Technically, it is a model, but is has been simplified to the extent that it is pretty much useless in solving the business problems. These problems are then solved in the service layer. But with the additions of new rules, this layer grows out of proportions with in some cases hundreds of methods, some of which are quite-the-same-but-not-really.</p>
<p>Another pitfall is the desire to make their model similar to the real world. The real world is not relevant to the application. An application needs to solve problems. The real world might just not be the ideal place to do that. Instead, the business itself should drive the modeling choices. And if two parts of a business (e.g. divisions) have different views on the same actual thing, consider creating a different model for each one of them.</p>
<p>A third consideration often forgotten in the development process is that not every part of the application should have to use the same model. A model is used to solve (complex) problems. Each part of an application solves different problems in the domain. A logical conclusion is that these parts do not necessarily ask for the same model. A good indicator for the possibility of splitting the model is that a single word is used in different contexts, and has a different meaning in each context. The word “Flight” will mean different things to the ground crew and the cabin crew. They will all have different intents when using the concept of a Flight. Combining all these intents into a single (shared) domain concept will most likely clutter your domain and make it harder to understand.</p>
<p><strong>Watch your language</strong></p>
<p>Ideally, the names of the concepts in the model reflect the actual words used in the business. If a new concept is added to the model, that name should be introduced in the business as well. Eric Evans calls this the “Ubiquitous Language”, the language used by all people and software involved in the domain the software runs in.</p>
<p>Why is this important? It helps new developers on a project. If they are familiar with the terminology, they will most likely understand the application right away. If they don’t, they will pick up the jargon faster and be able to talk to domain experts earlier.</p>
<p>It will also help in finding the locations where changes need to be made. If the model is correct (i.e. fits the business nicely), the language the domain expert uses will pinpoint you to the location where changes need to be made.</p>
<p><strong>Modularity</strong></p>
<p>Where simple applications will contain just a few concepts (where each concept is implemented as one or few classes), large applications may contain literally hundreds or thousands of concepts. A human being is simply not able to maintain a good overview of that amount of concepts.</p>
<p>Therefore, separate related concepts into modules. Within a module, these concepts may have tight relationships. In other words, the classes representing these concepts will have dependencies towards each other. Across modules, dependencies should be minimized. I often encounter dependencies between modules that don’t really need to be there. Removing them decreases application complexity and increases its maintainability. Especially “<a href="http://en.wikipedia.org/wiki/Domain-driven_design" target="_blank">Entity</a>”&#160; to “Entity” relationships should be avoided as much as possible.</p>
<p>For example, let’s say we have an Order that references a Product, both in different modules as different departments manage the lifecycle of these objects. What happens if the Product price changes? All orders containing that product (and most of them have probably been handled already) will change as well. The solutions is simple, add a property to the order that states the price at which the product was sold. What if other characteristics change? The name for example? Remember, we don’t care about the real world , where products don’t just change name, we care about the world the way the business wants it. Instead of referencing the Product entity as a whole, perhaps it is sufficient to copy the relevant data from the Product into the Order at the time the Order is created. Or perhaps the entity reference is only maintained for as long as the Order is being processed. This allows you to delete Product instances without losing data in the Orders module.</p>
<p>The choices you can make in keeping nicely separated modules heavily depend on the way the model has been built. The better the model is, the more flexibility you have in making choices that help your application.</p>
<p><strong>Conclusion</strong></p>
<p>In this post, I have briefly touched a few types of complexity encountered in software projects. Don’t deal with multiple types of complexity in one location (i.e. layer) in your application. Make a clear separation between these to prevent technical choices from interfering with your business logic and vice versa.</p>
<p>When it comes to business logic, try to make a model that fits the way the business likes to work. Don’t try to make it look like the real world. That world has proven to be less than ideal when it comes to solving complex problems.</p>
<p>Use the Ubiquitous Language to define the terms and concepts in your model. This helps new developers to learn the language faster and get a better understanding of the application.</p>
<p>Finally, when the number of concepts expands beyond human capability of maintaining an overview of them, separate concepts into modules. Choose your modularity carefully. Try to keep dependencies tight inside the module, while limiting the dependencies between modules.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jteam.nl/2009/10/20/battling-complexity-in-large-web-applications/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Exploring the world of Android :: Part 3</title>
		<link>http://blog.jteam.nl/2009/10/08/exploring-the-world-of-android-part-3/</link>
		<comments>http://blog.jteam.nl/2009/10/08/exploring-the-world-of-android-part-3/#comments</comments>
		<pubDate>Wed, 07 Oct 2009 23:00:06 +0000</pubDate>
		<dc:creator>Tom van Zummeren</dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[Android]]></category>
		<category><![CDATA[Application Design]]></category>
		<category><![CDATA[Java]]></category>

		<guid isPermaLink="false">http://blog.jteam.nl/?p=1163</guid>
		<description><![CDATA[In my travels through the world of Android I faced a lot of challenges. Brave as I am, *cough* I conquered each one of them. A few of the challenges include saving activity state, asynchronous tasks, pagination, error handling, context/option menu&#8217;s and even drawing custom application/tab icons in Photoshop! Some challenges I already shared with [...]]]></description>
			<content:encoded><![CDATA[<p>In my travels through the world of Android I faced a lot of challenges. Brave as I am, *cough* I conquered each one of them. A few of the challenges include saving activity state, asynchronous tasks, pagination, error handling, context/option menu&#8217;s and even drawing custom application/tab icons in Photoshop! Some challenges I <a href="http://blog.jteam.nl/2009/09/08/exploring-the-world-of-android-part-1/">already</a> <a href="http://blog.jteam.nl/2009/09/17/exploring-the-world-of-android-part-2/">shared</a> with you guys, but there is one challenge in particular I would like to elaborate on this time.</p>
<p>The app I am currently building is getting larger every day, and so is the main <em>Activity</em> class! Because my main activity contains a <em>TabHost</em> with a bunch of tabs, it also contains references to all individual view components contained in those tabs. All kinds of listeners are registered on those components so the activity contains some inner and anonymous classes as well. So you could say that this activity now has way too much responsibility! What I was looking for, is a way to separate the main activity into multiple parts, each with its own clear responsibility. </p>
<p>As it turns out, you can <strong>create custom components</strong> for a single piece of functionality within an <em>Activity</em>. Exactly what I was looking for!<br />
<span id="more-1163"></span></p>
<h2>Writing custom components</h2>
<p>There are different ways to write custom components for your Android application. </p>
<ul>
<li><strong>Simply extend a view class</strong> &#8211; If you want to add some behavior to an existing view class (like a TextView or a ListView) you can simply extend the class and override any method you like.</li>
<li><strong>Create an entirely customized component</strong> &#8211; Extend the View class and implement everything from scratch. Create listeners, properties, implement onMeasure() and onDraw(), etcetera. This might be useful if you want a very specific component and fine grained for your needs, for example a slider control.</li>
</ul>
<p>Read about the above approaches here: <a href="http://developer.android.com/guide/topics/ui/custom-components.html">http://developer.android.com/guide/topics/ui/custom-components.html</a>.</p>
<h3>Compound components</h3>
<p>Unfortunately both of the above approaches are not what I was looking for in this case. I was looking for a way to simply group a bunch of view components in a separate class, also containing all related behavior logic. Luckily there is a way to do this! In the documentation they call it &#8220;compound components&#8221;, which is exactly what I was looking for. To explain it, I will try to demonstrate it with the following example:</p>
<pre class="brush: java;">
public class MyActivity extends TabActivity {

    // First tab
    private LinearLayout linearLayout;
    private EditText editText;
    private ListView listView;

    // Second tab
    private RelativeLayout relativeLayout;
    private ImageView imageView;
    private TextView textView;
    private TextView anotherTextView;

    // Third tab
    private TableLayout tableLayout;
    private TextView tableLabel;

    @Override
    protected void onCreate(Bundle bundle) {
        super.onCreate(bundle);
        setContentView(R.layout.main);

        // Initialization logic for all the above components
    }

    // All kinds of helper methods for things like the initialization logic,
    // listeners, context and option menu's ...

    private void handleSomeClick() {
        // ...
    }

    private class FirstTabEditTextClickListener implements View.OnClickListener {
        public void onClick(View view) {
            // On click logic for the editText component
        }
    }

    // Some more listener inner classes ...
}
</pre>
<p>The &#8220;main.xml&#8221; layout file would look something like this:</p>
<pre class="brush: xml;">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
&lt;TabHost xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;
         android:id=&quot;@android:id/tabhost&quot;
         android:layout_width=&quot;fill_parent&quot;
         android:layout_height=&quot;fill_parent&quot;&gt;

    &lt;LinearLayout android:orientation=&quot;vertical&quot;
                  android:layout_width=&quot;fill_parent&quot;
                  android:layout_height=&quot;fill_parent&quot;&gt;

        &lt;TabWidget android:id=&quot;@android:id/tabs&quot;
                   android:layout_width=&quot;fill_parent&quot;
                   android:layout_height=&quot;wrap_content&quot;/&gt;

        &lt;FrameLayout android:id=&quot;@android:id/tabcontent&quot;
                     android:layout_width=&quot;fill_parent&quot;
                     android:layout_height=&quot;fill_parent&quot;&gt;
            &lt;LinearLayout android:id=&quot;@+id/firstTab&quot;
                          android:layout_width=&quot;fill_parent&quot;
                          android:layout_height=&quot;fill_parent&quot;&gt;
                &lt;!-- All view components of the first tab --&gt;
            &lt;/LinearLayout&gt;
            &lt;RelativeLayout android:id=&quot;@+id/secondTab&quot;
                          android:layout_width=&quot;fill_parent&quot;
                          android:layout_height=&quot;fill_parent&quot;&gt;
                &lt;!-- All view components of the second tab --&gt;
            &lt;/RelativeLayout&gt;
            &lt;TableLayout android:id=&quot;@+id/thirdTab&quot;
                          android:layout_width=&quot;fill_parent&quot;
                          android:layout_height=&quot;fill_parent&quot;&gt;
                &lt;!-- All view components of the third tab --&gt;
            &lt;/TableLayout&gt;
        &lt;/FrameLayout&gt;
    &lt;/LinearLayout&gt;
&lt;/TabHost&gt;
</pre>
<h3>Identify the components</h3>
<p>The first thing to do is to identify the individual components you want to separate. In this case we can simply split this activity into three components, one for each tab. Of course, the <em>Activity</em> itself will still exist for obvious reasons (handling menu items, displaying dialogs, etc.). So in the end we&#8217;ll have a total of 4 classes.</p>
<h3>Create new component classes</h3>
<p>Second step is to create a new class for each component you want to create, which extends some layout class. In the case of this example those layout classes are <em>RelativeLayout</em>, <em>LinearLayout</em> and <em>TableLayout</em> (see above layout definition). Next, move all components contained in those layouts to the appropriate classes along with all related logic (listeners, etc.). </p>
<p>Example of such a component:</p>
<pre class="brush: java;">
public class FirstTab extends LinearLayout {
    private ImageView imageView;
    private TextView textView;
    private TextView anotherTextView;

    public SecondTab(Context context, AttributeSet attributeSet) {
        super(context, attributeSet);

        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        inflater.inflate(R.layout.firstTab, this);
    }
}
</pre>
<p>Classes called <em>SecondTab</em> and <em>ThirdTab</em> can be implemented in a similar way. First thing to notice about the above implementation is the constructor. It should always have the following 2 arguments: <em>Context</em> and <em>AttributeSet</em>. Without such a constructor this component can&#8217;t be instantiated from XML. Another thing to notice is that a layout called &#8220;firstTab&#8221; is inflated on instantiation. All instantiated views in that layout are added as a child of <em>FirstTab</em></p>
<p>Now, let&#8217;s try to create the &#8220;firstTab&#8221; layout that is being instantiated from the <em>FirstTab</em> component class:</p>
<pre class="brush: xml;">
&lt;LinearLayout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;&gt;
    &lt;!-- All view components of the first tab --&gt;
&lt;/LinearLayout&gt;
</pre>
<p><strong>There is a problem with this layout definition.</strong> If you think about it, you&#8217;ll notice what&#8217;s wrong with it. The problem is that when this layout is inflated, an instance of <em>LinearLayout</em> is created with all it&#8217;s defined child components attached. This is a problem because after the <em>LinearLayout</em> is instantiated, it is attached as a child component of the <em>FirstTab</em>, which itself already is a <em>LinearLayout</em>. So using this layout you will get a redundant <em>LinearLayout</em> in between the <em>FirstTab</em> and its child components.</p>
<p>The solution for this problem took me a while to figure out, but is actually quite simple. Instead of <em>LinearLayout</em> you should use the <em>merge</em> tag like this:</p>
<pre class="brush: xml;">
&lt;merge xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;&gt;
    &lt;!-- All view components of the first tab --&gt;
&lt;/merge&gt;
</pre>
<p>The <em>merge</em> tag makes sure that all its child views are attached to the <em>merge</em> tag&#8217;s parent instead. This is exactly what we want! Because now no new <em>LinearLayout</em> is instantiated and all child components are attached directly to the <em>FirstTab</em>.</p>
<p>To reference your new components from the original layout definition &#8220;main.xml&#8221;, you should use the fully qualified class name of the components. So this is how the layout could look like now:</p>
<pre class="brush: xml;">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
&lt;TabHost xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;
         android:id=&quot;@android:id/tabhost&quot;
         android:layout_width=&quot;fill_parent&quot;
         android:layout_height=&quot;fill_parent&quot;&gt;

    &lt;LinearLayout android:orientation=&quot;vertical&quot;
                  android:layout_width=&quot;fill_parent&quot;
                  android:layout_height=&quot;fill_parent&quot;&gt;

        &lt;TabWidget android:id=&quot;@android:id/tabs&quot;
                   android:layout_width=&quot;fill_parent&quot;
                   android:layout_height=&quot;wrap_content&quot;/&gt;

        &lt;FrameLayout android:id=&quot;@android:id/tabcontent&quot;
                     android:layout_width=&quot;fill_parent&quot;
                     android:layout_height=&quot;fill_parent&quot;&gt;
            &lt;com.example.android.FirstTab android:id=&quot;@+id/firstTab&quot;
                          android:layout_width=&quot;fill_parent&quot;
                          android:layout_height=&quot;fill_parent&quot;/&gt;
            &lt;com.example.android.SecondTab android:id=&quot;@+id/secondTab&quot;
                          android:layout_width=&quot;fill_parent&quot;
                          android:layout_height=&quot;fill_parent&quot;/&gt;
            &lt;com.example.android.ThirdTab android:id=&quot;@+id/thirdTab&quot;
                          android:layout_width=&quot;fill_parent&quot;
                          android:layout_height=&quot;fill_parent&quot;/&gt;
        &lt;/FrameLayout&gt;
    &lt;/LinearLayout&gt;
&lt;/TabHost&gt;
</pre>
<p>This is it! Now you have divided your views over several components (classes).</p>
<h2>Keep components loosely coupled</h2>
<p>Now that you have all your view and behavior logic divided into multiple classes, you will probably run into some issues. Examples:</p>
<ul>
<li><em>FirstTab</em> wants to refresh the <em>SecondTab</em> after a click on certain button</li>
<li>Menu items are handled in <em>MyActivity</em>, but actually need to make changes to <em>ThirdTab</em> when selected</li>
</ul>
<h3>Listeners</h3>
<p>The issue with the first example is, that <em>FirstTab</em> doesn&#8217;t have a reference to <em>SecondTab</em> to be able to refresh it. Under <strong>no circumstance</strong> should you give the <em>FirstTab</em> a direct reference to the <em>SecondTab</em>. This would result in very tight coupling between the components, which generally is not a good idea. Instead try to solve the issue using listeners. This is already a pattern implemented in a lot of places in the Android SDK itself, for example here: <a href="http://developer.android.com/reference/android/view/View.html#setOnClickListener(android.view.View.OnClickListener)">View#setOnClickListener(OnClickListener)</a>. So in the above example, you should create your own listener interface:</p>
<pre class="brush: java;">
public interface SearchListener {
    void onSearch(SearchResult searchResult);
}
</pre>
<p>This could for example be a listener for when a search is performed in the <em>FirstTab</em>. The <em>MyActivity</em> class could register an anonymous implementation of this listener interface and call the <em>SecondTab</em> to refresh it.</p>
<pre class="brush: java;">
firstTab.setSearchListener(new SearchListener() {
    public void onSearch(SearchResult searchResult) {
        secondTab.refresh(searchResult);
    }
});
</pre>
<p>A similar thing could be done when handling menu item clicks in the <em>MyActivity</em>, only this time listeners are not needed.</p>
<pre class="brush: java;">
public boolean onMenuItemSelected(int featureId, MenuItem item) {
    switch (item.getItemId()) {
        case MENU_ADD_ENTRY:
            thirdTab.addEntry();
            break;
    }
}
</pre>
<p>So, create methods on your custom components if you need to control them from your Activity. Never expose any child components of your custom component to the Activity. The <em>Activity</em> should not have to know about them at all. Instead, create methods on your custom components that controls these child components like the above examples (refresh(&#8230;) and addEntry()).</p>
<p>I think with similar approaches, all issues can be solved when splitting your activity in multiple components. When you solve all issues you might have, you will have a cleanly separated Android application! This improves the overview of the application and makes it more maintainable.</p>
<h2>Summary</h2>
<p>I&#8217;ve shown you how to avoid making a mess of your application&#8217;s Activities by splitting clear chunks of functionality into custom components. Also, to avoid tight coupling between the custom components, I suggested to use Listeners.</p>
<p>If you have ever tried to deal with this before and have other suggestions to approach this, please leave a comment! Also, if you decided to try this structure in your application, let me know how that works out for you by leaving a comment!</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jteam.nl/2009/10/08/exploring-the-world-of-android-part-3/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>
