<?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>Modular Architecture</title>
	<atom:link href="http://www.kirkk.com/modularity/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.kirkk.com/modularity</link>
	<description>Patterns of Modular Architecture</description>
	<lastBuildDate>Wed, 28 Apr 2010 20:15:10 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.8.6</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>The Future of Modularity: OSGi</title>
		<link>http://www.kirkk.com/modularity/2010/04/the-future-of-modularity-osgi/</link>
		<comments>http://www.kirkk.com/modularity/2010/04/the-future-of-modularity-osgi/#comments</comments>
		<pubDate>Fri, 23 Apr 2010 16:09:15 +0000</pubDate>
		<dc:creator>kirk knoernschild</dc:creator>
				<category><![CDATA[Appendix]]></category>

		<guid isPermaLink="false">http://www.kirkk.com/modularity/?p=553</guid>
		<description><![CDATA[Discuss the future of modularity and the impact OSGi will have on enabling and enforcing modularity, as well as how these patterns will be implemented and supported by OSGi.
For instance, PublishedInterface is directly enabled by OSGi export packages.
Note the increasing platform support and that development teams will be able to use it soon.
Note the impact, [...]]]></description>
			<content:encoded><![CDATA[<p>Discuss the future of modularity and the impact OSGi will have on enabling and enforcing modularity, as well as how these patterns will be implemented and supported by OSGi.</p>
<p>For instance, PublishedInterface is directly enabled by OSGi export packages.</p>
<p>Note the increasing platform support and that development teams will be able to use it soon.</p>
<p>Note the impact, not just on the developer and how applications are created, but also in how they are managed.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.kirkk.com/modularity/2010/04/the-future-of-modularity-osgi/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>SOLID Principles of Class Design</title>
		<link>http://www.kirkk.com/modularity/2009/12/solid-principles-of-class-design/</link>
		<comments>http://www.kirkk.com/modularity/2009/12/solid-principles-of-class-design/#comments</comments>
		<pubDate>Wed, 30 Dec 2009 20:15:47 +0000</pubDate>
		<dc:creator>kirk knoernschild</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://www.kirkk.com/modularity/?p=453</guid>
		<description><![CDATA[The SOLID principles lie at the heart of the object-oriented paradigm. Many of the principles presented here first appeared in Robert Martin’s Design Principles and Design Principles [MARTIN2000], which serves as an excellent complement to this discussion. These principles help you manage dependencies between classes and encourage class cohesion. They are also critical to effective [...]]]></description>
			<content:encoded><![CDATA[<p>The SOLID principles lie at the heart of the object-oriented paradigm. Many of the principles presented here first appeared in Robert Martin’s Design Principles and Design Principles [MARTIN2000], which serves as an excellent complement to this discussion. These principles help you manage dependencies between classes and encourage class cohesion. They are also critical to effective module design using object oriented techniques.</p>
<h2>Single Responsibility Principle (SRP)</h2>
<blockquote><p>Classes should change for only a single reason.</p></blockquote>
<p>The basis for this principle is cohesion. Cohesion represents the measure to which a class performs a single function. Classes that are highly cohesive are easier to understand. But they are also easier to maintain. This is the motivating force behind SRP. If a class has more than one reason to change, then it stands to reason that the responsibilities of that class that are the cause of change should be separated into multiple classes.</p>
<p>Cohesion is not a concept new to objects. In fact, the concept is taught in most introductory programming courses. Ironically, I&#8217;ve found that while most developers can easily define cohesion and explain it&#8217;s benefits, few developers actually apply it. Cohesion measures the degree to which an entity does a single thing. Given this definition, it&#8217;s no surprise that if some entity is responsible for performing only a single thing, most of our entities should be fairly small. Yet I commonly come across methods that run well over 100 lines of code, and classes that run orders of magnitudes larger than that. I struggle to convince myself that either are very cohesive. When you&#8217;re designing a highly cohesive system, you have to think small.</p>
<h2>Open Closed Principle (OCP)</h2>
<blockquote><p>Classes should be open for extension, but closed for modification.</p></blockquote>
<p>The Open Closed Principle (OCP) is undoubtedly the most important of all the class category principles. In fact, each of the remaining class principles are derived from OCP. It originated from the work of Bertrand Meyer who is recognized as an authority on the object-oriented paradigm. OCP is states that we should have the ability to add new features to our system without having to modify our set of preexisting classes. As stated previously, one of the benefits of the object-oriented paradigm is to enable us to add new data structures to our system without having to modify the existing system’s code base.</p>
<p>Let’s look at an example to see how this can be done. Consider a financial institution where we have to accommodate different types of accounts to which individuals can make deposits. Figure 4.1 shows a class diagram, with accompanying descriptions of some of the elements and how we might structure a portion of our system. For the purposes of our discussion in this chapter, we will focus on how the OCP can be used to extend the system.</p>
<p>Our Account class has a relationship to our AccountType abstract class. In other words, our Account class is coupled at the abstract level to the AccountType inheritance hierarchy. Because our Savings and Checking classes each inherit from the AccountType class, we know that through dynamic binding, we can substitute instances of either of these classes wherever the AccountType class is referenced. Subsequently, Savings and Checking can be freely substituted for AccountType within the Account class. This is the intent of an abstract class and enables us to effectively adhere to OCP by creating a contract between the Account class and the AccountType descendents. Because our Account is not directly coupled to either of the concrete Savings or Checking classes, we can extend the AccountType class, creating a new class such as MoneyMarket, without having to modify our Account class. We have achieved OCP and can now extend our system without modify its existing code base.</p>
<p>Figure 4.1<br />
Therefore, one of the tenets of OCP is to reduce the coupling between classes to the abstract level. Instead of creating relationships between two concrete classes, we create relationships between a concrete class and an abstract class or, in Java, between a concrete class and an interface. When we create an extension of our base class, assuming we adhere to the public methods and their respective signatures defined on the abstract class, we have essentially achieved OCP. Let’s take a look at a simplified version of the Java code for this example, focusing on how we achieve OCP, instead of on the actual method implementations.</p>
<pre class="brush: java;">
public class Account {
   private AccountType _act;
   public Account(String act) {
      try {
         Class c = Class.forName(act);
         this._act = (AccountType) c.newInstance();
      } catch (Exception e) {
         e.printStackTrace();
      }
   }
   public void deposit(int amt) {
      this._act.deposit(amt);
   }
}
</pre>
<p>Here, our Account class accepts as an argument to its constructor a String representing the class we wish to instantiate. It then uses the Class class to dynamically create an instance of the appropriate AccountType subclass. Note that we don’t explicitly refer to either the Savings or Checking class directly.</p>
<pre class="brush: java;">
public abstract class AccountType  {
   public abstract void deposit(int amt);
}</pre>
<p>This is the abstract AccountType class that serves as the contract between our Account class and AccountType descendents. The deposit method is the contract.</p>
<pre class="brush: java;">
public class CheckingAccount extends AccountType {
   public void deposit(int amt) {
      System.out.println();
      System.out.println();
      System.out.println(&quot;Amount deposited in checking account: &quot; + amt);
      System.out.println();
      System.out.println();
   }
}
</pre>
<pre class="brush: java;">
public class SavingsAccount extends AccountType {
   public void deposit(int amt)  {
      System.out.println();
      System.out.println();
      System.out.println(&quot;Amount deposited in savings account: &quot; + amt);
      System.out.println();
      System.out.println();
   }
}
</pre>
<p>Each of our AccountType descendents satisfies the contract by providing an implementation for the deposit method. In the real world, the behaviors of the individual deposit methods would be more interesting and, given the preceding design, would be algorithmically different.</p>
<h2>Liskov Substitution Principle (LSP)</h2>
<blockquote><p>Subclasses should be substitutable for their base classes.</p></blockquote>
<p>We mentioned in our previous discussion that OCP is the most important of the class category principles. We can think of the Liskov Substitution Principle (LSP) as an extension to OCP. In order to take advantage of LSP, we must adhere to OCP because violations of LSP are also a violation of OCP, but not vice versa. LSP is the work of Barbara Liskov and is derived from Bertrand Meyer’s Design by Contract. In its simplest form, it is difficult to differentiate OCP and LSP, but a subtle difference does exist. OCP is centered around abstract coupling. LSP, while also heavily dependent on abstract coupling, is also heavily dependent on preconditions and postconditions, which is LSP’s relation to Design by Contract, where the concept of preconditions and postconditions was formalized.</p>
<p>A precondition is a contract that must be satisfied before a method can be invoked. A postcondition, on the other hand, must be true upon method completion. If the precondition is not met, the method should not be invoked, and if the postcondition is not met, the method should not return. The relation of preconditions and postconditions has meaning embedded within an inheritance relationship that is not supported within Java, outside of some manual assertions or nonexecutable comments. Because of this, violations of LSP can be difficult to find.</p>
<p>To illustrate LSP and the interrelationship of preconditions and postconditions, we need only consider how Java’s exception handling mechanism works. Consider a method on an abstract class that has the following signature:</p>
<pre class="brush: java;">
public abstract deposit(int amt) throws InvalidAmountException
</pre>
<p>Assume in this situation, that our InvalidAmountException is an exception defined by our application, is inherited from Java’s base Exception class, and can be thrown if the amount we try to deposit is less than zero. By rule, when overriding this method in a subclass, we cannot throw an exception that exists at a higher level of abstraction than InvalidAmountException. Therefore, a method declaration such as the following is not allowed:</p>
<pre class="brush: java;">
public void deposit(int amt) throws Exception
</pre>
<p>This method declaration is not allowed because the Exception class thrown in this method is the ancestor of the InvalidAmountException thrown previously. Again, we cannot throw an exception in a method on a subclass that exists at a higher level of abstraction than the exception thrown by the base class method we are overriding. On the other hand, reversing these two method signatures would have been perfectly acceptable to the Java compiler. We can throw an exception in an overridden subclass method that is at a lower level of abstraction than the exception thrown in the ancestor. While this does not correspond directly to the concept of preconditions and postconditions, it does capture the essence. Therefore, we can state that any precondition stipulated by a subclass method cannot be stronger than the base class method.Therefore, any postcondition stipulated by a subclass method cannot be weaker than the base class method.</p>
<p>To adhere to LSP in Java, we must make sure that developers define preconditions and postconditions for each of the methods on an abstract class. When defining our subclasses, we must adhere to these preconditions and postconditions. If we do not define preconditions and postconditions for our methods, it becomes virtually impossible to find violations of LSP. Suffice it to say, in the majority of cases, OCP will be our guiding principle.</p>
<h2>Dependency Inversion Principle (DIP)</h2>
<blockquote><p>Depend upon abstractions. Do not depend upon concretions.</p></blockquote>
<p>The Dependency Inversion Principle (DIP) formalizes the concept of abstract coupling and clearly states that we should couple at the abstract level, not at the concrete level. Abstract coupling is the notion that a class is not coupled to another concrete class, or class that can be instantiated. Instead, the class is coupled to other base, or abstract, classes. In Java, this abstract class can be either a class with the abstract modifier or a Java interface data type. Regardless, this concept is actually the means through which LSP achieves its flexibility, the mechanism required for DIP, and the heart of OCP.</p>
<p>In our own designs, attempting to couple at the abstract level can at times seem like overkill. Pragmatically, we should apply this principle in any situation where we are unsure whether the implementation of a class may change in the future. We have encountered situations during development where we know exactly what needs to be done. Requirements state this very clearly, and the probability of change or extension is quite low. In these situations, adherence to DIP may be more work than the benefit realized.<br />
At this point, there exists a striking similarity between DIP and OCP. In fact, these two principles are closely related. Fundamentally, DIP tells us how we can adhere to OCP. Or, stated differently, if OCP is the desired end, DIP is the means through which we achieve that end. While this statement may seem obvious, we commonly violate DIP in a certain situation and don’t even realize it.</p>
<p>When we create an instance of a class in Java, we typically must explicitly reference that object. Only after the instance has been created can we flexibly reference that object via its ancestors or implemented interfaces. Therefore, the moment we reference a class to create it, we have violated DIP and, subsequently, OCP. Recall that in order to adhere to OCP, we must first take advantage of DIP. There are a couple of different ways to resolve this.</p>
<p>The first way to resolve this impasse is to dynamically load the object using the Class class and its newInstance method. However, this solution can be problematic and somewhat inflexible. Because DIP doesn’t allow us to refer to the concrete class explicitly, we must use a String representation of the concrete class. For instance, consider the following:</p>
<pre class="brush: java;">
Class c = Class.forName(&quot;SomeDescendent&quot;); SomeAncestor sa = (SomeAncestor) c.newInstance();
</pre>
<p>In this example, we wish to create an instance of the class SomeDescendent in the first line, but reference it as type SomeAncestor in the second line. This was also illustrated in the code samples in the section “Open Closed Principle (OCP),” earlier in this chapter. This is perfectly acceptable, as long as the SomeDescendent class is inherited, either directly or indirectly, from the SomeAncestor class. If it is not, our application will throw an exception at runtime. Another more obvious problem occurs when we misspell the class of which we want an instance. Yet another, less apparent, obstacle eventually is encountered when taking this approach. Because we reference the class name as a string, there isn’t any way to pass parameters into the constructor of this class. Java does provides a solution to this problem, but it quickly becomes complex, unwieldy, and error prone.</p>
<p>Another approach to resolving the object creation challenge is to use an object factory. Here, we create a separate class whose only responsibility is to create instances. This way, our original class, where the instance would have previously been created, stays clear of any references to concrete classes, which have been removed and placed in this factory. The only references contained within this class are to abstract, or base, classes. The factory does, however, reference the concrete classes, which is, in fact, a blatant violation of DIP. However, it is an isolated and carefully thought through violation and is therefore acceptable.</p>
<p>Keep in mind that we may not always need to use an object factory. Along with the flexibility of a factory comes the complexity of a more dynamic collaboration of objects. Concrete references are not always a bad thing. If the class to which we are referring is a stable class, not likely to undergo many changes, using a factory adds unwarranted complexity to our system. If a factory is deemed necessary, the design of the factory itself should be given careful consideration.</p>
<h2>Interface Segregation Principle</h2>
<blockquote><p>Many specific interfaces are better than a single, general interface.</p></blockquote>
<p>Put simply, any interface we define should be highly cohesive. In Java, we know that an interface is a reference data type that can have method declarations, but no implementation. In essence, an interface is an abstract class with all abstract methods. As we define our interfaces, it becomes important that we clearly understand the role the interface plays within the context of our application. In fact, interfaces provide flexibility: They allow objects to assume the data type of the interface. Subsequently, an interface is simply a role that an object plays at some point throughout its lifetime. It follows, rather logically, that when defining the operation on an interface, we should do so in a manner that does not accommodate multiple roles. Therefore, an interface should be responsible for allowing an object to assume a single role, assuming the class of which that object is an instance implements that interface.</p>
<p>While working on a project recently, an ongoing discussion took place as to how we would implement our data access mechanism. Quite a bit of time was spent designing a flexible framework that would allow uniform access to a variety of different data sources. These back-end data sources might come in the form of a relational database, a flat file, or possibly even another proprietary database. Therefore, our goal was not only to provide a common data access mechanism, but also to present data to any class acting as a data client in a consistent manner. Doing so would clearly decouple our data clients from the back-end data source, making it much easier to port our back-end data sources to different platforms without impacting our data clients. Therefore, we decided that all data clients would depend on a single Java interface, depicted in Figure 4.3, with the associated methods.</p>
<p>Figure 4.3</p>
<p>At first glance, the design depicted in Figure 4.3 seemed plausible. After further investigation, however, questions were raised as to the cohesion of the RowSetManager interface. What if classes implementing this interface were read-only and didn’t need insert and update functionality? Also, what if the data client were not interested in retrieving the data, but only in iterating its already retrieved internal data set? Exploring these questions a bit further, and carefully considering ISP, we found that it was meaningful to have a data structure that wasn’t even dependent on a retrieve action at all. For instance, we may wish to use a data set that was cached in memory and wasn’t dependent on an underlying physical data source. This led us to the design in Figure 4.4.</p>
<p>Figure 4.4</p>
<p>In Figure 4.4, we see that we have segregated the reponsibilities of our RowSetManager into multiple interfaces. Each interface is responsible for allowing a class to adhere to a cohesive set of responsibilities. Now, our application can implement the interfaces necessary to provide the desired set of functionality. We are no longer forced to provide data update behavior if our class is read-only.</p>
<h2>Composite Reuse Principle (CRP)</h2>
<blockquote><p>Favor polymorphic composition of objects over inheritance.</p></blockquote>
<p>The Composite Reuse Principle (CRP) prevents us from making one of the most catastrophic mistakes that contribute to the demise of an object-oriented system: using inheritance as the primary reuse mechanism. The first reference to this principle was in [GOF94]. For example, let’s turn back to a section of our diagram in Figure 4.1. In Figure 4.5, we see the AccountType hierarchy with a few additional attributes and methods added. In this example, we have added an additional method that calculates the interest for each of our accounts. We have added this method to the ancestor AccountType class. This seems to be a good approach, because our Savings and MoneyMarket classes are each interest bearing accounts. Our Checking class is representative of an account that is not interest bearing. Regardless, we justify this by convincing ourselves that it’s better to define some default behavior on an ancestor and override it on descendents instead of duplicating the behavior across descendents. We know that we can simply define a null operation  on our Checking class that doesn’t actually calculate interest, and our problem is solved. While we do want to reuse our code, and we can prevent the Checking class from calculating interest, our implementation contains a tragic flaw. First, let’s discuss the flaw and when it will surface. Then we’ll discuss why this problem has occurred.</p>
<p>Let’s consider a couple of new requirements. We need to support the addition of a new account type, called Stock. A Stock does calculate interest, but the algorithm for doing so is different than the default defined in our ancestor AccountType. That’s easy to solve. All we have to do is override the calculateInterest in our new Stock class, just as we did in the Checking class, but instead of implementing a null operation , we can implement the appropriate algorithm. This works fine until our business realizes that the Stock class is doing extremely well, primarily because of its generous interest calculation mechanism. It’s been decided that MoneyMarket should calculate interest using the same algorithm as Stock, but Savings remains the same. How do we solve this problem? We have three choices. First, redefine the calculateInterest method on our AccountType to implement this new algorithm and define a new method on Savings that implements the older method. This option is not ideal because it involves modifying at least two of our existing system classes, which is a blatant violation of OCP. Second, we could simply override calculateInterest on our MoneyMarket class, copy the code from our Stock class, and paste it in our MoneyMarket calculateInterest method. Obviously, this option is not a very flexible solution. Our goal in reuse is not copy and paste. Third, we can define a new class called InterestCalculator, define a calculateInterest method on this class that implements our new algorithm, and then delegate the calculation of interest from our Stock and MoneyMarket classes to this new class. So, which option is best?</p>
<p>The third solution is the one we should have used up front. Because we realized that the calculation of interest was not common to all classes, we should not have defined any default behavior in our ancestor class. Doing so in any situation inevitably results in the previously described outcome. Let’s now resolve this problem using CRP.</p>
<p>Figure 4.5</p>
<p>In Figure 4.6, we see a depiction of our class structure utilizing CRP. In this example, we have no default behavior defined for calculateInterest in our AccountType hierarchy. Instead, in our calculateInterest methods on both our MoneyMarket and Savings classes, we defer the calcuation of interest to a class that implements the InterestCalculator interface. Now, when we add our Stock class, we simply choose the InterestCalculator that is applicable for this new class or define a new one if it’s needed. If any of our other classes need to redefine their algorithms, we have the ability to do so because we are abstractly coupled to our interface and can substitute any of the classes that implement the interface anywhere the interface is referenced. Therefore, this solution is ultimately flexible in how it enables us to calculate interest. This is an example of CRP. Each of our MoneyMarket and Savings classes are composed of our InterestCalculator, which is the composite. Because we are abstractly coupled, we easily see we can receive polymorphic behavior. Hence, we have used polymorphic composition instead of inheritance to achieve reuse.</p>
<p>Figure 4.6</p>
<p>You might say at this point, however, that we still have to duplicate some code across the Stock and MoneyMarket classes. While this is true, the solution still solves our initial problem, which is how to easily accommodate new interest calculation algorithms.Yet an even more flexible solution is available, and one that will enable us to be even more dynamic in how we configure our objects with an instance of InterestCalculator.</p>
<p>In Figure 4.7, we have moved the relationship to InterestCalculator up the inheritance hierarchy into our AccountType class. In fact, in this scenario, we are back to using inheritance for reuse, though a bit differently. Our AccountType knows that it needs to calculate interest, but it does not know how actually to do it. Therefore, we see a relationship from AccountType to our InterestCalculator. Because of this relationship, all accounts calculate interest. However, if one of our algorithms is a null object [PLOP98] (that is, it’s an instance of a class that implements the interface and defines the methods, but the methods have no implementation), and we use the null object with the Savings class, we can now state that all of our accounts need to calculate interest. This substantiates our use of implementation inheritance. Because each account calculates it differently, we configure each account with the appropriate InterestCalculator.</p>
<p>Figure 4.7</p>
<p>So how did we fall into the original trap depicted in Figure 4.5? The problem lies within the inheritance relationship. Inheritance can be thought of as a generalization over a specialization relationship—that is, a class higher in the inheritance hierarchy is a more general version of those inherited from it. In other words, any ancestor class is a partial descriptor that should define some default characteristics that will be applicable to any class inherited from it. Violating this convention almost always results in the situation described previously. In fact, any time we have to override default behavior defined in an ancestor class, we are saying that the ancestor class is not a more general version of all of its descendents but actually contains descriptor characteristics that make it too specialized to serve as the ancestor of the class in question. Therefore, if we choose to define default behavior on an ancestor, it should be general enough to apply to all of its descendents.</p>
<p>In practice, CRP is applied a bit differently. In fact, it’s not uncommon to define a default behavior in an ancestor class. However, we should still accommodate CRP in our relationships. This is easy to see in Figure 4.6. We could have easily defined default behavior in our calcuateInterest method on the AccountType class. We still have the flexibility, using CRP, to alter the behaviors of any of our AccountType classes because of the relationship to InterestCalculator. In this situation, we may even choose to create a null op InterestCalculator class that our Checking class uses. This way, we even accommodate the likelihood that Savings accounts can someday calculate interest. We have ultimate flexibility.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.kirkk.com/modularity/2009/12/solid-principles-of-class-design/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>External Configuration</title>
		<link>http://www.kirkk.com/modularity/2009/12/external-configuration/</link>
		<comments>http://www.kirkk.com/modularity/2009/12/external-configuration/#comments</comments>
		<pubDate>Mon, 28 Dec 2009 20:22:54 +0000</pubDate>
		<dc:creator>kirk knoernschild</dc:creator>
				<category><![CDATA[Part 2]]></category>
		<category><![CDATA[Usability Pattern]]></category>

		<guid isPermaLink="false">http://www.kirkk.com/modularity/?p=378</guid>
		<description><![CDATA[Statement
Modules should be externally configurable.
Description
The ability to configure a module to it&#8217;s usage context increases our ability to reuse the module across contexts. Figure 1 illustrates External Configuration.

Figure 1: External Configuration
Implementation Variations
Different configuration files can be used for different contexts. The configuration file can be included in the module or included in a separate module, [...]]]></description>
			<content:encoded><![CDATA[<h2>Statement</h2>
<p>Modules should be externally configurable.</p>
<h2>Description</h2>
<p>The ability to configure a module to it&#8217;s usage context increases our ability to reuse the module across contexts. Figure 1 illustrates External Configuration.</p>
<p style="text-align: center;"><img class="aligncenter size-full wp-image-381" style="border: 0pt none;" title="ExternalConfiguration" src="http://www.kirkk.com/modularity/wp-content/uploads/2009/12/ExternalConfiguration.jpg" alt="ExternalConfiguration" width="557" height="99" /></p>
<p><strong>Figure 1: External Configuration</strong></p>
<h2>Implementation Variations</h2>
<p>Different configuration files can be used for different contexts. The configuration file can be included in the module or included in a separate module, depending on the flexibility desired. Figure 2 illustrates a configuration file that is not deployed with the module.</p>
<p style="text-align: center;"><img class="aligncenter size-full wp-image-386" style="border: 0pt none;" title="ExternalConfiguration2" src="http://www.kirkk.com/modularity/wp-content/uploads/2009/12/ExternalConfiguration2.jpg" alt="ExternalConfiguration2" width="557" height="177" /></p>
<p style="text-align: center;"><strong>Figure 2: External Configuration File</strong></p>
<p>A flexible alternative is to provide a default configuration file with the module, but allow for the module to be configured with an alternative configuration file.</p>
<h2>Consequences</h2>
<h2>Sample Code</h2>
<p>Show example using Spring to configure a module with a uid/pwd combination.</p>
<h2>Wrapping Up</h2>
]]></content:encoded>
			<wfw:commentRss>http://www.kirkk.com/modularity/2009/12/external-configuration/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Module Facade</title>
		<link>http://www.kirkk.com/modularity/2009/12/module-facade/</link>
		<comments>http://www.kirkk.com/modularity/2009/12/module-facade/#comments</comments>
		<pubDate>Mon, 28 Dec 2009 20:08:52 +0000</pubDate>
		<dc:creator>kirk knoernschild</dc:creator>
				<category><![CDATA[Part 2]]></category>
		<category><![CDATA[Usability Pattern]]></category>

		<guid isPermaLink="false">http://www.kirkk.com/modularity/?p=373</guid>
		<description><![CDATA[Statement
Create a facade serving as a coarse-grained entry point to the modules underlying implementation.
Description
Often times, configuring fine-grained modules can be a burden, especially when multiple fine-grained modules are typically used in conjunction but forces prevent module designers from combining the fine-grained module into a single coarse-grained entity. In these situations, a module facade can be [...]]]></description>
			<content:encoded><![CDATA[<h2>Statement</h2>
<p>Create a facade serving as a coarse-grained entry point to the modules underlying implementation.</p>
<h2>Description</h2>
<p>Often times, configuring fine-grained modules can be a burden, especially when multiple fine-grained modules are typically used in conjunction but forces prevent module designers from combining the fine-grained module into a single coarse-grained entity. In these situations, a module facade can be used to expose a subset of the functionality contained within a group of fine-grained modules. A module facade allows a group of fine-grained modules to operate as a coarse-grained module. Figure 1 illustrates a Module Facade.</p>
<p style="text-align: center;"><img class="aligncenter size-full wp-image-374" style="border: 0pt none;" title="ModuleFacade" src="http://www.kirkk.com/modularity/wp-content/uploads/2009/12/ModuleFacade.jpg" alt="ModuleFacade" width="699" height="572" /></p>
<p style="text-align: center;"><strong>Figure 1: Module Facade</strong></p>
<h2>Implementation Variations</h2>
<p>The module facade can configure the fine-grained modules.</p>
<p>Module facade can also act as a mediator to help break dependencies between modules. This is quite similar to escalation.</p>
<h2>Consequences</h2>
<p>All fine-grained modules must be deployed whenever the coarse-grained module is deployed.</p>
<h2>Sample Code</h2>
<h2>Wrapping Up</h2>
]]></content:encoded>
			<wfw:commentRss>http://www.kirkk.com/modularity/2009/12/module-facade/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Colocate Exceptions</title>
		<link>http://www.kirkk.com/modularity/2009/12/colocate-exceptions/</link>
		<comments>http://www.kirkk.com/modularity/2009/12/colocate-exceptions/#comments</comments>
		<pubDate>Mon, 28 Dec 2009 19:51:32 +0000</pubDate>
		<dc:creator>kirk knoernschild</dc:creator>
				<category><![CDATA[Dependency Pattern]]></category>
		<category><![CDATA[Part 2]]></category>

		<guid isPermaLink="false">http://www.kirkk.com/modularity/?p=367</guid>
		<description><![CDATA[Statement
Exceptions should be close to the class or interface that throw them.
Description
Sadly, dealing with exceptions in enterprise software systems is often an afterthought. But allocation of exceptions to modules has significant implications on the modularity, and more specifically the dependencies between modules, within our software system. Placing the exception close to a class that catches [...]]]></description>
			<content:encoded><![CDATA[<h2>Statement</h2>
<p>Exceptions should be close to the class or interface that throw them.</p>
<h2>Description</h2>
<p>Sadly, dealing with exceptions in enterprise software systems is often an afterthought. But allocation of exceptions to modules has significant implications on the modularity, and more specifically the dependencies between modules, within our software system. Placing the exception close to a class that catches it will often cause a cyclic dependency between the module containing the class that throws the exception and the module containing the class that catches the exception. Exceptions should always be placed in a module closer to the class that throws the exception than a module closer to the class that catches the exception. Figure 1 illustrates this scenario.</p>
<p style="text-align: center;"><img class="aligncenter size-full wp-image-369" style="border: 0pt none;" title="ColocateExceptions" src="http://www.kirkk.com/modularity/wp-content/uploads/2009/12/ColocateExceptions.jpg" alt="ColocateExceptions" width="557" height="225" /></p>
<p style="text-align: center;"><strong>Figure 1: Colocate Exceptions</strong></p>
<p style="text-align: center;">
<h2>Implementation Variations</h2>
<p>Whereas separate abstractions says that interfaces should be close to the classes that use them, exceptions should be close to the class that throws them.</p>
<p>If multiple classes from separate modules throw the same exception, the demotion should be used to manage the dependencies between the two modules.</p>
<p>Similar to separate abstractions &#8211; that is where we place the interface.</p>
<h2>Consequences</h2>
<h2>Sample Code</h2>
<h2>Wrapping Up</h2>
]]></content:encoded>
			<wfw:commentRss>http://www.kirkk.com/modularity/2009/12/colocate-exceptions/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Container Independence</title>
		<link>http://www.kirkk.com/modularity/2009/12/container-independence/</link>
		<comments>http://www.kirkk.com/modularity/2009/12/container-independence/#comments</comments>
		<pubDate>Mon, 28 Dec 2009 19:28:50 +0000</pubDate>
		<dc:creator>kirk knoernschild</dc:creator>
				<category><![CDATA[Dependency Pattern]]></category>
		<category><![CDATA[Part 2]]></category>

		<guid isPermaLink="false">http://www.kirkk.com/modularity/?p=355</guid>
		<description><![CDATA[Statement
Modules should be independent of the runtime container.
Description
Modules with excessive runtime container dependencies are heavyweight modules that cannot execute outside the confines of the runtime container. A good example of a heavyweight technology is Enterprise JavaBeans (EJB), and the meteoric rise in popularity of lighter weight frameworks, such as Spring, are the direct result of [...]]]></description>
			<content:encoded><![CDATA[<h2>Statement</h2>
<p>Modules should be independent of the runtime container.</p>
<h2>Description</h2>
<p>Modules with excessive runtime container dependencies are heavyweight modules that cannot execute outside the confines of the runtime container. A good example of a heavyweight technology is Enterprise JavaBeans (EJB), and the meteoric rise in popularity of lighter weight frameworks, such as Spring, are the direct result of the shortcomings of heavyweight technologies.</p>
<p>Over time, we&#8217;ve come to realize that these container dependencies should be abstracted away. Container Independence is leveraged to ensure a module is portable across containers. Figure 1 illustrates how the client.jar module is made independent of the container through the use of the clientconfig.xml file. The Client class will have no dependencies on the modularity frameworks APIs.</p>
<p style="text-align: center;"><img class="aligncenter size-full wp-image-383" style="border: 0pt none;" title="ContainerIndependence" src="http://www.kirkk.com/modularity/wp-content/uploads/2009/12/ContainerIndependence.jpg" alt="ContainerIndependence" width="557" height="225" /></p>
<p style="text-align: center;"><strong>Figure 1: Container Independence</strong></p>
<h2>Implementation Variations</h2>
<p>External configuration can be used to configure a module so that it operates correctly in a specific runtime environment. In these situations, External Configuration is a pattern that is used to achieve Container Independence since the configuration dependencies are moved to an external configuration file. A superceding framework then manages module configuration. However, there are subtle differences between External Configuration and Container Independence that validates the pattern individuality. External configuration is used to configure a module so that it can be reused across contexts, which may have little to do with container dependence.</p>
<p>For instance, configuring a module with a userid and password combination so that it can be used to access different database instances is an example of external configuration, not container independence. While poor practice, hardcoding the userid and password combination wouldn&#8217;t create dependencies on any runtime container, though obviously would limit the context in which the module could be reuse.</p>
<p>External configuration is used to configure a module so that it can be used across contexts. Container Independence is leveraged to ensure a module is portable across containers. While there exists overlap in specific use cases, the two are very distinct patterns.</p>
<h2>Consequences</h2>
<h2>Sample Code</h2>
<p>Show example using Spring DM.</p>
<h2>Wrapping Up</h2>
]]></content:encoded>
			<wfw:commentRss>http://www.kirkk.com/modularity/2009/12/container-independence/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Levelize Modules</title>
		<link>http://www.kirkk.com/modularity/2009/12/levelize-modules/</link>
		<comments>http://www.kirkk.com/modularity/2009/12/levelize-modules/#comments</comments>
		<pubDate>Sun, 27 Dec 2009 18:10:25 +0000</pubDate>
		<dc:creator>kirk knoernschild</dc:creator>
				<category><![CDATA[Dependency Pattern]]></category>
		<category><![CDATA[Part 2]]></category>

		<guid isPermaLink="false">http://www.kirkk.com/modularity/?p=218</guid>
		<description><![CDATA[Statement
Module relationships should be levelized.
Description
Levelized modules demands that module relationships be acyclic. Any cycles in module relationships therefore prevents levelization. There is a close relationship between levelized modules and physical layers, though the two are not the same. Physical layers aims to create one or more modules that are functionally equivalent to the typical layers [...]]]></description>
			<content:encoded><![CDATA[<h2>Statement</h2>
<p>Module relationships should be levelized.</p>
<h2>Description</h2>
<p>Levelized modules demands that module relationships be acyclic. Any cycles in module relationships therefore prevents levelization. There is a close relationship between levelized modules and physical layers, though the two are not the same. Physical layers aims to create one or more modules that are functionally equivalent to the typical layers composing an application. Levelized modules are more fine-grained than physical layers. While a typical software system may have only three or four layers, within each layer might exist multiple levels.</p>
<p>To levelize modules relationships, do the following:</p>
<ul>
<li>External modules are assigned level zero.</li>
<li>Modules dependent only on level zero modules are assigned level one.</li>
<li>Modules dependent on level one are assigned level two.</li>
<li>Modules dependent on level <em>n</em> are assigned level <em>n + 1</em>.</li>
</ul>
<p>Figure 1 shows levelized modules. Even though the topclient.jar module is dependent on client.jar, a Level 1 module, topclient.jar is also dependent on the midlevel.jar module, which is a Level 2 module. Because of this, topclient.jar module is a Level 3 module. More generally, if a module is dependent on an <em>n &#8211; 1</em> leve module, the module is an <em>n</em> level module, even if it&#8217;s also dependent on modules lower in the level hierarchy.</p>
<p style="text-align: center;"><img class="aligncenter size-full wp-image-343" style="border: 0pt none;" title="LevelizedModules" src="http://www.kirkk.com/modularity/wp-content/uploads/2009/12/LevelizedModules.jpg" alt="LevelizedModules" width="468" height="468" /></p>
<p style="text-align: center;">
<p style="text-align: center;"><strong>Figure 1: Levelized Modules</strong></p>
<h2>Implementation Variations</h2>
<p>Architectural layers have to do with responsibilities. Levels have to do with understanding the system structure.</p>
<p>Levelizing modules requires that module relationships are acyclic. Assuming, that module relationships are acyclic, the modules can be levelized to help better keep track of your physical layers.</p>
<p>Levels will typically not equate to layers within an application. Typically, we&#8217;ll have more levels than layers.</p>
<p>Excessive dependencies in lower level modules have the greatest capacity to increase overall cost of maintaining a system.</p>
<p>Likewise, coarse grained modules at lower levels of the system have a significant impact on the ability to easily reuse these modules. In general, lower level modules should have fewer outgoing dependencies and more incoming dependencies. Likewise, lower level modules should also be finer grained and lighter weight than higher level modules. This concept spans layers, as well. The lowest level module in any particular layer should adhere to these general guidelines.</p>
<p>Should you allow relationships that span levels. This is an architectural decision, and a decision that is similar to deciding if you should enforce strict layers are relaxed layers.</p>
<p>Relaxed versus strict levelization. Enforcing strict levelization can be cumbersome, since you&#8217;ll be forced to</p>
<p>How about a level 2 presentation module? Or a level 5 data access module? Offers a completely different view of your system structure and how the modules can be used (reused).</p>
<h2>Consequences</h2>
<p>If you levelize your components, you can perform a LevelizedBuild.</p>
<p>Many other patterns are used to levelize module and enforce the levelization.</p>
<p>Improves testability of the system (ie. Test Module).</p>
<p>Improves ability to understand the system structure. And the ability to extract and understand the module relationships in a large software system allows us to efficiently and accurately verify throughout the development lifecycle that these dependencies are consistent with our overall architectural vision.</p>
<p>For example, reusing a level 3 module comes with the implicit knowledge that one or more level 2 and one or more level 1 modules must also be included in the application.</p>
<h2>Sample</h2>
<p>As mentioned, levelizing modules is slightly different than physical layers. Figure 2 illustrates this difference. As can be seen here, the levels don&#8217;t necessarily coincide with layers. At least, a single layer isn&#8217;t necessarily confined to contain a specific set of levels. The billpayutils.jar module is in the control layer based on the set of responsibilities it provides. However, it&#8217;s lack of dependence on any level 3 or level 4 modules in the domain layer Even though the billpayutils.jar module is in the control layer make it a level 2 component because it&#8217;s only dependency is on the level 1 dbutils.jar module.</p>
<p style="text-align: center;"><img class="aligncenter size-full wp-image-572" style="border: 0pt none;" title="LevelizedWithLayers" src="http://www.kirkk.com/modularity/wp-content/uploads/2009/12/LevelizedWithLayers1.jpg" alt="LevelizedWithLayers" width="703" height="640" /></p>
<p style="text-align: center;">
<p style="text-align: center;">
<p style="text-align: center;"><strong>Figure 2: Levelized Modules and Physical Layers</strong></p>
<h2>Wrapping Up</h2>
]]></content:encoded>
			<wfw:commentRss>http://www.kirkk.com/modularity/2009/12/levelize-modules/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Cohesive Modules</title>
		<link>http://www.kirkk.com/modularity/2009/12/cohesive-modules/</link>
		<comments>http://www.kirkk.com/modularity/2009/12/cohesive-modules/#comments</comments>
		<pubDate>Wed, 23 Dec 2009 02:11:24 +0000</pubDate>
		<dc:creator>kirk knoernschild</dc:creator>
				<category><![CDATA[Base Pattern]]></category>
		<category><![CDATA[Part 2]]></category>

		<guid isPermaLink="false">http://www.kirkk.com/modularity/?p=310</guid>
		<description><![CDATA[Statement
Module behavior should serve a singular purpose.
Description
Cohesion is a measure of how closely related and focused the various responsibilities of a module are. In the worst case scenario, little emphasis is placed on the allocation of classes to modules. Instead, modules are assembled at random, and the likelihood that modules suffer from lack of cohesion [...]]]></description>
			<content:encoded><![CDATA[<h2>Statement</h2>
<p>Module behavior should serve a singular purpose.</p>
<h2>Description</h2>
<p>Cohesion is a measure of how closely related and focused the various responsibilities of a module are. In the worst case scenario, little emphasis is placed on the allocation of classes to modules. Instead, modules are assembled at random, and the likelihood that modules suffer from lack of cohesion is high. In the best case scenario, modules exhibit high degrees of functional cohesion and the entities composing the module each work in conjunction to fulfill module behavior.</p>
<p>In general, cohesion is a qualitative measurement that is difficult to measure. Instead, we typically refer to a software module as either possessing high cohesion or low cohesion. Modules with higher degrees of cohesion are preferred. There are key difficulties that arise when modules suffer from low cohesion, including the inability to understand the software system and difficulty maintaining the software system.</p>
<p>Reusing modules that lack cohesion is also difficult. Module consumers rarely need all of the random behaviors provided by modules lacking cohesion, and the random behaviors often increase dependencies on other modules. In general, modules that lack cohesion degrade the overall quality of a software system&#8217;s architecture.</p>
<h2>Implementation Variations</h2>
<p>There are two key elements that affect module cohesion. These follow:</p>
<ul>
<li>The rate at which the software entities within a module change.</li>
<li>The likelihood that the software entities within a module are reused together.</li>
</ul>
<p>Based on these statements, it&#8217;s easy to draw the following conclusion:</p>
<ul>
<li>Classes which change at different rates belong in separate modules.</li>
<li>Classes that change at the same rate belong in the same module.</li>
<li>Classes not reused together belong in separate modules.</li>
<li>Classes reused together belong in the same module.</li>
</ul>
<p>Unfortunately, this simple logic is flawed because it doesn&#8217;t consider the intricate relation between rate of change, reuse, and the natural shifts that occur throughout the development lifecycle. It&#8217;s possible, even likely, that classes change at different rates but are reused together, or that classes change at the same rate but are rarely reused together. Indeed, there is a tension between rate of change and reuse, and we must consider the following combinations.</p>
<ul>
<li>Classes within a module that change at the same rate and are reused together.</li>
<li>Classes within a module that change at a different rate and are reused together.</li>
<li>Classes within a module that change at the same rate and are not reused together.</li>
<li>Classes within a module that change at a different rate and are not reused together.</li>
</ul>
<p>The first and fourth scenarios are the easiest to accommodate. When classes change at the same rate and are reused together, it&#8217;s logical that they belong in the same module. Likewise, classes that change at different rates and are not reused together belong in separate modules. The final two scenarios, which tend to be most common, are also the most challenging.</p>
<p>Fortunately, the natural shifts that occur throughout the development lifecycle provide insight to dealing with the second and third scenarios, and encourage us to emphasize one of these aspects more than the other. Early in the development lifecycle, when the system is volatile and change is rampant, packaging the classes based on rate of change should supersede packaging based on reuse. As the system stabilizes, we should focus on packaging the classes based on reuse since the rate of change is much less.</p>
<h2>Consequences</h2>
<p>Early in the development lifecycle, when change is rampant, we are encouraged to package classes into more coarse-grained module. This is logical. Because change is rampant and widespread, packaging into coarse-grained modules means less module management as change occurs. We don&#8217;t have to worry as much about managing dependencies between modules. Unfortunately, this can lead to dire consequences if not dealt with on an ongoing basis. Failure to refactor the modules as the system stabilizes results in a software system composed of coarse-grained modules.</p>
<p>The ramifications of coarse-grained modules are discussed in Chapter 6, Section 6.1. Coarse-grained modules make the modules easier to use, but the increased ease of use comes at the price of reusability. It&#8217;s vital to recognize that shifts will occur throughout development As the rate of change lessens, it&#8217;s imperative to turn our attention toward the cohesive properties of the modules that affect reuse.</p>
<h2>Sample</h2>
<p>Figure 1 illustrates the initial version of our system, where Bill instances are routed to an appropriate place so they can be handled (ie., rejected or paid). Unfortunately, the bill.jar module lacks cohesion, since the Bill and Router instances are each bundled and deployed in that module. The lack of cohesion affects reuse, as we cannot reuse Bill without the Router nor reuse the Router to handle other types of entites that might require routing.</p>
<p style="text-align: center;"><img class="aligncenter size-full wp-image-535" style="border: 0pt none;" title="CohesiveModulesv1" src="http://www.kirkk.com/modularity/wp-content/uploads/2009/12/CohesiveModulesv12.jpg" alt="CohesiveModulesv1" width="582" height="173" /></p>
<p style="text-align: center;"><strong>Figure 1: Module Lacking Cohesion</strong></p>
<p style="text-align: left;">The code for the Bill class is shown in Listing 1. As can be seen, a Router is passed to the Bill constructor, which is used when the Bill&#8217;s route method is called. The Router is an abstract class with an abstract route method on it. The TypeARouter shown in Figure 1 extends the Router and provides an implementation for the route method.</p>
<pre class="brush: java;">package com.extensiblejava.bill;

import java.math.*;
import com.extensiblejava.route.*;

public class Bill {
	private String type;
	private String location;
	private BigDecimal amount;
	private Router router;

	public Bill(String type, String location, BigDecimal amount, Router router) {
		this.type = type;
		this.location = location;
		this.amount = amount;
		this.router = router;
	}
	public String getType() {return this.type;}
	public String getLocation() {return this.location;}
	public BigDecimal getAmount() {return this.amount;}
	public String route() { return this.router.route(this); }
}
}</pre>
<p style="text-align: center;"><strong>Listing 1: The Bill Class</strong></p>
<p style="text-align: left; "><strong></strong>To increase cohesion of the bill.jar module, routing functionality can be moved to it&#8217;s own module, as shown in Figure 2.</p>
<p style="text-align: center; "><img class="aligncenter size-full wp-image-538" style="border: 0pt none;" title="CohesiveModulesv2" src="http://www.kirkk.com/modularity/wp-content/uploads/2009/12/CohesiveModulesv2.jpg" alt="CohesiveModulesv2" width="530" height="191" /><strong></strong></p>
<p style="text-align: center; "><strong>Figure 2: Cohesive Bill and Route Modules</strong></p>
<p>The only change required to bundle the functionality separately was to modify the build script. Previously, the build bundled all classes into a single module. The modified script, shown in Listing 2 with the lines responsible for creating the bundles highlight, illustrates how the functionality is allocated to the separate bundles.</p>
<pre class="brush: xml; highlight: [2,3,4];">
&lt;target name=&quot;dist&quot; depends=&quot;compile&quot;&gt;
   &lt;jar jarfile=&quot;${dist}/bill.jar&quot; basedir=&quot;${bin}&quot; includes=&quot;com/extensiblejava/bill/**&quot;/&gt;
   &lt;jar jarfile=&quot;${dist}/route.jar&quot; basedir=&quot;${bin}&quot; includes=&quot;com/extensiblejava/route/**&quot;/&gt;
   &lt;jar jarfile=&quot;${dist}/bill-test.jar&quot; basedir=&quot;${bin}&quot; includes=&quot;com/extensiblejava/test/**&quot;/&gt;
   &lt;junit printsummary=&quot;yes&quot; haltonfailure=&quot;yes&quot;&gt;
      &lt;classpath&gt;
         &lt;pathelement path=&quot;${dist}/route.jar&quot;/&gt;
         &lt;pathelement path=&quot;${dist}/bill.jar&quot;/&gt;
         &lt;pathelement path=&quot;${dist}/bill-test.jar&quot;/&gt;
         &lt;pathelement path=&quot;${lib}/junit.jar&quot;/&gt;
      &lt;/classpath&gt;
      &lt;test name=&quot;com.extensiblejava.test.RouterTest&quot; outfile=&quot;junitresults&quot;&gt;
         &lt;formatter type=&quot;plain&quot;/&gt;
      &lt;/test&gt;
   &lt;/junit&gt;
&lt;/target&gt;
</pre>
<p style="text-align: center;"><strong>Listing 2: Modified Build Script</strong></p>
<p style="text-align: left;">Unfortunately, there is still a glaring problem with the module structure illustrated in Figure 2. A cyclic dependency exists between the bill.jar and route.jar modules. Applying the AcyclicRelationships pattern will help eliminate the cyclic dependency. When applying the AcyclicRelationships pattern to break the cycle between the bill.jar and route.jar modules, we also applied the SeparateAbstractions pattern. Otherwise, the cycle would have persisted. Upon doing so, the final module structure would resemble what&#8217;s illustrated in Figure 3. Note the addition of the Routable interface, which is implemented by Bill. It&#8217;s the Routable interface, and it&#8217;s placement in the route.jar module that eliminates the cycle.</p>
<p style="text-align: center;"><img class="aligncenter size-full wp-image-541" style="border: 0pt none;" title="CohesiveModulesv3" src="http://www.kirkk.com/modularity/wp-content/uploads/2009/12/CohesiveModulesv3.jpg" alt="CohesiveModulesv3" width="583" height="323" /></p>
<p style="text-align: center;"><strong>Figure 3: Cohesive Modules with Acyclic Relationships</strong></p>
<h2>Wrapping Up</h2>
<p>Highly cohesive modules are easier to understand, maintain, and reuse. In many cases though, it can be difficult to create cohesive modules early in the development lifecycle, when the team may not have a clear understanding of system behavior. As this insight is gained, the development team should structure the system to ensure highly cohesive modules are available.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.kirkk.com/modularity/2009/12/cohesive-modules/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Implementation Factory</title>
		<link>http://www.kirkk.com/modularity/2009/12/implementation-factory/</link>
		<comments>http://www.kirkk.com/modularity/2009/12/implementation-factory/#comments</comments>
		<pubDate>Wed, 23 Dec 2009 00:53:57 +0000</pubDate>
		<dc:creator>kirk knoernschild</dc:creator>
				<category><![CDATA[Extensibility Pattern]]></category>
		<category><![CDATA[Part 2]]></category>

		<guid isPermaLink="false">http://www.kirkk.com/modularity/?p=297</guid>
		<description><![CDATA[Statement
Use factories to create a modules implementation classes.
Description
One of the challenges we face with abstract coupling is creation of the implementation class. A client class cannot create an implementation class if we want the two classes abstractly coupled. Figure 1 illustrates the Implementation Factory pattern.


Figure 1: Implementation Factory Pattern
Implementation Variations
Implementation Factory is often used with [...]]]></description>
			<content:encoded><![CDATA[<h2>Statement</h2>
<p>Use factories to create a modules implementation classes.</p>
<h2>Description</h2>
<p>One of the challenges we face with abstract coupling is creation of the implementation class. A client class cannot create an implementation class if we want the two classes abstractly coupled. Figure 1 illustrates the Implementation Factory pattern.</p>
<p style="text-align: center;"><img class="aligncenter" style="border: 0pt none;" title="ImplementationFactory" src="http://www.kirkk.com/modularity/wp-content/uploads/2009/12/ImplementationFactory.jpg" alt="ImplementationFactory" width="595" height="301" /></p>
<p style="text-align: center;">
<p style="text-align: center;"><strong>Figure 1: Implementation Factory Pattern</strong></p>
<h2>Implementation Variations</h2>
<p>Implementation Factory is often used with Abstract Module and Separate Abstractions.</p>
<p>Where does the factory live.</p>
<p>What is the factory? Class or framework such as Spring.</p>
<p>Injection or Lookup.</p>
<h2>Consequences</h2>
<h2>Sample Code</h2>
<p style="text-align: center;"><img class="aligncenter size-full wp-image-328" style="border: 0pt none;" title="LoanSampleImplementationFactory" src="http://www.kirkk.com/modularity/wp-content/uploads/2009/12/LoanSampleImplementationFactory.jpg" alt="LoanSampleImplementationFactory" width="976" height="897" /></p>
<p style="text-align: center;"><strong>Figure 1: Implementation Factory using Spring</strong></p>
<p>In abstract modules, we were left wondering how to create the implementation class without referencing the concrete class within the client.jar module.</p>
<h2>Wrapping Up</h2>
]]></content:encoded>
			<wfw:commentRss>http://www.kirkk.com/modularity/2009/12/implementation-factory/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Separate Abstractions</title>
		<link>http://www.kirkk.com/modularity/2009/12/separate-abstractions/</link>
		<comments>http://www.kirkk.com/modularity/2009/12/separate-abstractions/#comments</comments>
		<pubDate>Wed, 23 Dec 2009 00:42:40 +0000</pubDate>
		<dc:creator>kirk knoernschild</dc:creator>
				<category><![CDATA[Extensibility Pattern]]></category>
		<category><![CDATA[Part 2]]></category>

		<guid isPermaLink="false">http://www.kirkk.com/modularity/?p=289</guid>
		<description><![CDATA[Statement
Place abstractions and the classes that implement them in separate modules.
Description
You create an abstract class or interface to help reduce coupling between classes. This offers the ability to create new implementations of the abstraction without impacting clients dependent on that abstraction. In this sense, abstract coupling allows you to add new classes to your system [...]]]></description>
			<content:encoded><![CDATA[<h2>Statement</h2>
<p>Place abstractions and the classes that implement them in separate modules.</p>
<h2>Description</h2>
<p>You create an abstract class or interface to help reduce coupling between classes. This offers the ability to create new implementations of the abstraction without impacting clients dependent on that abstraction. In this sense, abstract coupling allows you to add new classes to your system without modifying existing classes, and it does so by reducing the dependency relationship between classes.</p>
<p>But coupling classes abstractly does not help reduce the dependency structure between components, especially if the abstraction and the classes that realize the abstraction reside in the same component. So while abstract coupling allows you to effectively reduce coupling between classes, it does not help to eliminate coupling between components. The abstract modules patterns is a prime example of this, where the client.jar module is still tightly coupled to the service.jar module even though the Client concrete class is not directly coupled to the ServiceImpl class.</p>
<p>The ability to deploy client.jar without service.jar does not exist given the structure in Figure 10.1.1. But what if I have a situation where I need to use client.jar without service.jar, or possibly with a new implementation. Even if I create new implementations of the Service interface, I&#8217;m still required to deploy service.jar with client.jar due to the placement of Service interface. In order to avoid this nasty problem, I can move the Service interface to the client.jar. This still allows me to configure the Client class with the appropriate Service implementation, yet the client.jar is not dependent on the service.jar module. In fact, the direction of the relationship has been inversed. Instead of client.jar depending on service.jar, the service.jar is now dependent on client.jar.</p>
<p>By simply changing the placement of classes, I&#8217;ve changed the dependency relationship between my modules. We saw an example of how module relationships can be inverted in the Module Relationships pattern Sample Code section. But inverting the dependency relationship may not always be what we&#8217;re interested in doing. Certainly, we know have the ability to use client.jar without service.jar, but can no longer use service.jar without client.jar. If we need the ability to use both client and service independent of each other, I need a different structure that accommodates this need. When this situation arises, the Separate Abstraction pattern can be used.</p>
<p>Fortunately, it&#8217;s as easy as moving the Service interface to a new component that both client.jar and service.jar modules are dependent upon. Figure 1 illustrates the new structure. In most cases where you take this approach, the new module will be an entirely abstract module. We refer to an abstract module as a specification module.</p>
<p style="text-align: center;"><img class="aligncenter size-full wp-image-290" style="border: 0pt none;" title="SeparateAbstractionsPattern" src="http://www.kirkk.com/modularity/wp-content/uploads/2009/12/SeparateAbstractionsPattern.jpg" alt="SeparateAbstractionsPattern" width="557" height="336" /></p>
<p style="text-align: center;"><strong>Figure 1: Separate Abstractions Pattern</strong></p>
<h2>Implementation Variations</h2>
<p>SeparateAbstractions solves two different problems using a common technique. If there are two modules involved in the relationship, by separating the abstraction from the implementation, you are inverting the relationship between the two components. Using an ImplementationFactory will help maintain this separation. When more than three components are involved, SeparateAbstractions allows you to physically decouple two components where no relationship exists between the two components in either direction.</p>
<h2>Consequences</h2>
<p>Invariably more complex structure to manage.</p>
<p>The two key ingredients when you SeparateAbstractions is deciding where you should place the abstraction and where you should place the implementation. Since there could be many different implementations, they key to making this decision is figuring out your dependencies keeping in mind that the components containing the implementation will be dependent on the component containing the abstraction.</p>
<p>Since all implementations will only have a single abstraction, the placement of the abstraction is key to creating the component relationships that you want. In general, you want to keep the abstraction as close as possible to the classes that depend upon it. Here are some general guidelines to making this happen.</p>
<ul>
<li>If only a single class, or set of classes in the same package, rely upon the abstraction, then place the abstraction in that package.</li>
<li>If a set of classes that span multiple packages all rely upon the abstraction, but all packages exist within the same component, place the abstraction in a separate package in that component.</li>
<li>If a set of classes that span multiple components all rely upon the abstraction, and you want to keep each of those components independent of each other, then place the abstraction in separate component.</li>
</ul>
<p>SeparateAbstractions allows you to eliminate a module relationship. The module depending on the abstraction needs to be injected with an implementation or have some way to lookup the implementation at run-time. Creation of the appropriate implementation is another important consideration. If a lookup approach is taken, the lookup mechanism should use reflection to avoid introducing the dependency. If injection is used, you&#8217;ll need a separate component that performs the creation. SeparateAbstractions is concerned with flexibility, but comes at the price of complexity.</p>
<p>When assembling components, you may find that two otherwise independent components share common state. You&#8217;ll likely want to avoid having each component initialize and manage that state separately due to overhead, and possibly unreliable processing. Doing so also incurs  and unneccessary performance burden. If the state that each component relies upon is simply data that each requires to perform some processing, then it&#8217;s fairly easy to populate a bean defined by each component and pass the bean into the class requiring that data. But in situations involving more than state, each component may need to call back on an external entity. In this case, you cannot put the functionality on the bean since the bean would then require the ability to talk to the component. In order to accommodate this scenario, each component would need to define it&#8217;s own abstraction (the approach taken in Figure 10.1.2) or each component would need to depend on another component containing the abstraction (the approach taken in Figure 10.1.3).</p>
<h2>Sample Code</h2>
<p>In Abstract Modules, we depend upon the abstract elements of a module. In Implementation Factory, we used a factory to create the implementation class. Now, by moving the abstract class to a separate module, we can completely eliminate the relationship between the two modules.</p>
<p>Inverting the relationships allows us to deploy the customer.jar module independent of the billing.jar module. Again, it’s all about need. But I’d like to explore another option based on another important need – the ability to test and deploy modules independently. Before inverting the relationships, I am able to test and deploy the billing.jar module independently. After inverting the relationships, I can test and deploy the customer.jar module independently. But what if I want to test or deploy both modules independently? To do this, I need to completely eliminate the relationship altogether.</p>
<p>As it turns out, because I’ve got a pretty flexible class structure after I inverted the relationships (lot’s of abstract coupling), I can do this by simply bundling the two interfaces – Bill and DiscountCalculator – into a separate module. No other coding changes required. I start by moving them to a new package, which we’ll case base. (<a href="http://code.google.com/p/kcode/source/browse/#svn/trunk/edcie/eliminated/src/com/kirkk/base">moving them to a new package called base</a>). Then, I modify my build script (<a href="http://code.google.com/p/kcode/source/browse/trunk/edcie/eliminated/build.xml#34">modify my build script</a>) to bundle these two interfaces into a separate base.jar module, and we have successfully eliminated the relatinonship between the bill.jar and cust.jar modules. This is illustrated below in Figure 1.</p>
<p style="text-align: center;"><img class="aligncenter size-large wp-image-330" style="border: 0pt none;" title="LoanSampleSeparateAbstractions" src="http://www.kirkk.com/modularity/wp-content/uploads/2009/12/LoanSampleSeparateAbstractions-1024x789.jpg" alt="LoanSampleSeparateAbstractions" width="1024" height="789" /></p>
<p style="text-align: center;">
<p style="text-align: center;">
<p style="text-align: center;">
<p style="text-align: center;"><strong>Figure 1: Separating Abstractions to another Module</strong></p>
<h2>Wrapping Up</h2>
]]></content:encoded>
			<wfw:commentRss>http://www.kirkk.com/modularity/2009/12/separate-abstractions/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
