<?xml version="1.0" encoding="UTF-8" ?>
<?xml-stylesheet type="text/xsl" href="http://devlicio.us/utility/FeedStylesheets/rss.xsl" media="screen"?><rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/" xmlns:wfw="http://wellformedweb.org/CommentAPI/"><channel><title>Billy McCafferty : Patterns</title><link>http://devlicio.us/blogs/billy_mccafferty/archive/tags/Patterns/default.aspx</link><description>Tags: Patterns</description><dc:language>en</dc:language><generator>CommunityServer 2008.5 SP1 (Build: 31106.3070)</generator><item><title>Checklist for Developing Message-Based Systems</title><link>http://devlicio.us/blogs/billy_mccafferty/archive/2010/03/23/checklist-for-developing-message-based-systems.aspx</link><pubDate>Tue, 23 Mar 2010 21:22:00 GMT</pubDate><guid isPermaLink="false">40756a8b-6212-4073-9d98-6c26781577de:56236</guid><dc:creator>Billy McCafferty</dc:creator><slash:comments>3</slash:comments><description>&lt;p&gt;Even when developing the most basic CRUD application, we ask ourselves a number of questions - whether we realize it or not - during the initial phases of development concerning the architecture and construction of the project.&amp;nbsp; Where will the data be persisted?&amp;nbsp; What mechanism will be used to communicate with the database?&amp;nbsp; How will data from the database be transformed into business objects?&amp;nbsp; Should separated interfaces and dependency injection be employed to maintain a clean separation of concerns between application logic and data access objects?&amp;nbsp; What UI components will be leveraged to speed development of the UI layer?&amp;nbsp; When developing message-based systems (see &lt;a href="http://devlicio.us/blogs/billy_mccafferty/archive/2010/03/01/message-based-systems-for-maintainable-asynchronous-development.aspx"&gt;Message-Based Systems for Maintainable, Asynchronous Development&lt;/a&gt; for an introduction) it&amp;#39;s immensely helpful to formalize such questions about how the systems will be designed and developed.&amp;nbsp; Creating a checklist of such items to decide upon, and formalizing answers for the application context, helps to:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Standardize how components (applications participating in the message-based system) will communicate with the messaging middleware;&lt;/li&gt;
&lt;li&gt;Provide architectural guidance throughout project development concerning how components will leverage message end-points;&lt;/li&gt;
&lt;li&gt;Define the data model that will be used for sending commands and exchanging data among components;&lt;/li&gt;
&lt;li&gt;Assist new developers on the team with getting up to speed with maintaining and extending the message-based system; and&lt;/li&gt;
&lt;li&gt;Support consistency (and predictable maintainability) amongst the components of the system.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;This post provides an addendum, if you will (I&amp;#39;m sure you will), to &lt;a href="http://devlicio.us/blogs/billy_mccafferty/archive/2010/03/01/message-based-systems-for-maintainable-asynchronous-development.aspx"&gt;Message-Based Systems for Maintainable, Asynchronous Development&lt;/a&gt;&amp;nbsp;for complementing the article with a checklist of questions and architectural topics that should be discussed, decided upon, and/or spiked before beginning development of your budding message-based system. &amp;nbsp;Accordingly, this does not describe a methodology for developing message-based systems, but simply a checklist of topics which should be taken into consideration before development begins.&amp;nbsp; Many of the checklist items below serve as good starting points for team discussion and for the development of architectural spikes for demonstrating implementation details.&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;Messaging Middleware&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;What messaging middleware solution will form the background of the message-based system?&lt;/li&gt;
&lt;li&gt;How are channels addressed in the selected middleware? &amp;nbsp;(E.g., as a string or as a port number?)&lt;/li&gt;
&lt;li&gt;How does the nomenclature of the middleware match up to standard elements of message-based systems and design patterns? &amp;nbsp;E.g., in &lt;a href="http://www.ros.org/wiki/"&gt;Robot Operating System (ROS&lt;/a&gt;), a channel is called a &amp;quot;topic.&amp;quot; &amp;nbsp;Likewise, is their middleware specific nomenclature for elements such as component, publisher, subscriber, point-to-point channel, publish/subscribe channel, message, command message, request-reply message, router, message end-point, and other messaging design patterns?&lt;/li&gt;
&lt;li&gt;What mechanism is available for peeking at messages going over a point-to-point channel?&lt;/li&gt;
&lt;li&gt;What utilities are available for viewing active channels, publishers, and subscribers?&lt;/li&gt;
&lt;li&gt;What other tools does the middleware provide for debugging and observing the messaging system? &amp;nbsp;Will custom utilities need to be developed to autment development and debugging capabilities?&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;strong&gt;Integration with Messaging Middleware&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;How will message end-points publish a messages?&lt;/li&gt;
&lt;li&gt;How will message end-points subscribe to a channel for messages?&lt;/li&gt;
&lt;li&gt;How will message end-points poll a channel?&lt;/li&gt;
&lt;li&gt;What technique will be used to decouple the component (participating application) from the message end-point when sending a message? &amp;nbsp;E.g., dependency injection, separated interface, or other?&lt;/li&gt;
&lt;li&gt;What technique will be used to decouple the component from the message end-point when receiving a message or polling a channel? &amp;nbsp;E.g., callback, separated interface, or other?&lt;/li&gt;
&lt;li&gt;Should exceptions raised by the messaging middleware be wrapped in component specific exceptions for looser coupling? &amp;nbsp;If so, what will be the standard exceptions? &amp;nbsp;Additionally, how will such exceptions be logged and tracked for debugging; e.g., email alerts, logging, exception message channel?&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;strong&gt;Channels and Routing&lt;/strong&gt;&lt;/p&gt;
&lt;div&gt;
&lt;ul&gt;
&lt;li&gt;What channels will be created and what data type should each channel carry?&lt;/li&gt;
&lt;li&gt;Will a hierarchical naming strategy be leveraged for naming and organizing channels? &amp;nbsp;If so, what are the naming conventions for the project?&lt;/li&gt;
&lt;li&gt;Has an invalid message channel been setup with a logger to capture and record invalid messages?&lt;/li&gt;
&lt;li&gt;How should a predictive router be implemented, when needed?&lt;/li&gt;
&lt;li&gt;How should a reactive router (e.g., a message filter) be implemented, when needed?&lt;/li&gt;
&lt;/ul&gt;
&lt;strong&gt;Message Elements&lt;/strong&gt;&lt;strong&gt;&lt;br /&gt;&lt;/strong&gt;
&lt;ul&gt;
&lt;li&gt;What data elements may the header of a message contain and how should each be specified? &amp;nbsp;E.g., return address, message expiration, timestamp, origin, format indicator, etc.&lt;/li&gt;
&lt;li&gt;How should a message identifier and correlation identifier be generated and included in the header?&lt;/li&gt;
&lt;li&gt;What is the messaging data model supported and/or enforced by the messaging middleware? &amp;nbsp;E.g., ROS supports&amp;nbsp;&lt;a href="http://www.ros.org/wiki/msg"&gt;http://www.ros.org/wiki/msg&lt;/a&gt;.&lt;/li&gt;
&lt;li&gt;What canonical data model will be used to imbue message content with domain specific semantic meaning? &amp;nbsp;E.g., &lt;a href="http://en.wikipedia.org/wiki/JAUS"&gt;JAUS&lt;/a&gt;.&lt;/li&gt;
&lt;li&gt;How will message translators and/or message mappers be leveraged for converting between each component&amp;#39;s domain model and the canonical data model?&lt;/li&gt;
&lt;li&gt;How will a command, document, event and request-reply message be composed?&lt;/li&gt;
&lt;/ul&gt;
&lt;strong&gt;Other Topics&lt;/strong&gt;&lt;br /&gt;
&lt;ul&gt;
&lt;li&gt;How will components maintain information that is associated with a correlation identifier?&lt;/li&gt;
&lt;li&gt;Are there existing components which need to interact with the messaging middleware which cannot be modified?&amp;nbsp; If so, how will each communicate with the messaging middleware?&lt;/li&gt;
&lt;li&gt;How will each component participate with the message based system; e.g., as a polling consumer, as an event-driven consumer, as strictly an event publisher, as a combination of these?&lt;/li&gt;
&lt;li&gt;Should exceptions raised by a component participate in a global exception tracking and debugging mechanism?&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;As stated previously, this checklist is not intended to provide a methodology for developing message-based systems, but should serve as a good basis to make sure &amp;quot;T&amp;#39;s are crossed and I&amp;#39;s are dotted&amp;quot; when deciding upon the major architectural aspects and development techniques that will be leveraged throughout the development of your (team&amp;#39;s) message-based system.&lt;/p&gt;
&lt;p&gt;Enjoy!&lt;br /&gt;Billy McCafferty&lt;/p&gt;
&lt;/div&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://devlicio.us/aggbug.aspx?PostID=56236" width="1" height="1"&gt;</description><category domain="http://devlicio.us/blogs/billy_mccafferty/archive/tags/Architecture/default.aspx">Architecture</category><category domain="http://devlicio.us/blogs/billy_mccafferty/archive/tags/Quality+Assurance/default.aspx">Quality Assurance</category><category domain="http://devlicio.us/blogs/billy_mccafferty/archive/tags/Robotics/default.aspx">Robotics</category><category domain="http://devlicio.us/blogs/billy_mccafferty/archive/tags/Patterns/default.aspx">Patterns</category></item><item><title>Message-Based Systems for Maintainable, Asynchronous Development</title><link>http://devlicio.us/blogs/billy_mccafferty/archive/2010/03/01/message-based-systems-for-maintainable-asynchronous-development.aspx</link><pubDate>Tue, 02 Mar 2010 04:22:00 GMT</pubDate><guid isPermaLink="false">40756a8b-6212-4073-9d98-6c26781577de:55589</guid><dc:creator>Billy McCafferty</dc:creator><slash:comments>8</slash:comments><description>&lt;p&gt;&lt;strong&gt;Preface&lt;/strong&gt; (you know it&amp;rsquo;s good if there&amp;#39;s a preface)&lt;/p&gt;
&lt;p&gt;In &lt;a href="http://devlicious.com/blogs/billy_mccafferty/archive/2010/02/03/software-architectural-approaches-for-robotics.aspx"&gt;Architectural Paradigms of Robotic Control&lt;/a&gt;, a number of architectures were reviewed including deliberative, reactive, and hybrid architectures. &amp;nbsp;Each of these exhibit a clean separation of concerns with layering and encapsulation of defined behaviors. &amp;nbsp;When implemented, the various capabilities, such as planners and mobility controllers, are encapsulated into discrete components for better reusability and maintainability. &amp;nbsp;A pivotal aspect &lt;i&gt;not&lt;/i&gt; discussed in the previous article is how the various system layers and components communicate with each other, such as reporting sensor feedback and sending commands to actuator controllers. &amp;nbsp;Effectively resolving this communication challenge is not only important to robotic systems but to many other industries and domains for the successful integration of disparate applications.&lt;/p&gt;
&lt;p&gt;To give credit where credit is due, this article pulls quite heavily&amp;nbsp;from the patterns, taxonomy, and best practices presented in&amp;nbsp;&lt;a href="http://www.amazon.com/Enterprise-Integration-Patterns-Designing-Deploying/dp/0321200683"&gt;Enterprise Integration Patterns&lt;/a&gt;&amp;nbsp;(Hohpe, 2003). &amp;nbsp;This well organized book is chock full of hard learned lessons and solid guidelines for developing maintainable message-based systems. &amp;nbsp;This article should not be seen as an adequate replacement for that book (it&amp;rsquo;s more like cliff notes with a spackling of robotics bias); indeed,&amp;nbsp;&lt;a href="http://www.amazon.com/Enterprise-Integration-Patterns-Designing-Deploying/dp/0321200683"&gt;Enterprise Integration Patterns&lt;/a&gt;&amp;nbsp;should have a prominent place on your bookshelf if you&amp;#39;re developing message-based systems&amp;nbsp;&amp;ndash;&amp;nbsp;so read this post and then browse&amp;nbsp;&lt;a href="http://www.eaipatterns.com/"&gt;http://www.eaipatterns.com/&lt;/a&gt;&amp;nbsp;while waiting for your copy to arrive to delve deeper.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;A Need for Message-Based Systems&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;A few industries in particular, such as finance, healthcare and robotics, are demanding integration of an intimidating number of separate technologies that may be spread across computers, networks, and/or built upon a variety of technological platforms. &amp;nbsp;Not only is this integration tricky, it can come with a significant cost to performance and maintainability if not implemented correctly. &amp;nbsp;Accordingly, a solution is needed which facilitates loosely coupled integration while accommodating the performance demands of the task at hand. &amp;nbsp;Taking a message-oriented approach to inter-application communications is one such way to accommodate these demands in a maintainable manner without sacrificing performance. &amp;nbsp;This article gives an introduction to developing message-based systems using messaging middleware, describes taxonomy for discussing messaging topics and patterns, and includes a number of best practices.&lt;/p&gt;
&lt;p&gt;Before delving further, it&amp;#39;s important to clarify a few terms that will be used frequently:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;i&gt;Messaging Middleware&lt;/i&gt; (aka, a message bus): &amp;nbsp;a 3rd party application which provides messaging infrastructure and capabilities (e.g., &lt;a href="http://www.microsoft.com/windowsserver2003/technologies/msmq/default.mspx"&gt;MSMQ&lt;/a&gt;, &lt;a href="http://msdn.microsoft.com/en-us/library/bb648752.aspx"&gt;MS Concurrency and Coordination Runtime&lt;/a&gt; (CCR), &lt;a href="http://www.ros.org/wiki/"&gt;Robot Operating System&lt;/a&gt; (ROS)),&lt;/li&gt;
&lt;li&gt;&lt;i&gt;Component&lt;/i&gt;: &amp;nbsp;a stand-alone application or piece of executable code which communicates with the messaging middleware,&lt;/li&gt;
&lt;li&gt;&lt;i&gt;Message-based system&lt;/i&gt;: &amp;nbsp;the entirety of the system including all integrated components and the messaging middleware.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;As stated, messaging provides one means of facilitating inter-component communications. &amp;nbsp;But as with any design approach, the project requirements must be carefully considered to determine if messaging is the appropriate mechanism for integration. &amp;nbsp;While messaging is robust and facilitates integration, it also adds complexity and indirection. &amp;nbsp;So before deciding to use messaging as the means of integration, consider all component integration options including (Hohpe, 2003):&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;i&gt;File Transfer&lt;/i&gt;: &amp;nbsp;wherein a component produces files of shared data which other components consume,&lt;/li&gt;
&lt;li&gt;&lt;i&gt;Shared Database&lt;/i&gt;: &amp;nbsp;each component stores and retrieves data from a common database,&lt;/li&gt;
&lt;li&gt;&lt;i&gt;Remote Procedure Invocation&lt;/i&gt;: &amp;nbsp;each component exposes specific procedures to be invoked remotely for exposing behavior and exchanging data,&lt;/li&gt;
&lt;li&gt;&lt;i&gt;Messaging&lt;/i&gt;: &amp;nbsp;each component connects to a common messaging system, using messages to invoke behavior and exchange data.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Determining which integration approach is most suitable to your project&amp;#39;s needs is beyond the scope of this article, focusing instead specifically on messaging. &amp;nbsp;In turn, we&amp;#39;ll review important elements of developing a message-based system including: &amp;nbsp;message channels, messages, message routers, and message endpoints.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Message Channels&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;When a component sends information to another component in a message-based system, it adds the information to a &lt;i&gt;message channel&lt;/i&gt;. &amp;nbsp;The receiving component then retrieves the information from the message channel. &amp;nbsp;Different channels are created for each kind of data to be carried; having a separate channel for each datatype better enables receiving components to know what kind of data will be retrieved from a given channel. &amp;nbsp;For using a channel, each channel is addressable for sending and retrieving messages to/from them. &amp;nbsp;How a channel is addressed varies depending on the messaging middleware being leveraged, but it&amp;#39;s usually a port number or a unique string identifier. &amp;nbsp;As a good practice for keeping channels organized, if string identifiers are available, a hierarchical naming convention may be employed to label channels by type and name; e.g., a channel carrying laser scans might be called &amp;quot;Perception/LaserScans.&amp;quot;&lt;/p&gt;
&lt;p&gt;&lt;img border="0" src="http://devlicious.com/resized-image.ashx/__size/550x0/__key/CommunityServer.Blogs.Components.WeblogFiles/billy_5F00_mccafferty/ChannelTypes.png" style="border:0;float:right;margin-top:6px;margin-bottom:6px;margin-left:2px;margin-right:2px;" alt="" /&gt;There are two basic kinds of message channels:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;i&gt;Point-to-Point Channels&lt;/i&gt; (aka - client/server style): &amp;nbsp;routes messages for components to talk directly with other components; e.g., a remote procedure call to another component. &amp;nbsp;A message over a point-to-point channel only has a single receiver; so while the sender may not necessarily know who the receiver is, the sender can rest assured that the message will only be received by one receiver &amp;ndash; it&amp;rsquo;s a &lt;a href="http://en.wikipedia.org/wiki/FIFO"&gt;FIFO&lt;/a&gt; queue.&lt;/li&gt;
&lt;li&gt;&lt;i&gt;Publish-Subscribe Channels&lt;/i&gt; (aka - broadcast): &amp;nbsp;routes messages for components to publish data and an arbitrary number of components to subscribe to that data. &amp;nbsp;A copy of the message is generated for each subscriber on the channel.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;In addition to channels intended to carry information among components, it is a good practice to setup an &lt;i&gt;invalid message channel&lt;/i&gt;&amp;nbsp;that bad-formed or unreadable messages may be forwarded to for logging and to assist with debugging.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Messages&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;With a function call, a simple parameter or object reference may be passed and retrieved by the invoked method, sharing the same memory space. &amp;nbsp;But when passing data between two processes with separate memory spaces, the data must be packaged into a &amp;quot;message&amp;quot; adhering to an agreed upon format which the receiver will be able to disassemble and understand. &amp;nbsp;The sender of the message passes the message via a message channel. &amp;nbsp;The receiver retrieves the message from the message channel and transforms the message into internal data structures appropriate for the task at hand.&lt;/p&gt;
&lt;p&gt;A message is made up of two parts:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;i&gt;Header&lt;/i&gt;: &amp;nbsp;describes the data being transmitted and details concerning the message itself; e.g., origin, timestamp information, message expiration (if content is time-sensitive), message identifier, correlation identifier, return address, etc., and&lt;/li&gt;
&lt;li&gt;&lt;i&gt;Body&lt;/i&gt;: &amp;nbsp;the data content that the receiver is looking to use.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;When sending a message, the sender intends for the message to be used, or responded to, in a particular way. &amp;nbsp;The intention of the message may be described as being one of the following:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;i&gt;Command Message&lt;/i&gt;: &amp;nbsp;invokes a procedure in another application,&lt;/li&gt;
&lt;li&gt;&lt;i&gt;Document Message&lt;/i&gt;: &amp;nbsp;passes a set of data to another application,&lt;/li&gt;
&lt;li&gt;&lt;i&gt;Event Message&lt;/i&gt;: &amp;nbsp;notifies another application of a change in state, and&lt;/li&gt;
&lt;li&gt;&lt;i&gt;Request-Reply&lt;/i&gt;: &amp;nbsp;requests a reply from another application.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Event messages deserve a bit more discussion. &amp;nbsp;In its simplest form, an event message would simply be informational, letting subscribers know that an event has occurred; e.g., a new laser scan is available. &amp;nbsp;If subscribers would like details concerning the event, they would send a request-reply to the sender of the event to provide further details; e.g., the laser scan details. &amp;nbsp;Alternatively, the event could be a document &lt;i&gt;as&lt;/i&gt;&amp;nbsp;an event to inform subscribers that an event has occurred along with the details of that event; e.g., a new laser scan is available with laser scan details included. &amp;nbsp;The size of the event details and the rapidity in which the event occurs should be considered when deciding between publishing simple event messages and document messages &lt;i&gt;as&lt;/i&gt; events.&lt;/p&gt;
&lt;p&gt;Request-reply messages could also use a bit more describing. &amp;nbsp;A request-reply is usually implemented as two point-to-point channels. &amp;nbsp;The first channel delivers the request as a command message, while the second carries the reply back to the requestor as a document message. &amp;nbsp;To keep the replying component more loosely coupled and reusable, the requestor should include a &lt;i&gt;return address&lt;/i&gt;&amp;nbsp;indicating the channel that the replier should use to publish the reply. &amp;nbsp;After receiving the reply, a challenge for the requestor is to then correlate the reply to the original request. &amp;nbsp;If the requestor is sending a number of requests in succession, it will likely be difficult to keep clear &amp;ndash; if it matters &amp;ndash; which request a reply is associated with. &amp;nbsp;To resolve this, every request may include a unique &lt;i&gt;message identifier&lt;/i&gt;&amp;nbsp;that the replier would then include as a &lt;i&gt;correlation identifier&lt;/i&gt;. &amp;nbsp;(A message could have both a message Id and a correlation Id.) &amp;nbsp;The requestor uses the correlation identifier to &amp;ldquo;jog its memory&amp;rdquo; concerning which request the response is for. &amp;nbsp;But frequently, a request-reply is in context of a particular domain object, such as a terrain map or a bank transaction; but the correlation Id doesn&amp;rsquo;t include such information. &amp;nbsp;To assist, the requestor can maintain a mapping (e.g., hashtable) between message Ids and relevant domain object Ids which are related to the original request. &amp;nbsp;When the reply is received, the mapping may be used to load the appropriate domain objects and take further action, accordingly.&lt;/p&gt;
&lt;p&gt;Obviously, it is important that the senders and receivers of a message system agree upon the format that messages will take for clear interoperability, better reusability of components, and extensibility of the system. &amp;nbsp;Consequently, a &lt;i&gt;canonical data model&lt;/i&gt;&amp;nbsp;should be well defined that all applications will adhere to. &amp;nbsp;The canonical data model does not dictate how each application&amp;#39;s domain model must be structured, only how each application must format data within messages. &amp;nbsp;&lt;i&gt;Message translators&lt;/i&gt;&amp;nbsp;are developed to convert the sending application&amp;#39;s domain model into the canonical data model before sending a message; receivers of messages then use their own message translators to translate the message into their own domain. &amp;nbsp;This mechanism allows applications built on completely different technologies (e.g., C#, Lisp, and C++) to communicate with each other and exchange data. &amp;nbsp;Many off the shelf messaging systems define their canonical data model which must be adhered to. &amp;nbsp;For example, the &lt;a href="http://www.ros.org/wiki/"&gt;Robot Operating System&lt;/a&gt; (ROS), which we&amp;#39;ll looking at in more detail in subsequent posts, defines their canonical model at &lt;a href="http://www.ros.org/wiki/msg"&gt;http://www.ros.org/wiki/msg&lt;/a&gt;. &amp;nbsp;But the canonical data model need not be limited to defining the types of primitives available and how to include them in messages.&lt;/p&gt;
&lt;p&gt;Domain-specific canonical data models may augment message formatting rules, adding semantic meaning to the data within a message. &amp;nbsp;For example, the &lt;a href="http://en.wikipedia.org/wiki/JAUS"&gt;Joint Architecture For Unmanned Systems (JAUS)&lt;/a&gt; is a set of message guidelines for the domain of unmanned systems, such as autonomous vehicles. &amp;nbsp;The JAUS guidelines provide domain specific rules for communicating data, such as propulsion and braking commands, sensor events, pose and location information, etc. &amp;nbsp;To demonstrate, JAUS message types include (Siciliano, 2008):&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;i&gt;Command&lt;/i&gt;: &amp;nbsp;initiate mode changes or actions,&lt;/li&gt;
&lt;li&gt;&lt;i&gt;Query&lt;/i&gt;: &amp;nbsp;used to solicit information from a component,&lt;/li&gt;
&lt;li&gt;&lt;i&gt;Inform&lt;/i&gt;: &amp;nbsp;response to a query,&lt;/li&gt;
&lt;li&gt;&lt;i&gt;Event set up&lt;/i&gt;: &amp;nbsp;passes parameters to set up an event, and&lt;/li&gt;
&lt;li&gt;&lt;i&gt;Event notification&lt;/i&gt;: &amp;nbsp;sent when the event happens.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;A challenge in dealing with canonical data models is how to handle changes to the model. &amp;nbsp;In order to support backwards compatibility of existing components when the canonical data model changes, new message channels could be created to carry the messages adhering to the model; e.g., &amp;quot;Perception/LaserScans_V1&amp;quot; and &amp;quot;Perception/LaserScans_V2.&amp;quot; &amp;nbsp;Alternatively, the existing channels could continue to be leveraged to carry messages adhering to different version of the canonical data model. &amp;nbsp;To do so, the message, within its header, would include a &lt;i&gt;format indicator&lt;/i&gt;, such as a version number or format document (e.g., DTD) reference. &amp;nbsp;But if a sender knows that receivers of a particular message are mixed in what format is being used, a component would need to send two messages, one for each version of the canonical data model. &amp;nbsp;Certainly, this is an important consideration when deciding which components should (or even can) be upgraded to newer formats, and in what order.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Message Routers&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;While the heavy lifting of the message routing is handled by the messaging middleware itself, there are times when it is useful to augment the middleware with custom message routers to support unique scenarios.&lt;/p&gt;
&lt;p&gt;&lt;img border="0" src="http://devlicious.com/resized-image.ashx/__size/550x0/__key/CommunityServer.Blogs.Components.WeblogFiles/billy_5F00_mccafferty/MessageRouter.png" style="border:0;float:right;margin-left:2px;margin-right:2px;" alt="" /&gt;Suppose the destination of a message may change based on the number of messages that have already passed over a channel. &amp;nbsp;In this scenario, the sender of a message may not know how many messages have been passed over a channel since other senders may have been publishing messages on the same channel. &amp;nbsp;Consequently, a message router may subscribe to the channel to determine where each message should be forwarded to, based on the described business rules. &amp;nbsp;Once the destination is determined, the router would then place the message on a subsequent channel to be delivered to the appropriate destination. &amp;nbsp;This intermediary routing is described as &lt;i&gt;predictive routing&lt;/i&gt;&amp;nbsp;as the message router is aware of every possible destination and the rules for routing, accordingly. &amp;nbsp;If the routing is based on content within the message itself, such as threshold values, then the custom router is known as a &lt;i&gt;content-based router&lt;/i&gt;.&lt;/p&gt;
&lt;p&gt;A drawback to using message routers is that if the routing rules change frequently, the message router will need to be modified just as often. &amp;nbsp;To help remedy this, if the rules are expected to change frequently, configurable routing rules (e.g., via XML) could be employed to enable easier management of routing rules.&lt;/p&gt;
&lt;p&gt;&lt;img border="0" src="http://devlicious.com/resized-image.ashx/__size/550x0/__key/CommunityServer.Blogs.Components.WeblogFiles/billy_5F00_mccafferty/MessageFilter.png" style="border:0;float:right;margin-left:2px;margin-right:2px;" alt="" /&gt;Let&amp;#39;s now consider another scenario wherein it&amp;#39;s left up to the subscribers to determine which messages they&amp;#39;re interested in; i.e., subscribers will be responsible for filtering out the messages they&amp;#39;re uninterested in. &amp;nbsp;In this &lt;i&gt;reactive routing&lt;/i&gt; scenario, each subscriber would provide a respective &lt;i&gt;message filter&lt;/i&gt;&amp;nbsp;which is similar to a message router, but simply forwards, or does not forward, a message onto a subsequent channel that the destination subscriber is listening to. &amp;nbsp;Frequently, message filters decide to forward, or not forward, based on content in the message itself; e.g., only forwarding orders that have a coupon included. &amp;nbsp;While being similar to a message router in basic functionality, a message filter only has one possible channel to forward the message onto.&lt;/p&gt;
&lt;p&gt;Deciding between predictive and reactive filtering must take into account a number of considerations. &amp;nbsp;Is the message content sensitive? &amp;nbsp;Do you need to minimize network traffic? &amp;nbsp;Do you need to be able to add and remove subscribers easily? &amp;nbsp;Is the predictive router becoming a bottleneck of message dissemination? &amp;nbsp;For further guidance on selecting among routing options, see (Hohpe, 2003), ppg. 241-242.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Message Endpoints&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Each messaging middleware option (e.g., CCR, ROS) has unique requirements for communicating with it. &amp;nbsp;Each has its own API, its own means of addressing channels, and its own rules for packaging messages. &amp;nbsp;Ideally, the components of the system should not be aware of the specifics of communicating with the messaging middleware. &amp;nbsp;Furthermore, while unlikely to occur, the middleware should be able to be replaced with another, requiring little, if any, changes to the components. &amp;nbsp;Accordingly, the components must be loosely coupled to the messaging middleware. &amp;nbsp;&lt;i&gt;Message endpoints&lt;/i&gt;&amp;nbsp;provide the bridge between the domain of each component and the API of the messaging middleware.&lt;/p&gt;
&lt;p&gt;&lt;img style="border:0;float:right;margin-left:2px;margin-right:2px;" src="http://devlicious.com/resized-image.ashx/__size/550x0/__key/CommunityServer.Blogs.Components.WeblogFiles/billy_5F00_mccafferty/MessageEndpoints.png" border="0" alt="" /&gt;Message endpoints are similar in nature to &lt;a href="http://domaindrivendesign.org/node/123"&gt;repositories&lt;/a&gt; when communicating with a database. &amp;nbsp;Repositories encapsulate the code required to communicate with a database to store and retrieve data while being able to convert information from the database into domain objects. &amp;nbsp;If the database changes, or if the mechanism for database communication changes (e.g., ADO.NET to NHibernate), then, ideally, only the repositories are affected. &amp;nbsp;The rest of the application knows little about database communications outside of the repository interfaces. &amp;nbsp;Likewise, components of a message-based system should not be aware of messaging details outside of the message endpoint interfaces, which provide the means to send and receive data. &amp;nbsp;The message endpoint accepts a command or data, converts it into a message, and publishes it onto the correct channel. &amp;nbsp;Additionally, the message endpoint receives messages from a channel, converts the content into the domain of the component, and passes the domain objects to the component for further action. &amp;nbsp;Internally, the message endpoint implements a &lt;i&gt;message mapper&lt;/i&gt; to convert between the component domain objects and the canonical data model.&lt;/p&gt;
&lt;p&gt;While posting to a channel is rather straight forward, a message endpoint may receive a message by acting as a:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;i&gt;Polling Consumer&lt;/i&gt;: &amp;nbsp;wherein the receiver looks at a channel on a regular basis for new messages and/or as soon as it completes the processing of a previous message. &amp;nbsp;This frees the receiver from having to deal with messages as soon as they arrive on the channel in favor of dealing with messages went it&amp;rsquo;s ready and willing. &amp;nbsp;A consideration to keep in mind is that messages may queue up on a channel while waiting to be retrieved by the polling consumer. &amp;nbsp;Additionally, a polling consumer may take up threads and resources while polling a channel, even if the channel is empty.&lt;/li&gt;
&lt;li&gt;&lt;i&gt;Event-Driven Consumer&lt;/i&gt;: &amp;nbsp;wherein the message is given to the receiver as soon as it arrives on the channel. &amp;nbsp;The benefits to this include avoiding messages queuing up while being able to process messages asynchronously. &amp;nbsp;But the receiver is no longer in control of the timing in which it processes messages and must handle messages as soon as they arrive on a channel.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Many messaging middleware solutions include support for transactions that the message endpoints may leverage, making the endpoints &lt;i&gt;transactional clients&lt;/i&gt;. &amp;nbsp;To illustrate the need for this, suppose the receiver of a request-reply command crashes just moments after the command message is consumed and removed from the channel. &amp;nbsp;When it recovers, the command message is lost and the sender will never receive a reply. &amp;nbsp;Using a transaction, the command message is not removed from the channel until the response is completed and sent. &amp;nbsp;Committing the transaction removes the command message from the channel and adds the reply document message to the reply channel.&lt;/p&gt;
&lt;p&gt;There are a few recommendations which should be considered when developing message endpoints. &amp;nbsp;In accordance with the &lt;a href="http://www.objectmentor.com/resources/articles/srp.pdf"&gt;SRP&lt;/a&gt;, message endpoints should be able to receive messages or send messages, but not both in the same message endpoint. &amp;nbsp;Furthermore, a message endpoint should only communicate with one message channel. &amp;nbsp;If a component needs to send a message on separate channels, it would leverage multiple message endpoints to do so. &amp;nbsp;If your components are developed in line with &lt;a href="http://www.infoq.com/minibooks/domain-driven-design-quickly"&gt;DDD&lt;/a&gt;, it would be each component&amp;#39;s &lt;a href="http://martinfowler.com/eaaCatalog/serviceLayer.html"&gt;application services layer&lt;/a&gt; which would communicate with the message endpoints, preferably via their interfaces instead of concrete instances. &amp;nbsp;This facilitates swapping out the message endpoints with mock objects for unit testing. &amp;nbsp;Leveraging &lt;a href="http://devlicious.com/blogs/billy_mccafferty/archive/2008/10/30/refactoring-service-dependencies-to-separated-interface.aspx"&gt;separated interfaces&lt;/a&gt;&amp;nbsp;and &lt;a href="http://devlicious.com/blogs/billy_mccafferty/archive/2009/11/09/dependency-injection-101.aspx"&gt;dependency injection&lt;/a&gt;&amp;nbsp;helps enable this approach. &amp;nbsp;While these guidelines introduce more objects and indirection, they are proven practices for increasing maintainability of the component and reusability of the message endpoints.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Performance of Message Based Systems&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;One would likely be quick to assume that developing a message-based system has a huge cost to performance. &amp;nbsp;Domain objects are converted to messages, messages are passed over channels, routers and filters intercept and forward messages, and messages are converted back into domain objects...this sounds like a heck of a lot going on. &amp;nbsp;But because each component executes in its own thread or process, they need not wait for other components to complete their job before being able to move on to handling another message or task.&lt;/p&gt;
&lt;p&gt;&lt;img border="0" src="http://devlicious.com/resized-image.ashx/__size/550x0/__key/CommunityServer.Blogs.Components.WeblogFiles/billy_5F00_mccafferty/SynchVsAsynchProcessing.png" alt="" /&gt;&lt;/p&gt;
&lt;p&gt;In the figure above (adapted from&amp;nbsp;Hohpe, 2003, pg. 73), note that a sequential process requires that each message life cycle is completed in full before moving on to the next message. &amp;nbsp;But in an asynchronous, message-based system, each component can move onto a subsequent message just as soon as it has completed its part in the last one. &amp;nbsp;This greatly compensates for the extra overhead imparted by the messaging infrastructure.&lt;/p&gt;
&lt;p&gt;With that said, there are some component responsibilities which take a long time to complete and may impede the speed by which messages are processed. &amp;nbsp;For example, imagine a component which takes images from a web cam and extracts information such as human figures or road signs. &amp;nbsp;This is likely a time consuming process and would impact the turn around time in which the component could process subsequent messages. &amp;nbsp;To alleviate this bottleneck, multiple instances of the same component may subscribe to the same point-to-point channel. &amp;nbsp;Recall that a point-to-point channel ensures that each message only has a single receiver. &amp;nbsp;The instances of the component then become &lt;i&gt;competing consumers&lt;/i&gt; of each message. &amp;nbsp;So if one instance of the component is still processing an earlier message, another instance can grab the next message that arrives for concurrent processing. &amp;nbsp;Power in numbers!&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Monitoring and Debugging&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Due to the widely asynchronous nature of message-based systems, attention must be given to monitoring and debugging techniques to observe system behavior and iron out problems.&lt;/p&gt;
&lt;p&gt;Logging message content is an invaluable measure towards getting a clear look at what communications are taking place. &amp;nbsp;To facilitate this, logging could be added directly into sending and receiving components, but logging message content should not be a concern of components; accordingly, using a monitoring utility to log such information is a cleaner separation of concerns. &amp;nbsp;Certainly a benefit of publish-subscribe channels is that a monitoring component may subscribe to all messages and log the information to a file or console window. &amp;nbsp;While it&amp;rsquo;s just as valuable to monitor messages on point-to-point channels, if a monitor were to consume a message over a point-to-point channel, the message would be noted as consumed and would no longer be available to the intended receiver. &amp;nbsp;Because such monitoring capability is so helpful in developing and debugging, many messaging middleware options include a &amp;quot;peek&amp;quot; option which allows a monitoring utility to review message contents on a point-to-point channel without actually consuming the message. &amp;nbsp;This capability should be taken into consideration when comparing messaging middleware alternatives.&lt;/p&gt;
&lt;p&gt;In addition to monitoring message content sent over channels, it&amp;rsquo;s also assistive to monitor active subscriptions to various channels to accurately determine which components are receiving which messages. &amp;nbsp;This capability is typically built into messaging middleware solutions and is very assistive during development.&lt;/p&gt;
&lt;p&gt;It&amp;rsquo;s possible that even if a message is routed appropriately, the receiving component may not know what to do with the message due to an incorrectly formatted header or body content. &amp;nbsp;Invalid messages such as this should be forwarded to an &lt;i&gt;invalid message channel&lt;/i&gt; which an error logging utility would monitor and log, accordingly. &amp;nbsp;An invalid message channel is setup just like any other channel but with the intention of exposing such messages for debugging purposes.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Closing Thoughts&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Developing asynchronous, message-based systems requires a paradigm shift from the more traditional, synchronously executed applications that most people are familiar with. &amp;nbsp;It is not appropriate for every application domain and should be seen as one additional architectural option to consider when developing applications. &amp;nbsp;But in some domains, such as robotics or in the integration of disparate applications, this approach to development is absolutely pivotal in providing responsive behavior without sacrificing maintainability of the overall system. &amp;nbsp;Indeed, by splitting responsibilities into discrete components, loosely coupled to each other via messaging middleware, immensely complex problems can be broken down into understandable chunks while being flexible enough to accommodate changes to the underlying middleware or introduction of new components.&lt;/p&gt;
&lt;p&gt;In the next couple of posts, we&amp;#39;ll look at a checklist for developing message-based systems followed with examples in CCR and ROS.&lt;/p&gt;
&lt;p&gt;Enjoy!&lt;/p&gt;
&lt;p&gt;Billy McCafferty&lt;br /&gt;&lt;a href="http://wiki.sharparchitecture.net"&gt;http://wiki.sharparchitecture.net&lt;/a&gt;&amp;nbsp;&lt;/p&gt;
&lt;p&gt;P.S., for S#arp fans, we&amp;#39;re trying to get another release together for the coming week...and this ain&amp;#39;t no quarterly release. ;)&lt;/p&gt;
&lt;hr /&gt;
&lt;p&gt;&lt;strong&gt;References&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Hohpe, G., Woolf, B. &amp;nbsp;2003. &amp;nbsp;&lt;a href="http://www.amazon.com/Enterprise-Integration-Patterns-Designing-Deploying/dp/0321200683"&gt;Enterprise Integration Patterns: &amp;nbsp;Designing, Building, and Deploying Messaging Solutions&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;Siciliano, B., Khatib, O. &amp;nbsp;2008. &amp;nbsp;&lt;a href="http://www.amazon.com/Springer-Handbook-Robotics-Bruno-Siciliano/dp/354023957X"&gt;Springer Handbook of Robotics&lt;/a&gt;.&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://devlicio.us/aggbug.aspx?PostID=55589" width="1" height="1"&gt;</description><category domain="http://devlicio.us/blogs/billy_mccafferty/archive/tags/Architecture/default.aspx">Architecture</category><category domain="http://devlicio.us/blogs/billy_mccafferty/archive/tags/Robotics/default.aspx">Robotics</category><category domain="http://devlicio.us/blogs/billy_mccafferty/archive/tags/Patterns/default.aspx">Patterns</category></item><item><title>Dependency Injection 101</title><link>http://devlicio.us/blogs/billy_mccafferty/archive/2009/11/09/dependency-injection-101.aspx</link><pubDate>Mon, 09 Nov 2009 22:26:00 GMT</pubDate><guid isPermaLink="false">40756a8b-6212-4073-9d98-6c26781577de:53587</guid><dc:creator>Billy McCafferty</dc:creator><slash:comments>21</slash:comments><description>&lt;p&gt;&lt;i&gt;(It looks like &lt;/i&gt;&lt;a href="http://www.kevinwilliampang.com/"&gt;&lt;i&gt;Kevin Pang&lt;/i&gt;&lt;/a&gt;&lt;i&gt; and I must have seen the same vision this weekend or had a close encounter flashback as he&amp;#39;s concurrently putting together a great series on &lt;/i&gt;&lt;a href="http://www.kevinwilliampang.com/post/Dependency-Injection-For-Dummies.aspx"&gt;&lt;i&gt;Dependency Injection for Dummies&lt;/i&gt;&lt;/a&gt;&lt;i&gt;...be sure to check out his posts for another take on this subject!)&lt;/i&gt;&lt;/p&gt;
&lt;p&gt;&lt;span style="font-size:large;"&gt;S&lt;/span&gt;imply put, dependency injection is the technique of supplying an object with its service dependency(s) from an external source.&lt;/p&gt;
&lt;p&gt;If you&amp;rsquo;re unfamiliar with dependency injection or just starting down the road of object oriented programming, the above statement might have the same effect as a mathematics book when the author puts forth a new equation that is about to be analyzed. &amp;nbsp;Symptoms may include glassy eyes, nausea, and headaches. &amp;nbsp;But when taken apart, we find that the idea of dependency injection is a much simpler concept than its grandiose title implies, and is a technique that many developers use commonly, quite naturally in many cases, without even knowing it.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Encapsulation&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;&lt;span&gt;The place to start, in understanding the motivations and implementation of dependency injection, is with the basic idea of encapsulation. &amp;nbsp;Crudely explained, &lt;/span&gt;&lt;strong&gt;&lt;i&gt;encapsulation&lt;/i&gt;&lt;/strong&gt;&lt;span&gt; is the art of determining which bits of logic belong together and putting them into discrete objects. &amp;nbsp;This allows the details of the logic to be modified within the encapsulated object without necessarily impacting the objects which use it. &amp;nbsp;Furthermore, encapsulation provides a neat and clean way to package up reusable code to be used by many other objects without introducing code duplication.&lt;/span&gt;&lt;img style="border:0;float:right;margin:5px;" src="http://devlicio.us/resized-image.ashx/__size/550x0/__key/CommunityServer.Blogs.Components.WeblogFiles/billy_5F00_mccafferty/Robot.png" border="0" alt="" /&gt;&lt;/p&gt;
&lt;p&gt;From a real-world perspective, encapsulation is a very useful technique when building a self-aware robot to take over the world. &amp;nbsp;When building any self-aware robot, you need to start with the basics, such as mobility and sensory perception. &amp;nbsp;For example, a robot might have a stereo camera for observing the visible world, sonar sensors for detecting nearby objects around it, and touch sensors to know if it has made contact with the object it&amp;rsquo;s trying to pick up. &amp;nbsp;Just by describing it, we&amp;rsquo;re already starting to imply areas of logic that could be nicely encapsulated: &amp;nbsp;visual perception, sonar object detection, touch feedback, and mobility.&lt;/p&gt;
&lt;p&gt;Assume for a moment that we&amp;rsquo;ll bypass the practice of encapsulation and throw all of the code for these various modules directly into the primary method which uses them, a benign method we&amp;rsquo;ll call &lt;span style="font-family:&amp;#39;Courier New&amp;#39;, Courier, monospace;"&gt;TakeOverTheWorld&lt;/span&gt;, living in a .NET assembly called CommandAndControl.dll. &amp;nbsp;The code might look something like the following:&lt;/p&gt;
&lt;pre class="c-sharp" name="code"&gt;public class WorldDomination {
   public void TakeOverTheWorld() {
      // Code to open USB connection to use stereo camera
      // Code to process camera images to identify humans

      // Code to open serial port to legs for moving
      // Code to send legs serial commands to move over to location of human

      // Code to generate speech to user; e.g., &amp;quot;All your leaders are belong to us&amp;quot;
   }
}&lt;/pre&gt;
&lt;p&gt;In the code, we see the &lt;span style="font-family:&amp;#39;Courier New&amp;#39;, Courier, monospace;"&gt;TakeOverTheWorld&lt;/span&gt; method taking on a lot of responsibilities and given explicit knowledge about components which are subject to change when the robot components are upgraded. &amp;nbsp;Some of the responsibilities which we&amp;rsquo;re burdening the method with include:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Knowing the stereo camera is connected via USB and how to open a connection to it;&lt;/li&gt;
&lt;li&gt;Knowing how to process camera images to identify humans;&lt;/li&gt;
&lt;li&gt;Knowing that the legs require communications to be sent via a specific serial port;&lt;/li&gt;
&lt;li&gt;Knowing how to send low level communications to the legs as serial commands.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;img style="border:0;float:right;margin:5px;" src="http://devlicio.us/resized-image.ashx/__size/550x0/__key/CommunityServer.Blogs.Components.WeblogFiles/billy_5F00_mccafferty/C3PO.png" border="0" alt="" /&gt;So what&amp;rsquo;s the problem you ask? &amp;nbsp;For starters, the &lt;span style="font-family:&amp;#39;Courier New&amp;#39;, Courier, monospace;"&gt;TakeOverTheWorld&lt;/span&gt; method would likely be a few thousand lines long and would be immensely difficult to maintain. &amp;nbsp;Let&amp;rsquo;s suppose that we upgrade the camera to use a better stereo imaging device which now receives commands wirelessly. &amp;nbsp;You&amp;rsquo;d have to carefully, tediously walk through all of the lines of &lt;span style="font-family:&amp;#39;Courier New&amp;#39;, Courier, monospace;"&gt;TakeOverTheWorld&lt;/span&gt; to find any communications with the camera, upgrade the capabilities, and test, accordingly. &amp;nbsp;But now testing is much more challenging as well. &amp;nbsp;Since all of the other code, such as the mobility code, will also run whenever we invoke &lt;span style="font-family:&amp;#39;Courier New&amp;#39;, Courier, monospace;"&gt;TakeOverTheWorld&lt;/span&gt;, then we&amp;rsquo;ll need to make sure that the rest of the robot is in perfect working order while we switch out one component. &amp;nbsp;In other words, it&amp;rsquo;s simply not possible now to test the various components in isolation of each other. &amp;nbsp;This approach quickly turns into spaghetti code, becoming a maintenance nightmare, difficult to debug, and exhibiting decreasing code quality as time progresses. &amp;nbsp;What started out as a simple project to develop a robot to conquer the world is turning out to be about as effective as C-3PO&amp;hellip;after being blasted by a storm trooper that is.&lt;/p&gt;
&lt;p&gt;The first step that we can take, to make our robot for world domination a little easier to understand and maintain, is to encapsulate the various modules into their own, respective classes. &amp;nbsp;Let&amp;rsquo;s look at the &lt;span style="font-family:&amp;#39;Courier New&amp;#39;, Courier, monospace;"&gt;TakeOverTheWorld&lt;/span&gt; code again with a sprinkling of better encapsulation by moving the camera related responsibilities to a class called &lt;span style="font-family:&amp;#39;Courier New&amp;#39;, Courier, monospace;"&gt;StereoCamera.cs&lt;/span&gt; and the mobility related responsibilities to &lt;span style="font-family:&amp;#39;Courier New&amp;#39;, Courier, monospace;"&gt;MobilePlatform.cs&lt;/span&gt;. &amp;nbsp;Furthermore, let&amp;rsquo;s move these two classes to a new class library assembly called Services.dll.&lt;/p&gt;
&lt;pre class="c-sharp" name="code"&gt;// Within the Services package (or class library)

public class StereoCamera {
   public void Connect() {
      // Code to open USB connection to use stereo camera
   }

   public MeaslyHuman IdentifyHumanInFieldOfVision() {
      // Code to process camera images to identify humans
   }
}

public class MobilePlatform {
   public void Connect() {
      // Code to open serial port to legs for moving
   }

   public void MoveTo(Location location) {
      // Code to send legs serial commands to move over to location 
   }
}

// Within the CommandAndControl package

public class WorldDomination {
   public void TakeOverTheWorld() {
      StereoCamera camera = new StereoCamera();
      camera.Open();
      MeaslyHuman human = camera.IdentifyHumanInFieldOfVision();

      MobilePlatform legs = new MobilePlatform();
      legs.Connect();
      legs.MoveTo(human.Location);

      // Code to generate speech to user; e.g., &amp;ldquo;All your leaders are belong to us&amp;rdquo;
   }
}&lt;/pre&gt;
&lt;p&gt;&lt;img style="border:0;float:right;margin:5px;" src="http://devlicio.us/resized-image.ashx/__size/550x0/__key/CommunityServer.Blogs.Components.WeblogFiles/billy_5F00_mccafferty/DI_5F00_RefactorToPackages.png" border="0" alt="" /&gt;As demonstrated, we introduced two new classes, &lt;span style="font-family:&amp;#39;Courier New&amp;#39;, Courier, monospace;"&gt;StereoCamera&lt;/span&gt; and &lt;span style="font-family:&amp;#39;Courier New&amp;#39;, Courier, monospace;"&gt;MobilePlatform&lt;/span&gt;, and moved the related responsibilities to those classes. &amp;nbsp;We also introduced a new package as a new class library, called Services.dll, to contain the two new classes. &amp;nbsp;The package diagram now looks as the figure shown to the right.&lt;/p&gt;
&lt;p&gt;This basic refactoring has resulted in a number of benefits:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;There are far fewer lines of code in the &lt;span style="font-family:&amp;#39;Courier New&amp;#39;, Courier, monospace;"&gt;TakeOverTheWorld&lt;/span&gt; method and easier to digest for whomever may be looking at it next;&lt;/li&gt;
&lt;li&gt;The &lt;span style="font-family:&amp;#39;Courier New&amp;#39;, Courier, monospace;"&gt;TakeOverTheWorld&lt;/span&gt; method is now much easier to understand the overall flow of control without getting bogged down in low level details;&lt;/li&gt;
&lt;li&gt;The &lt;span style="font-family:&amp;#39;Courier New&amp;#39;, Courier, monospace;"&gt;TakeOverTheWorld&lt;/span&gt; method now knows nothing about the details related to connecting to the camera via the USB connection (other than simply calling Connect), nothing about the mathematics behind processing camera images to identify humans, nor the details of opening a serial port and sending low level serial commands to move from point A to point B; and&lt;/li&gt;
&lt;li&gt;The &lt;span style="font-family:&amp;#39;Courier New&amp;#39;, Courier, monospace;"&gt;StereoCamera&lt;/span&gt; and &lt;span style="font-family:&amp;#39;Courier New&amp;#39;, Courier, monospace;"&gt;MobilePlatform&lt;/span&gt; classes are now quite reusable from a variety of other objects that will surely need to use them.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Overall, this encapsulation refactoring has led to a design that is easier to maintain and will likely reflect in the general level of maintainability and quality. &amp;nbsp;So things are better, but we still have much to improve. &amp;nbsp;I suppose we&amp;rsquo;re beginning to resemble C-3PO, but only after Chewbacca put his head on backwards. &amp;nbsp;(OK, so C-3PO didn&amp;rsquo;t have diabolical plans for world dominion, but let&amp;rsquo;s ignore that subtlety for now.) &amp;nbsp;As we proceed, we&amp;rsquo;ll examine what other areas we&amp;rsquo;ll want to improve and learn a bit more about the definition of dependency injection along the way.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Services&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Earlier, we defined dependency injection as the technique of supplying an object with its service dependency(s)&amp;hellip; &amp;nbsp;What exactly is a service dependency? &amp;nbsp;A &lt;strong&gt;&lt;i&gt;service&lt;/i&gt;&lt;/strong&gt;, in the context of dependency injection, is any object which provides access to an external resource. &amp;nbsp;In the refactoring exercise we performed on our code, and as implied by the package diagram, two services were introduced. &amp;nbsp;The first provided access to the stereo camera; the second provided access to the legs for moving the robot around. &amp;nbsp;In your own project, services may include web services, data access objects, file manipulation utilities, third party APIs, and many others.&lt;/p&gt;
&lt;p&gt;Because services depend on external resources (e.g., a physical component or database), they are inherently more complicated to test, require that the external resource be available when we test our code, and are subject to change when the underlying resource being managed changes (e.g., when the component is upgraded). &amp;nbsp;When considering these arguments, we want to remain &lt;i&gt;&lt;strong&gt;loosely coupled&lt;/strong&gt;&lt;/i&gt; to the services themselves. &amp;nbsp;To contrast, the refactored code above, even after applying encapsulation, is &lt;strong&gt;&lt;i&gt;tightly coupled&lt;/i&gt;&lt;/strong&gt; to the underlying services.&lt;/p&gt;
&lt;p&gt;To illustrate the idea of tight coupling, the &lt;span style="font-family:&amp;#39;Courier New&amp;#39;, Courier, monospace;"&gt;TakeOverTheWorld&lt;/span&gt; method is creating each service directly with the &lt;span style="font-family:&amp;#39;Courier New&amp;#39;, Courier, monospace;"&gt;new&lt;/span&gt; keyword; i.e., the method is creating a concrete instance of the service class. &amp;nbsp;Not only does the method have a concrete dependency on the service class itself, this inherently implies that the application layer that the &lt;span style="font-family:&amp;#39;Courier New&amp;#39;, Courier, monospace;"&gt;WorldDomination&lt;/span&gt; class resides in must have a direct dependency on the layer which the &lt;span style="font-family:&amp;#39;Courier New&amp;#39;, Courier, monospace;"&gt;StereoCamera&lt;/span&gt; service class resides in. &amp;nbsp;This layer dependency is shown as a directional line in the above package diagram from the CommandAndControl layer to the Services layer.&lt;/p&gt;
&lt;p&gt;In addition to having a concrete dependency on the service itself, the &lt;span style="font-family:&amp;#39;Courier New&amp;#39;, Courier, monospace;"&gt;TakeOverTheWorld&lt;/span&gt; method must also know to call &lt;span style="font-family:&amp;#39;Courier New&amp;#39;, Courier, monospace;"&gt;Open&lt;/span&gt; for the respective services (and presumably &lt;span style="font-family:&amp;#39;Courier New&amp;#39;, Courier, monospace;"&gt;Close&lt;/span&gt;); i.e., the &lt;span style="font-family:&amp;#39;Courier New&amp;#39;, Courier, monospace;"&gt;TakeOverTheWorld&lt;/span&gt; method needs to know how to create and initialize the services before it&amp;rsquo;s even able to use them. &amp;nbsp;These are further responsibilities which this method should not be concerned with.&lt;/p&gt;
&lt;p&gt;Ideally, the &lt;span style="font-family:&amp;#39;Courier New&amp;#39;, Courier, monospace;"&gt;TakeOverTheWorld&lt;/span&gt; method would be loosely coupled to the underlying services and wouldn&amp;rsquo;t have to know about such low level details of the service itself outside of calling methods such as &lt;span style="font-family:&amp;#39;Courier New&amp;#39;, Courier, monospace;"&gt;IdentifyHumanInFieldOfVision&lt;/span&gt;.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Coding to Interface&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;The first step we can take towards making &lt;span style="font-family:&amp;#39;Courier New&amp;#39;, Courier, monospace;"&gt;TakeOverTheWorld&lt;/span&gt; less tightly coupled to the service classes is to have the &lt;span style="font-family:&amp;#39;Courier New&amp;#39;, Courier, monospace;"&gt;TakeOverTheWorld&lt;/span&gt; method code to the interfaces of the services rather than to the concrete classes themselves. &amp;nbsp;One might argue against introducing two new interfaces for the objects; as we add new objects, we inherently introduce additional complexity to the overall system. &amp;nbsp;Also, with interfaces, not only are we introducing a small amount of additional complexity to the overall system, but we&amp;rsquo;re also introducing indirection. &amp;nbsp;In other words, in order for someone to fully understand what&amp;rsquo;s going on at runtime, the developer will need to determine which concrete object is being used under the interface. &amp;nbsp;It shouldn&amp;rsquo;t be difficult to do so, but it does add time to understanding the overall system. &amp;nbsp;These are fair arguments and ones not to be ignored. &amp;nbsp;Whenever we are faced with a decision that will lead to a better design at the expense of added complexity, we carefully need to consider if the benefits of refactoring outweigh the penalties of added complexity. &amp;nbsp;In this case, coding to interface (and another refactoring we will do next) will lead to a more maintainable system, provide a means to readily unit test the various components in isolation, and will result in a more loosely coupled design.&lt;/p&gt;
&lt;p&gt;Accordingly, we simply need to add two interfaces to the Services package, have the service classes implement them, and change the references in the &lt;span style="font-family:&amp;#39;Courier New&amp;#39;, Courier, monospace;"&gt;TakeOverTheWorld&lt;/span&gt; method to invoke the interfaces rather than the classes themselves. &amp;nbsp;But as we&amp;rsquo;ll see, this next refactoring still leaves us tightly coupled to the service classes. &amp;nbsp;Let&amp;rsquo;s look at the code.&lt;/p&gt;
&lt;pre class="c-sharp" name="code"&gt;// Within the Services package

public interface IStereoCamera {
   void Connect();
   MeaslyHuman IdentifyHumanInFieldOfVision();
}

public interface IMobilePlatform {
   void Connect();
   void MoveTo(Location location);
}

public class StereoCamera : IStereoCamera {
   public void Connect() {
      // Code to open USB connection to use stereo camera
   }

   public MeaslyHuman IdentifyHumanInFieldOfVision() {
      // Code to process camera images to identify humans
   }
}

public class MobilePlatform : IMobilePlatform {
   public void Connect() {
      // Code to open serial port to legs for moving
   }

   public void MoveTo(Location location) {
      // Code to send legs serial commands to move over to location 
   }
}

// Within the CommandAndControl package

public class WorldDomination {
   public WorldDomination() {
      camera = new StereoCamera();
      legs = new MobilePlatform();
   }

   public void TakeOverTheWorld() {
      camera.Open();
      MeaslyHuman human = camera.IdentifyHumanInFieldOfVision();

      legs.Connect();
      legs.MoveTo(human.Location);

      // Code to generate speech to user; e.g., &amp;ldquo;All your leaders are belong to us&amp;rdquo;
   }

   private readonly IStereoCamera camera;
   private readonly IMobilePlatform legs;
}&lt;/pre&gt;
&lt;p&gt;&lt;img style="border:0;float:right;margin:5px;" src="http://devlicio.us/resized-image.ashx/__size/550x0/__key/CommunityServer.Blogs.Components.WeblogFiles/billy_5F00_mccafferty/DI_5F00_AddInterfaces.png" border="0" alt="" /&gt;In the code above, note that the two interfaces were introduced and now the constructor of the &lt;span style="font-family:&amp;#39;Courier New&amp;#39;, Courier, monospace;"&gt;WorldDomination&lt;/span&gt; class now handles creating the service instances and setting private members, represented as interfaces, to the service instances. &amp;nbsp;The package diagram reflecting this refactoring is shown at right.&lt;/p&gt;
&lt;p&gt;Even though the &lt;span style="font-family:&amp;#39;Courier New&amp;#39;, Courier, monospace;"&gt;TakeOverTheWorld&lt;/span&gt; method is now communicating with the interfaces of the services, the class containing is still tightly coupled to the service classes due to the local instantiation of the classes within its constructor. &amp;nbsp;To further alleviate this coupling, we&amp;rsquo;re going to have to move a step &amp;ldquo;up&amp;rdquo; and introduce a package which will be responsible for creating the service dependencies and injecting them into the &lt;span style="font-family:&amp;#39;Courier New&amp;#39;, Courier, monospace;"&gt;WorldDomination&lt;/span&gt; class. &amp;nbsp;Yes, we&amp;rsquo;re finally ready to see dependency injection in action.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Service Initialization and Injection&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;&lt;img style="border:0;float:right;margin:5px;" src="http://devlicio.us/resized-image.ashx/__size/550x0/__key/CommunityServer.Blogs.Components.WeblogFiles/billy_5F00_mccafferty/DI_5F00_RefactorToDI.png" border="0" alt="" /&gt;While the previous refactorings have taken us closer towards a more loosely coupled design, we still need to remove the object creation from the &lt;span style="font-family:&amp;#39;Courier New&amp;#39;, Courier, monospace;"&gt;WorldDomination&lt;/span&gt; class altogether. &amp;nbsp;By introducing a new package which will contain the robot system&amp;rsquo;s &amp;ldquo;main&amp;rdquo; program, we can leverage that layer to also initialize the service dependencies and inject them into the &lt;span style="font-family:&amp;#39;Courier New&amp;#39;, Courier, monospace;"&gt;WorldDomination&lt;/span&gt; class. &amp;nbsp;Let&amp;rsquo;s look at the code of the new package, called Robot, along with modifications to the &lt;span style="font-family:&amp;#39;Courier New&amp;#39;, Courier, monospace;"&gt;WorldDomination&lt;/span&gt; class. &amp;nbsp;(The Services package, and the interfaces and classes therein, will remain unchanged.) &amp;nbsp;But before looking at the code, study the package diagram at right to see where the classes live and take particular note of the direction of package dependencies. &amp;nbsp;There&amp;rsquo;s one dependency that&amp;rsquo;s still problematic, which we&amp;rsquo;ll discuss after the code.&lt;/p&gt;
&lt;pre class="c-sharp" name="code"&gt;// Within the CommandAndControl package

public class WorldDomination {
   public WorldDomination(IStereoCamera camera, IMobilePlatform legs) {
      this.camera = camera;
      this.legs = legs;
   }

   public void TakeOverTheWorld() {
      // Same as before
   }

   private readonly IStereoCamera camera;
   private readonly IMobilePlatform legs;
}

// Within the new Robot package

public class Program {
   // This is the &amp;ldquo;main&amp;rdquo; method of the entire robot application.
   // I.e., it&amp;rsquo;s the method that gets called to kick off the application.
   public void Main() {
      IStereoCamera camera = new StereoCamera();
      IMobilePlatform legs = new MobilePlatform();

      WorldDomination worldDomination = new WorldDomination(camera, legs);

      worldDomination.TakeOverTheWorld();
   }
}&lt;/pre&gt;
&lt;p&gt;In the code above, the Main method initializes the services and &amp;ldquo;injects&amp;rdquo; them into the constructor of the &lt;span style="font-family:&amp;#39;Courier New&amp;#39;, Courier, monospace;"&gt;WorldDomination&lt;/span&gt; class. &amp;nbsp;As you can see, the injection of service dependencies into a class is really nothing more than passing the service instances as arguments to the class instantiation. &amp;nbsp;So when it comes right down to it, the intimidating phrase &amp;ldquo;dependency injection&amp;rdquo; is really quite simple in practice. &amp;nbsp;But there&amp;rsquo;s still a problem in our implementation that could lead to design &amp;ldquo;rot&amp;rdquo; over time. &amp;nbsp;The CommandAndControl package still has a dependency on the Services package. &amp;nbsp;This is bad because during later phases of the project, without a high level of discipline, developers may forego injecting the service dependencies into the &lt;span style="font-family:&amp;#39;Courier New&amp;#39;, Courier, monospace;"&gt;WorldDomination&lt;/span&gt; class, or other classes in the CommandAndControl package and simply instantiate the service classes directly using the &lt;span style="font-family:&amp;#39;Courier New&amp;#39;, Courier, monospace;"&gt;new&lt;/span&gt; keyword. &amp;nbsp;This would make all the work we&amp;rsquo;ve done to this point to support dependency injection a moot point. &amp;nbsp;To enforce our design, we need to introduce a new pattern known as &lt;strong&gt;&lt;i&gt;dependency inversion&lt;/i&gt;&lt;/strong&gt;, also known as &lt;strong&gt;&lt;i&gt;separated interface&lt;/i&gt;&lt;/strong&gt;.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Separated Interface&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;&lt;img style="border:0;float:right;margin:5px;" src="http://devlicio.us/resized-image.ashx/__size/550x0/__key/CommunityServer.Blogs.Components.WeblogFiles/billy_5F00_mccafferty/DI_5F00_RefactorToSeparatedInterface.png" border="0" alt="" /&gt;To enforce our design, and to eliminate the package dependency from CommandAndControl to Services, we will move the service interfaces to the CommandAndControl package and reverse, or invert, the dependency direction between the two packages. &amp;nbsp; Accordingly, the refactoring steps to do this include:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;Copy the service interfaces from the Services package to the CommandAndControl package.&lt;/li&gt;
&lt;li&gt;Change the interface references in the &lt;span style="font-family:&amp;#39;Courier New&amp;#39;, Courier, monospace;"&gt;WorldDomination&lt;/span&gt; class to refer to the interfaces now found within the CommandAndControl package.&lt;/li&gt;
&lt;li&gt;Remove the package dependency from CommandAndControl to Services. &amp;nbsp;Now add a package dependency from Services to CommandAndControl. &amp;nbsp;(In C#, this would be a matter of deleting the assembly reference from the CommandAndControl class library and adding a new assembly reference from the Services class library.)&lt;/li&gt;
&lt;li&gt;Modify the service classes, StereoCamera and MobilePlatform, to implement the interfaces now found in the CommandAndControl package.&lt;/li&gt;
&lt;li&gt;Modify the Main method, in the Main class to use the interfaces found within the CommandAndControl class.&lt;/li&gt;
&lt;li&gt;Delete the obsolete interfaces from the Services package.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;With the &lt;strong&gt;&lt;i&gt;separated interface&lt;/i&gt;&lt;/strong&gt; pattern implemented, the CommandAndControl package is only aware of the service interfaces without having any dependency, whatsoever, on the service implementations. &amp;nbsp;As performed in the previous refactoring, the CommandAndControl package, the &lt;span style="font-family:&amp;#39;Courier New&amp;#39;, Courier, monospace;"&gt;WorldDomination&lt;/span&gt; class specifically, is being given its service dependencies via &lt;strong&gt;&lt;i&gt;constructor injection&lt;/i&gt;&lt;/strong&gt; via initialization code found in the Robot&amp;rsquo;s main method.&lt;/p&gt;
&lt;p&gt;With this, we have implemented a basic example, including all the required pieces, for performing dependency injection. &amp;nbsp;It introduced a number of new pieces to the overall application, but our design is now loosely coupled to the underlying services and enables us easily swap out services with new implementations, without having to recompile the CommandAndControl package, and provides the ability for &lt;strong&gt;&lt;i&gt;test doubles&lt;/i&gt;&lt;/strong&gt;, such as mocks, stubs, and fakes, to be injected into the &lt;span style="font-family:&amp;#39;Courier New&amp;#39;, Courier, monospace;"&gt;WorldDomination&lt;/span&gt; class when unit testing. &amp;nbsp; (Unit testing with test doubles is beyond the scope of this article, but I encourage you to read &lt;a href="http://xunitpatterns.com/Test%20Double.html"&gt;http://xunitpatterns.com/Test%20Double.html &lt;/a&gt;to begin learning more about this subject.)&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Dependency Injection / Inversion of Control (IoC) Containers&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;There&amp;rsquo;s one final topic which is appropriate to discuss when describing dependency injection: &amp;nbsp;IoC containers. &amp;nbsp;(Dependency injection is also known as &amp;ldquo;Inversion of Control,&amp;rdquo; as originally described by Robert Martin. &amp;nbsp;Interestingly enough, the development community typically uses the phrase &amp;ldquo;dependency injection&amp;rdquo; when talking about the technique itself and &amp;ldquo;IoC&amp;rdquo; when talking about dependency injection containers. &amp;nbsp;But rest assured, there is no difference whatsoever between &amp;ldquo;Dependency Injection&amp;rdquo; and &amp;ldquo;Inversion of Control (IoC).&amp;rdquo;) &amp;nbsp;An IoC Container is a utility which is leveraged to initialize and inject dependencies into the objects that use them. &amp;nbsp;While it is a bit more difficult to visualize than the &amp;ldquo;manual&amp;rdquo; dependency injection we performed in the previous refactoring step, an IoC Container is nothing more than an object factory which initializes an object and satisfies its service dependencies in the process.&lt;/p&gt;
&lt;p&gt;With most IoC Containers (e.g., Ninject, Castle Windsor, LinFu, and many others), there are only a couple of steps required to setup and use the IoC Container:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;Register all of the classes which may be injected into another object. &amp;nbsp;In our carefree efforts for world domination via our robot, this would include, at minimum, registering the service classes MobilePlatform and StereoCamera. &amp;nbsp;While each IoC Container has its own means of registering a class for later retrieval, the underlying mechanism is often as simple as adding the service class&amp;rsquo; object type to a hashtable for later lookup. &amp;nbsp; If we were using Castle Windsor with our project, the registration lines would look like the following:
&lt;pre class="c-sharp" name="code"&gt;container.AddComponent(&amp;quot;camera&amp;quot;, 
   typeof(IStereoCamera), typeof(StereoCamera));
container.AddComponent(&amp;quot;mobilePlatform&amp;quot;, 
   typeof(IMobilePlatform), typeof(MobilePlatform));
container.AddComponent(&amp;quot;camera&amp;quot;, typeof(WorldDomination));&lt;/pre&gt;
Note that the last line registers the &lt;span style="font-family:&amp;#39;Courier New&amp;#39;, Courier, monospace;"&gt;WorldDomination&lt;/span&gt; class itself.  In doing so, we can let the IoC Container take care of the work of instantiating it with its service dependencies already injected.  We don&amp;rsquo;t &lt;i&gt;have&lt;/i&gt; to hand off instantiation of this class to the IoC Container, but it provides a useful benefit.  Suppose the &lt;span style="font-family:&amp;#39;Courier New&amp;#39;, Courier, monospace;"&gt;WorldDomination&lt;/span&gt; class needs a third service dependency provided via its constructor somewhere down the road.  If we aren&amp;rsquo;t using an IoC Container to manage its creation, we&amp;rsquo;d have to look for every place where the class is created, via the &lt;span style="font-family:&amp;#39;Courier New&amp;#39;, Courier, monospace;"&gt;new&lt;/span&gt; keyword, and pass in the extra dependency.  If we leave its creation to the IoC Container, then we simply add the new service interface parameter to its constructor and the IoC Container will take care of the rest, assuming you&amp;rsquo;ve registered the third dependency  as well.&amp;nbsp;&amp;nbsp;&lt;/li&gt;
&lt;li&gt;Invoke the IoC Container to instantiate a registered object with its dependencies already injected. &amp;nbsp; For our project, the following demonstrates getting a handle to the &lt;span style="font-family:&amp;#39;Courier New&amp;#39;, Courier, monospace;"&gt;WorldDomination&lt;/span&gt; class:
&lt;pre class="c-sharp" name="code"&gt;WorldDomination worldDomination = (WorldDomination) 
   ServiceLocator.Current.GetService(typeof(WorldDomination));&lt;/pre&gt;
This line of code tells the IoC Container to return an instance of the requested class with its dependencies injected.  This actually uses an IoC Container known as Common Service Locator.  Since almost all IoC Containers do the same actions &amp;ndash; registering and instantiating objects &amp;ndash; the major IoC Container authors worked together to establish a common interface for all IoC Containers.  In this way, you can register your objects with your favorite IoC Container and then register the IoC Container itself with the Common Service Locator.  It&amp;rsquo;s enough to make your head spin, but leads to further decoupling to the IoC Container itself so that you can easily swap out one for another (e.g., Castle Windsor for Ninject) without modifying the code which depends on the IoC Container.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;How you setup and use an IoC Container depends on the environment that you&amp;rsquo;re developing within. &amp;nbsp;For example, if you&amp;rsquo;re developing an ASP.NET MVC application, you can use an IoC Container to instantiate the controllers, injecting their dependencies via the controller&amp;rsquo;s constructor. &amp;nbsp;For example, the following two lines of code, within the Global.asax.cs file, instruct the ASP.NET MVC framework to use Castle Windsor to instantiate controllers:&lt;/p&gt;
&lt;pre class="c-sharp" name="code"&gt;IWindsorContainer container = new WindsorContainer();
ControllerBuilder.Current.SetControllerFactory(
   new WindsorControllerFactory(container));&lt;/pre&gt;
&lt;p&gt;The only thing left is to register the controller dependencies that they require for their constructors and the IoC Container takes care of the rest.&lt;/p&gt;
&lt;p&gt;While this will be enough to gain a basic understanding of what an IoC Container is and how it is used, a bit more studying will be required to learn how to actually set up and use one. &amp;nbsp;For more information about IoC Containers, including examples of setup and usage:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Common Service Locator: &amp;nbsp;&lt;a href="http://www.codeplex.com/CommonServiceLocator"&gt;http://www.codeplex.com/CommonServiceLocator&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;Castle Windsor Tutorial: &amp;nbsp;&lt;a href="http://www.castleproject.org/container/gettingstarted/"&gt;http://www.castleproject.org/container/gettingstarted/&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;LinFu in 5 Minutes: &amp;nbsp;&lt;a href="http://www.codeproject.com/KB/cs/LinFu_IOC.aspx"&gt;http://www.codeproject.com/KB/cs/LinFu_IOC.aspx&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;Using Ninject: &amp;nbsp;&lt;a href="http://ninject.codeplex.com/wikipage?title=user%20guide&amp;amp;ProjectName=ninject"&gt;http://ninject.codeplex.com/wikipage?title=user%20guide&amp;amp;ProjectName=ninject&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;StructureMap: &amp;nbsp;&lt;a href="http://structuremap.sourceforge.net"&gt;http://structuremap.sourceforge.net&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;A classic IoC Overview: &amp;nbsp;&lt;a href="http://martinfowler.com/articles/injection.html"&gt;http://martinfowler.com/articles/injection.html&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;Using IoC in a project: &amp;nbsp;&lt;a href="http://wiki.sharparchitecture.net/"&gt;http://wiki.sharparchitecture.net/&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Finally, for a much more thorough analysis of many of the concepts described above, I highly recommend reading Robert Martin&amp;#39;s&amp;nbsp;&lt;a href="http://www.amazon.com/Agile-Principles-Patterns-Practices-C/dp/0131857258/ref=sr_1_1?ie=UTF8&amp;amp;s=books&amp;amp;qid=1257809514&amp;amp;sr=1-1"&gt;Agile Principles, Patterns, and Practices in C#&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Final Thoughts&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;&lt;img style="border:0;float:right;margin:5px;" src="http://devlicio.us/resized-image.ashx/__size/550x0/__key/CommunityServer.Blogs.Components.WeblogFiles/billy_5F00_mccafferty/RobotInvasion.png" border="0" alt="" /&gt;Regardless of whether you&amp;rsquo;re looking to take over the world with a dominion of evil robots or simply trying to build a better web app, dependency injection and the use of an IoC Container can lead to an easy to maintain application that is loosely coupled to service dependencies. &amp;nbsp;These attributes naturally lead to better quality and happier developers. &amp;nbsp;(Both of which I would put squarely into a category known as &amp;ldquo;good.&amp;rdquo;) &amp;nbsp;But while these techniques provide many benefits, they also introduce a bit more complexity; especially when going from &amp;ldquo;manual&amp;rdquo; dependency injection, as we did in the coding example, to the use of an IoC Container. &amp;nbsp;Accordingly, your project team should carefully consider the benefits and added complexity to determine if it&amp;#39;s right for your project. &amp;nbsp;While the use of an IoC Container would be a bit overkill for a very simple application, its use is &lt;i&gt;obviously &lt;/i&gt;pivotal in creating self-aware robotic legions for conquering the world.&lt;/p&gt;
&lt;p&gt;Billy McCafferty&lt;br /&gt;&lt;a href="http://wiki.sharparchitecture.net/"&gt;http://wiki.sharparchitecture.net/&lt;/a&gt;&amp;nbsp;&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://devlicio.us/aggbug.aspx?PostID=53587" width="1" height="1"&gt;</description><category domain="http://devlicio.us/blogs/billy_mccafferty/archive/tags/Architecture/default.aspx">Architecture</category><category domain="http://devlicio.us/blogs/billy_mccafferty/archive/tags/Patterns/default.aspx">Patterns</category></item><item><title>The dojo is open...  www.ITSamuraiSchool.com</title><link>http://devlicio.us/blogs/billy_mccafferty/archive/2009/05/18/the-dojo-is-open-www-itsamuraischool-com.aspx</link><pubDate>Mon, 18 May 2009 22:52:00 GMT</pubDate><guid isPermaLink="false">40756a8b-6212-4073-9d98-6c26781577de:46899</guid><dc:creator>Billy McCafferty</dc:creator><slash:comments>11</slash:comments><description>&lt;p&gt;Codai&amp;#39;s IT Samurai School is open for enrollment.&amp;nbsp; It&amp;#39;s Flash, so it&amp;#39;ll take a few moments to download...but I hope you&amp;#39;ll agree it&amp;#39;s worth the wait...&amp;nbsp; &lt;a href="http://www.itsamuraischool.com"&gt;http://www.itsamuraischool.com&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;A few fun facts about the website and the school itself:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Born our of a short conversation at a BBQ concerning my desire to do high quality training&lt;/li&gt;
&lt;li&gt;100% Flash front-end, outside of the checkout screens&lt;/li&gt;
&lt;li&gt;Built on latest &lt;a href="http://code.google.com/p/sharp-architecture/"&gt;S#arp Architecture&lt;/a&gt; available from the trunk
&lt;/li&gt;
&lt;li&gt;6 months in the making, including the site and class preparation&lt;/li&gt;
&lt;li&gt;21 classes initially, including ASP.NET MVC, Object-Oriented JavaScript, SQL Server Integration Services, S#arp Architecture and many others&lt;/li&gt;
&lt;li&gt;5 cities initially, including Denver, Austin, San Jose, Washington DC, and Seattle&lt;/li&gt;
&lt;li&gt;A handful of top notch trainers, including myself (IMHO)&lt;/li&gt;
&lt;li&gt;Guest speakers and occasional, one-run only, unique courses&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;a title="IT Samurai School" href="http://www.itsamuraischool.com"&gt;&lt;img alt="Codai&amp;#39;s IT Samurai School" style="border:0;" src="http://devlicio.us/resized-image.ashx/__size/550x0/__key/CommunityServer.Blogs.Components.WeblogFiles/billy_5F00_mccafferty/dojo_5F00_screenshot.png" border="0" /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;We look forward to seeing you in class!&lt;/p&gt;
&lt;p&gt;Billy McCafferty&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://devlicio.us/aggbug.aspx?PostID=46899" width="1" height="1"&gt;</description><category domain="http://devlicio.us/blogs/billy_mccafferty/archive/tags/Architecture/default.aspx">Architecture</category><category domain="http://devlicio.us/blogs/billy_mccafferty/archive/tags/.NET/default.aspx">.NET</category><category domain="http://devlicio.us/blogs/billy_mccafferty/archive/tags/Software+Development/default.aspx">Software Development</category><category domain="http://devlicio.us/blogs/billy_mccafferty/archive/tags/Quality+Assurance/default.aspx">Quality Assurance</category><category domain="http://devlicio.us/blogs/billy_mccafferty/archive/tags/ASP.NET/default.aspx">ASP.NET</category><category domain="http://devlicio.us/blogs/billy_mccafferty/archive/tags/SQL+Server/default.aspx">SQL Server</category><category domain="http://devlicio.us/blogs/billy_mccafferty/archive/tags/Project+Management/default.aspx">Project Management</category><category domain="http://devlicio.us/blogs/billy_mccafferty/archive/tags/Patterns/default.aspx">Patterns</category><category domain="http://devlicio.us/blogs/billy_mccafferty/archive/tags/Test-Driven+Development/default.aspx">Test-Driven Development</category><category domain="http://devlicio.us/blogs/billy_mccafferty/archive/tags/Agile+Development/default.aspx">Agile Development</category><category domain="http://devlicio.us/blogs/billy_mccafferty/archive/tags/MVC.NET/default.aspx">MVC.NET</category><category domain="http://devlicio.us/blogs/billy_mccafferty/archive/tags/S_2300_arp+Architecture/default.aspx">S#arp Architecture</category><category domain="http://devlicio.us/blogs/billy_mccafferty/archive/tags/Tips+_2600_amp_3B00_+Tricks/default.aspx">Tips &amp;amp; Tricks</category><category domain="http://devlicio.us/blogs/billy_mccafferty/archive/tags/DDD/default.aspx">DDD</category></item><item><title>Refactoring Service Dependencies to Separated Interface</title><link>http://devlicio.us/blogs/billy_mccafferty/archive/2008/10/30/refactoring-service-dependencies-to-separated-interface.aspx</link><pubDate>Fri, 31 Oct 2008 00:06:00 GMT</pubDate><guid isPermaLink="false">40756a8b-6212-4073-9d98-6c26781577de:42831</guid><dc:creator>Billy McCafferty</dc:creator><slash:comments>18</slash:comments><description>&lt;p&gt;&lt;span style="font-size:x-small;"&gt;
&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;There are two factors which have a tremendous impact on a team&amp;#39;s likelihood to abandon unit testing:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Fragile tests which break often and require regular maintenance; and&lt;/li&gt;
&lt;li&gt;Slow tests which add excruciating seconds, if not minutes, to the total time of unit test runs.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;I find that fragile tests are often those that depend on data within a database, which can become out of synch with the assertions in the unit test, and those that depend on external services.&amp;nbsp; I use the term &amp;quot;services&amp;quot; loosely to define anything that represents an external resource; examples include web services (including RESTful services), file repositories, databases, and remote procedure calls.&amp;nbsp; But these dependencies on services aren&amp;#39;t just bad for keeping unit tests running fast and stable; they can often lead to maintenance problems due to tight coupling.&amp;nbsp; This post presents a common scenario wherein business logic is tightly coupled to a service and provides instruction for refactoring the concrete dependency to a more testable and loosely coupled configuration.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Separated Interface &amp;amp; Motivations for its Inclusion&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;The design pattern known as &amp;quot;Separated Interface&amp;quot; (coined by Martin Fowler; aka &amp;quot;Dependency Inversion&amp;quot; by Robert Martin) is a technique for reducing coupling to concrete dependencies; it achieves this by coding to the interface of the dependency while maintaining the implementation details of the dependency within a separate application layer.&amp;nbsp; You&amp;#39;ll find that the trick of using separated interface, as with any design pattern, is knowing &lt;em&gt;when&lt;/em&gt; to use it appropriately, rather than &lt;em&gt;how&lt;/em&gt; to use it, as the underlying mechanism is rather straight forward.&amp;nbsp; I find it best to use on most external services, as defined earlier, but should still be considered on a case by case basis.&amp;nbsp; You should ask yourself if introducing Separated Interface will make the overall application more maintainable and testable while keeping complexity to a minimum.&amp;nbsp; When used appropriately, the benefits of this decoupling include:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Improving the ability to unit test &amp;quot;around&amp;quot; the dependency using mocks/stubs,&lt;/li&gt;
&lt;li&gt;Greatly increasing the performance of domain oriented unit tests as a side effect of using mocks/stubs,&lt;/li&gt;
&lt;li&gt;Consolidating dependency communication details to a separate tier,&lt;/li&gt;
&lt;li&gt;Providing a plug-in architecture for external dependencies to be easily swapped without recompiling (e.g., when that 3rd party tool gets upgraded), and&lt;/li&gt;
&lt;li&gt;Allowing developers to develop and compile the domain logic without having all the dependencies in place (e.g., not having to install 3rd party tools A, B, and C just to develop and compile unrelated code).&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;To illustrate, the following diagram shows two separate assemblies within the project solution.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;The Project.Core assembly contains all of the domain logic for the application.&amp;nbsp; In addition to domain objects, such as Customer and Order, this example assembly also contains an interface to an external service; in this case, IOrderDao, which represents an interface to a data-access object.&amp;nbsp; Note that this is only the &lt;em&gt;interface&lt;/em&gt; of that service; the domain logic has no idea (or dependency) on the underlying implementation details outside of its conformance to the interface.&lt;/li&gt;
&lt;li&gt;The Project.Data assembly contains all of the implementation details for the interface and contains an assembly reference back to Project.Core.&amp;nbsp; &lt;em&gt;This is the fundamental key to Separated Interface.&lt;/em&gt;&amp;nbsp; In most applications, the data communications and external dependencies are depended on by the business logic.&amp;nbsp; With Separated Interface, the reverse is true wherein the service implementation depends on the interfaces within the domain layer - the true core of the application.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;img width="232" src="http://www.codeproject.com/KB/architecture/NHibernateBestPractices/SeparatedInterface.jpg" alt="Separated Interface" height="216" style="width:232px;height:216px;" title="Separated Interface" /&gt;&lt;/p&gt;
&lt;p&gt;This pattern typically presents two challenges.&amp;nbsp; The first is, how does the domain logic get passed a reference to the actual concrete dependency if all it knows about is an interface?&amp;nbsp; The dependency can get passed to the domain object via its constructor or a setter either manually or with an IoC container, such as &lt;a href="http://www.castleproject.org/container/index.html"&gt;Castle Windsor&lt;/a&gt; or &lt;a href="http://ninject.org/"&gt;Ninject&lt;/a&gt;.&amp;nbsp; (See &lt;a href="http://www.codeproject.com/KB/architecture/DependencyInjection.aspx"&gt;http://www.codeproject.com/KB/architecture/DependencyInjection.aspx&lt;/a&gt; for an example of doing so.)&amp;nbsp; The second and more challenging problem is, how can we get the external resource to depend on our domain layer interface when it&amp;#39;s a third party tool?&amp;nbsp; Recall that we want the service to depend on the domain, not the other way around.&amp;nbsp; In these cases, it&amp;#39;s appropriate to create a &lt;a href="http://en.wikipedia.org/wiki/Facade_pattern"&gt;facade&lt;/a&gt; which wraps the complicated details of communicating with the dependency; then, we simply add an interface for the facade to our domain layer.&amp;nbsp; The following example will walk through looking at a real world smell of a concrete dependency on a third party API - exposed as a RESTful service - and making appropriate modifications to introduce Separated Interface.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Real World Example (aka &amp;quot;the smell&amp;quot;)&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;To set the appropriate context, assume that (smelly) code has been developed to fulfill the following user story:&amp;nbsp; On a nightly basis, the application will download any new Observations added during the previous day,&amp;nbsp;input into ExternalApp, so that they may be copied locally.&amp;nbsp; (An &amp;quot;observation&amp;quot; is the domain name of the record we&amp;#39;re retrieving.)&amp;nbsp; The idea is that an external application exists, aptly called ExternalApp, which exposes a RESTful service to retrieve newly added records.&amp;nbsp; Our nightly process ties into the service, retrieves the appropriate records, parses the response, and copies the appropriate information locally.&lt;/p&gt;
&lt;p&gt;Our application currently has three tiers:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;The MySynch.Tests assembly contains unit tests to verify these processes.&amp;nbsp; (No, of course we didn&amp;#39;t call it &amp;quot;MySynch,&amp;quot; but that&amp;#39;ll work for now.)&lt;/li&gt;
&lt;li&gt;The MySynch.Core assembly contains all of the business logic for communicating with the RESTful service and processing the results.&amp;nbsp; Assume it contains one object called ObservationMigrator which encapsulates this logic.&lt;/li&gt;
&lt;li&gt;The MySynch.Console application which is the nightly process, which we won&amp;#39;t concern ourselves with here.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;The following unit tests, found in the folder MySynch.Tests/Core, verify that the records can be retrieved and that the data migration is successful:&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;pre name="code" class="c#:nogutter:nocontrols"&gt;[TestFixture]
public class ObservationMigratorTests
{
    [Test]
    public void CanRetrieveObservationRecords() {
        ObservationMigrator migrator = new ObservationMigrator();
        IList&amp;lt;Observation&amp;gt; observations = migrator.GetNewObservations();
        Assert.That(observations.Count, Is.GreaterThan(0));
    }
    [Test]
    public void CanMigrateObservationRecords() {
        ObservationMigrator migrator = new ObservationMigrator();
        Result result = migrator.MigrateRecords();
        Assert.That(result.CompletedSuccefully);
    }
}&lt;/pre&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;p&gt;The first test is really verifying if the communications with the RESTful service - the third party tool - are successful.&amp;nbsp; The second test is verifying if the data migration occurs successfully, assuming the communications with the RESTful service are successful.&amp;nbsp; Without even looking at the underlying code, these tests are already unveiling a number of smells:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;div&gt;It&amp;#39;s obvious that the ObservationMigrator isn&amp;#39;t adhering to the &lt;a href="http://www.objectmentor.com/resources/articles/srp.pdf"&gt;Single Responsibility Principle (SRP)&lt;/a&gt;.&amp;nbsp; It&amp;#39;s providing means to communicate with the service, via GetNewObservations, and it&amp;#39;s responsible for migrating those records to whatever destination.&amp;nbsp; Consequently, it&amp;#39;s likely that it&amp;#39;s inherently complex and that it&amp;#39;s likely to be touched often during maintenance for different reasons.&lt;/div&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;div&gt;The second test is really just trying to make sure that the migration occurs successfully without necessarily wanting to retest proper communications to the RESTful service; that was what the first test was doing.&amp;nbsp; The problem with this is that if the service goes down, in addition to breaking the first test, it&amp;#39;ll start breaking the second test which is really domain-oriented in nature.&amp;nbsp; It would be great if we could test the migration process without having to retest the communications to the service.&lt;/div&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;div&gt;Finally, communicating with any external resource via unit tests, especially web-based services, adds seconds to running the unit tests.&amp;nbsp; This can add minutes with hundreds of unit tests.&amp;nbsp; Again, if all we really want to test in the second test is the domain logic for completing the migration, then we shouldn&amp;#39;t be reconfirming communications are working and adding wasted time to running the tests.&lt;/div&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Indeed, if we look under the covers at the ObservationMigrator class, we confirm our concerns with respect to SRP and HTTP requests embedded into the business logic:&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;pre name="code" class="c#:nogutter:nocontrols"&gt;public class ObservationMigrator
{
    public IList&amp;lt;Observation&amp;gt; GetNewObservations() {
        WebClient webClient = new WebClient();
        byte[] response = webClient
            .DownloadData(&amp;quot;http://www.example.com/RESTfulServiceToRetrieveRecords&amp;quot;);
        string responseContent = Encoding.ASCII.GetString(response);
        IList&amp;lt;Observation&amp;gt; observations = new List&amp;lt;Observation&amp;gt;();
        // Lots of complicated parsing...like, crazy complicated
        return observations;
    }
    // Result is a DTO which let&amp;#39;s the caller know if everything succeeded
    public Result MigrateRecords() {
        IList&amp;lt;Observation&amp;gt; observations = GetNewObservations();
        foreach (Observation observation in observations) {
            // Migrate each observation to the appropriate repository
        }
        return new Result(...);
    }
}&lt;/pre&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Refactoring Mechanics&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;In refactoring this code, we&amp;#39;ll want to follow the steps below to reduce the amount of work done between tests and to minimize the amount of breaking code in the system at any given point in time.&amp;nbsp; Our goal is to always be very close to a check-in...the &amp;quot;don&amp;#39;t anybody check anything out for the next two days&amp;quot; won&amp;#39;t fly here.&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;
&lt;div&gt;Refactor with&amp;nbsp;&lt;a href="http://www.refactoring.com/catalog/extractClass.html"&gt;Extract Class&lt;/a&gt; to pull the RESTful communication and parsing logic into it&amp;#39;s own class.&amp;nbsp; This extracted class becomes the facade to the underlying RESTful API.&lt;/div&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;div&gt;Refactor with&amp;nbsp;&lt;a href="http://www.refactoring.com/catalog/extractInterface.html"&gt;Extract Interface&lt;/a&gt; to create an interface for the new API facade.&lt;/div&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;div&gt;Refactor with&amp;nbsp;&lt;a href="http://xunitpatterns.com/Dependency%20Injection.html"&gt;Introduce Constructor Injection&lt;/a&gt; to replace the creation of the dependency with a constructor parameter.&lt;/div&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;div&gt;Refactor with&amp;nbsp;&lt;a href="http://martinfowler.com/articles/mocksArentStubs.html"&gt;Introduce Stub Object&lt;/a&gt; to modify the testing of the migration test to focus on the domain logic rather than on retesting communications with the API.&lt;/div&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;div&gt;&lt;a href="http://www.refactoring.com/catalog/refactorArchitectureByTiers.html"&gt;Refactor Architecture by Tiers&lt;/a&gt; to move the implementation details to a separate tier.&lt;/div&gt;
&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;&lt;strong&gt;Step 1:&amp;nbsp; Extract Class&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;So without further ado, let&amp;#39;s start with step 1, extracting a class to act as a facade to the underlying RESTful API.&amp;nbsp; As always, we begin with a test; let&amp;#39;s do so by adding a new test as follows:&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;pre name="code" class="c#:nogutter:nocontrols"&gt;[TestFixture]
[Category(&amp;quot;ExternalApp Integration&amp;quot;)]
public class ObservationRetrieverTests
{
    [Test]
    public void CanRetrieveRecordsToImport() {
        ObservationRetriever observationRetriever = new ObservationRetriever();
        IList&amp;lt;Observation&amp;gt; observations = observationRetriever.GetNewObservations();
        Assert.That(observations.Count, Is.GreaterThan(0));
    }
}&lt;/pre&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;p&gt;Note that we&amp;#39;ve added this fixture to a category called &amp;quot;ExternalApp Integration.&amp;quot;&amp;nbsp; Doing so, we&amp;#39;re able to conveniently turn off this slow-running category of unit tests while we&amp;#39;re working on other areas of the application.&amp;nbsp; Compiling this breaks, so the next step is to add just enough code to MySynch.Core to get the test to compile:&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;p&gt;&lt;span style="font-size:x-small;"&gt;&lt;/span&gt;&lt;/p&gt;
&lt;pre name="code" class="c#:nogutter:nocontrols"&gt;public class ObservationRetriever
{
    public IList&amp;lt;Observation&amp;gt; GetNewObservations() {
        throw new NotImplementedException();
    }
}&lt;/pre&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;p&gt;You should now be able to run the test and see it fail with a NotImplementedException.&amp;nbsp; Yes, you want it to fail...a failing test is your next goal to fix.&amp;nbsp; So now let&amp;#39;s write enough code to get it to pass by copying the GetNewObservations() method from ObservationMigrator into ObservationRetriever:&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;pre name="code" class="c#:nogutter:nocontrols"&gt;public class ObservationRetriever
{
    public IList&amp;lt;Observation&amp;gt; GetNewObservations() {
        WebClient webClient = new WebClient();
        byte[] response = webClient
            .DownloadData(&amp;quot;http://www.example.com/RESTfulServiceToRetrieveRecords&amp;quot;);
        string responseContent = Encoding.ASCII.GetString(response);
        IList&amp;lt;Observation&amp;gt; observations = new List&amp;lt;Observation&amp;gt;();
        // Lots of complicated parsing...like, crazy complicated
        return observations;
    }
}&lt;/pre&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;p&gt;All the unit tests should now be passing again.&amp;nbsp; But we&amp;#39;ve introduced a problem...the smell of duplicated code.&amp;nbsp; We can remove this smell by replacing the ObservationMigrator.GetNewObservations() method with the creation of an ObservationRetriever object and the invocation of the method therein:&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;pre name="code" class="c#:nogutter:nocontrols"&gt;public class ObservationMigrator
{
    public Result MigrateRecords() {
        ObservationRetriever observationRetriever = new ObservationRetriever();
        IList&amp;lt;Observation&amp;gt; observations = observationRetriever.GetNewObservations();
        foreach (Observation observation in observations) {
            // Migrate each observation to the appropriate repository
        }
        return new Result(...);
    }
}&lt;/pre&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;p&gt;You&amp;#39;ll need to drop ObservationMigratorTests.CanRetrieveObservationRecords() to get it to compile; but all the tests should still be passing.&amp;nbsp; We&amp;#39;ve officially completed step 1 by extracting a class from the ObservationMigrator class into a facade class which only concerns itself with communicating with the RESTful API and parsing the results.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Step 2:&amp;nbsp; Extract Interface&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Step 2 is introducing the interface to our service.&amp;nbsp; Instead of creating a new test, we simply modify the ObservationRetrieverTests.CanRetrieveRecordsToImport() method to invoke GetNewObservations() via an interface rather than the concrete object itself:&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;pre name="code" class="c#:nogutter:nocontrols"&gt;[TestFixture]
[Category(&amp;quot;ExternalApp Integration&amp;quot;)]
public class ObservationRetrieverTests
{
    [Test]
    public void CanRetrieveRecordsToImport() {
        // Note the &amp;quot;I&amp;quot; that&amp;#39;s been introduced below
        IObservationRetriever observationRetriever = new ObservationRetriever();
        IList&amp;lt;Observation&amp;gt; observations = observationRetriever.GetNewObservations();
        Assert.That(observations.Count, Is.GreaterThan(0));
    }
}&lt;/pre&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;p&gt;Since a quick compilation shows that this isn&amp;#39;t compilable (and it shouldn&amp;#39;t be), let&amp;#39;s add an interface to MySynch.Core which reflects the method on our facade class, and have ObservationRetriever then implement that interface.&amp;nbsp; First, the interface that we need to add to MySynch.Core:&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;pre name="code" class="c#:nogutter:nocontrols"&gt;public interface IObservationRetriever
{
    IList&amp;lt;Observation&amp;gt; GetNewObservations();
}&lt;/pre&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;p&gt;Then, simply have the ObservationRetriever class implement this interface:&amp;nbsp; public class ObservationRetriever : IObservationRetriever { ...&lt;/p&gt;
&lt;p&gt;All unit tests should be passing again...oh, happy days again.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Step 3:&amp;nbsp; Introduce Constructor Injection&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;The ObservationMigrator class still has a concrete dependency on the ObservationRetriever...damn that concrete dependency!!&amp;nbsp; So let&amp;#39;s now introduce constructor injection to remove this tight coupling.&amp;nbsp; Guess where we&amp;#39;re going to start...that&amp;#39;s right, back in a unit test.&amp;nbsp; But here again, we don&amp;#39;t need to add a new test, we simply need to alter an existing one, ObservationMigratorTests.CanMigrateObservationRecords().&amp;nbsp; The modified test should be as follows:&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;pre name="code" class="c#:nogutter:nocontrols"&gt;[Test]
public void CanMigrateObservationRecords() {
    IObservationRetriever observationRetriever = new ObservationRetriever();
    ObservationMigrator migrator = new ObservationMigrator(observationRetriever);
    Result result = migrator.MigrateRecords();
    Assert.That(result.CompletedSuccefully);
}&lt;/pre&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;p&gt;All we&amp;#39;re intending to do here is to pass an instance of IObservationRetriever to the migration utility rather than having it create its own.&amp;nbsp; Tying to compile breaks the build, so now let&amp;#39;s write just enough code to get this puppy to compile...usually we&amp;#39;d write just enough to compile and then just enough to pass, but I&amp;#39;m getting tired of writing, so we&amp;#39;ll combine the two here:&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;pre name="code" class="c#:nogutter:nocontrols"&gt;public class ObservationMigrator
{
    public ObservationMigrator(IObservationRetriever observationRetriever) {
        // Let&amp;#39;s do a design-by-contract (DbC) check to make sure we&amp;#39;re not 
        // given a null service dependency. For more about this, see 
        // http://devlicio.us/blogs/billy_mccafferty/archive/2006/09/22/Design_2D00_by_2D00_Contract_3A00_-A-Practical-Introduction.aspx
        Check.Require(observationRetriever != null, 
            &amp;quot;observationRetriever may not be null&amp;quot;);
        this.observationRetriever = observationRetriever;
    }
    public Result MigrateRecords() {
        IList&amp;lt;Observation&amp;gt; observations = observationRetriever.GetNewObservations();
        foreach (Observation observation in observations) {
            // Migrate each observation to the appropriate repository
        }
        return new Result(...);
    }
    private IObservationRetriever observationRetriever;
}&lt;/pre&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;p&gt;With these changes, everything should now compile and the tests should be passing again.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Step 4:&amp;nbsp; Introduce Stub Object&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;As mentioned in the previous gripes against the original code, the ObservationMigratorTests.CanMigrateObservationRecords() test shouldn&amp;#39;t be worried about communicating with the RESTful service; it should only be concerned with ensuring the migration occurs assuming the RESTful service is working as expected.&amp;nbsp; The ObservationRetrieverTests.CanRetrieveRecordsToImport() test is already verifying that the service is working, so it&amp;#39;s just adding extra time and complexity to the ObservationMigratorTests.CanMigrateObservationRecords() test.&amp;nbsp; Therefore, let&amp;#39;s now introduce a stub object to simulate communications with the RESTful service.&amp;nbsp; Keep in mind that this modification isn&amp;#39;t being done to test new functionality; instead, it&amp;#39;s a refactoring to an existing unit test to properly focus the test&amp;#39;s attention on the domain logic.&amp;nbsp; Accordingly, the ObservationMigratorTests now reflects the following:&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;pre name="code" class="c#:nogutter:nocontrols"&gt;[TestFixture]
public class ObservationMigratorTests
{
    [Test]
    public void CanMigrateObservationRecords() {
        IObservationRetriever observationRetriever = new ObservationRetrieverStub();
        ObservationMigrator migrator = new ObservationMigrator(observationRetriever);
        Result result = migrator.MigrateRecords();
        Assert.That(result.CompletedSuccefully);
    }
    private class ObservationRetrieverStub : IObservationRetriever
    {
        public IList&amp;lt;Observation&amp;gt; GetNewObservations() {
            IList&amp;lt;Observation&amp;gt; observations = new List&amp;lt;Observation&amp;gt;();
            observations.Add(new Observation(...));
            observations.Add(new Observation(...));
            observations.Add(new Observation(...));
            return observations;
        }
    }
}&lt;/pre&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;p&gt;In the unit test above, a stub object has been created which implements IObservationRetriever and fakes communications with the external service to retrieve three new Observation records.&amp;nbsp; The ObservationMigrator.MigrateRecords() method happily uses this stub, not knowing that it&amp;#39;s actually not talking to the external RESTful service.&amp;nbsp; We&amp;#39;re now focusing this unit test on testing the domain logic, outside of communicating with the RESTful service.&amp;nbsp; Again, the ObservationRetrieverTests fixture of tests is already testing the communications with this service and related parsing functionality...no need to retest it here.&lt;/p&gt;
&lt;p&gt;In such a simple case, where the interface only has one method to implement, a stub is perfectly adequate.&amp;nbsp; But we&amp;#39;re passing three observations to the migration step without verifying that all three were processed...we might as well have just passed one, or none at all for that matter.&amp;nbsp; This test could be&amp;nbsp;extended in two ways to verify the underlying migration processed each and every Observation appropriately.&amp;nbsp; The first is that we could include the status of how many observations were migrated within the Result object returned from the migration step.&amp;nbsp; The&amp;nbsp;other way is to use a mock object, instead of a stub, which can verify that the expected behavior is occurring under the scenes.&amp;nbsp; Although mocking is beyond the scope of this post, I encourage you to take a look at &lt;a href="http://xunitpatterns.com/"&gt;http://xunitpatterns.com/&lt;/a&gt;&amp;nbsp;and &lt;a href="http://ayende.com/wiki/Rhino+Mocks+Documentation.ashx"&gt;Rhino Mocks&lt;/a&gt; for more information.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Step 5:&amp;nbsp; Refactor Architecture by Tiers&lt;/strong&gt;&lt;br /&gt;(i.e., add the &amp;quot;Separated&amp;quot; part of &amp;quot;Separated Interface&amp;quot;)&lt;/p&gt;
&lt;p&gt;After all of this, we&amp;#39;re finally at the point of culmination:&amp;nbsp; the introduction of the Separated Interface.&amp;nbsp; But by now, it&amp;#39;s rather anticlimactic as the hard work has already been done.&amp;nbsp; Nonetheless...on with the anticlimactic conclusion!&amp;nbsp; A problem with the solution as it stands is that the service facade still physically resides in the MySynch.Core assembly.&amp;nbsp; Consequently, there&amp;#39;s nothing we can do to prevent developers from bypassing our elegant interface and go straight to the ObservationRetriever class itself.&amp;nbsp; This is a wonderful side benefit of introducing Separated Interface; it forces developers to adhere to certain design decisions.&amp;nbsp; To mitigate this concern, and to remove all coupling from MySynch.Core to the implementation details of ObservationRetriever, we&amp;#39;ll refactor the architecture itself to move the implementation details to a separate tier.&amp;nbsp; Let&amp;#39;s head back to the tests assembly and add a new &lt;em&gt;folder&lt;/em&gt; called ExternalAppIntegrator; recall that &amp;quot;ExternalApp&amp;quot; is the name of our 3rd party tool which exposes the RESTful service.&amp;nbsp; Now move the ObservationRetrieverTests class to this new folder.&amp;nbsp; This new folder represents the new class library that we&amp;#39;ll be introducing.&amp;nbsp; The ObservationRetrieverTests class should then be modified to reflect the change in namespace and a using statement to pull in the class library which we have not yet created (remember...write the test and &lt;em&gt;then&lt;/em&gt; write the code to get the test to pass):&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;pre name="code" class="c#:nogutter:nocontrols"&gt;using NUnit.Framework;
using NUnit.Framework.SyntaxHelpers;
using System.Collections.Generic;
// The compiler will throw an error on the following line since 
// the ExternalAppIntegrator.Core class library doesn&amp;#39;t exist yet
using ExternalAppIntegrator.Core;
namespace Tests.ExternalAppIntegrator.Core
{
    [TestFixture]
    [Category(&amp;quot;ExternalApp Integration&amp;quot;)]
    public class ObservationRetrieverTests
    {
        [Test]
        public void CanRetrieveRecordsToImport() {
            IObservationRetriever observationRetriever = 
                new ObservationRetriever();
            IList&amp;lt;Observation&amp;gt; observations = 
                observationRetriever.GetNewObservations();
            Assert.That(observations.Count, Is.GreaterThan(0));
        }
    }
}&lt;/pre&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;p&gt;We&amp;#39;ve introduced some work for us here, but we will overcome!&amp;nbsp; Firstly, create a new class library called &amp;quot;ExternalAppIntegrator.Core&amp;quot; and add a reference to it from our MySynch.Tests assembly.&amp;nbsp; Next, move the class MySynch.Core/ObservationRetriever.cs to the ExternalAppIntegrator.Core class library...be sure you move it completely by deleting the original.&amp;nbsp; Ack...a new problem now!&amp;nbsp; We&amp;#39;ve moved the class but it depended upon IObservationRetriever.&amp;nbsp; Fear not!&amp;nbsp; Simply add a reference to MySynch.Core to the ExternalAppIntegrator.Core class library.&amp;nbsp; Since we&amp;#39;ve removed all other dependencies to the ObservationRetriever from MySynch.Core, all the unit tests will still pass.&amp;nbsp; As a matter of fact, we&amp;#39;re done!&lt;/p&gt;
&lt;p&gt;But wait, how do we know it&amp;#39;s working?&amp;nbsp; Although not necessary, since the unit testing has proven&amp;nbsp;that all of the&amp;nbsp;inner workings are in order, we can make sure our Separated Interface is working as expected with the rest of the migration process by going back to ObservationMigratorTests.CanMigrateObservationRecords() and replacing the creation of the stub object with our concrete implementation:&amp;nbsp; IObservationRetriever observationRetriever = new ObservationRetriever();&amp;nbsp; With that said, I&amp;#39;d quickly change it back to using the stub so that we can keep that unit test focused on the domain rather than communications with the RESTful service.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;In Conclusion&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;We&amp;#39;ve taken some rather smelly dependencies and moved them to a dedicated class library which concerns itself with the management of a facade over the external API.&amp;nbsp; We finished by having this facade implement an interface found without our domain layer so that the domain layers could communicate to the external API without having a direct, concrete dependency on the implmentation details.&amp;nbsp; The hope is that this has made our code more testable, less coupled, and more maintainable down the road.&amp;nbsp; The cost has been the introduction of increased complexity.&amp;nbsp; Accordingly, care should be taken before the introduction of any design pattern to ensure that the pattern itself is &amp;quot;pulling its weight,&amp;quot; so to speak.&lt;/p&gt;
&lt;p&gt;I have found immense value from this design pattern; it has been particularly handy for removing direct dependencies on data access objects.&amp;nbsp; The sample code that comes along with&amp;nbsp;&lt;a href="http://code.google.com/p/sharp-architecture/"&gt;S#arp Architecture&lt;/a&gt; has a full example of just such an instance.&amp;nbsp; Happy coding!&lt;/p&gt;
&lt;p&gt;Billy McCafferty&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://devlicio.us/aggbug.aspx?PostID=42831" width="1" height="1"&gt;</description><category domain="http://devlicio.us/blogs/billy_mccafferty/archive/tags/Architecture/default.aspx">Architecture</category><category domain="http://devlicio.us/blogs/billy_mccafferty/archive/tags/Patterns/default.aspx">Patterns</category><category domain="http://devlicio.us/blogs/billy_mccafferty/archive/tags/S_2300_arp+Architecture/default.aspx">S#arp Architecture</category></item><item><title>(Re)Assessing Best Practices</title><link>http://devlicio.us/blogs/billy_mccafferty/archive/2007/10/15/re-assessing-best-practices.aspx</link><pubDate>Mon, 15 Oct 2007 18:47:00 GMT</pubDate><guid isPermaLink="false">40756a8b-6212-4073-9d98-6c26781577de:38682</guid><dc:creator>Billy McCafferty</dc:creator><slash:comments>10</slash:comments><description>&lt;p&gt;As we progress as developers, we strive to seek out the &amp;quot;best&amp;quot; way to perform our craft. The chosen methods to attain this lofty goal always bring with them a number of developmental trade-offs. Some techniques may simplify the code but lessen fine grained control while others enable greater power while introducing complexity. &lt;a href="http://www.codeproject.com/aspnet/ModelViewPresenter.asp"&gt;Model-View-Presenter with ASP.NET&lt;/a&gt; is a wonderful example of the latter. MVP aims to facilitate test-driven development of ASP.NET applications with the unfortunate introduction of added complexity. So while developers will be more confient in the quality of their product, MVP hinders their ability to easily maintain code. Yes, the tests will (hopefully) inform the developer that a bug has been introduced, but the inherent complexity of MVP makes it difficult for later team members to become comfortable with the code base and maintain it as project development continues.&lt;/p&gt;
&lt;p&gt;Fortunately, as time progresses quickly in our field, resources and tools become available which enhance our ability to write powerful applications while simplifying the coding process itself. The introduction of &lt;a href="http://www.hibernate.org/343.html"&gt;NHibernate&lt;/a&gt;, for example, eliminated vast amounts of data-access code while still providing powerful facilities for managing transactions and dynamically querying data. &lt;a href="http://www.castleproject.org/"&gt;Castle MonoRail&lt;/a&gt; (and &lt;a href="http://weblogs.asp.net/scottgu/archive/2007/10/14/asp-net-mvc-framework.aspx"&gt;Microsoft&amp;#39;s upcoming&lt;/a&gt; &lt;a href="http://codebetter.com/blogs/jeffrey.palermo/archive/2007/10/05/altnetconf-scott-guthrie-announces-asp-net-mvc-framewor

k-at-alt-net-conf.aspx"&gt;spin-off&lt;/a&gt; &lt;a href="http://www.hanselman.com/blog/ScottGuMVCPresentationAndScottHaScreencastFromALTNETConference.aspx"&gt;of this framework&lt;/a&gt;) now does for writing testable and maintainable .NET web applications what NHibernate (and the upcoming &lt;a href="http://msdn2.microsoft.com/en-us/library/aa697427(vs.80).aspx"&gt;LINQ to Entities&lt;/a&gt;) did for ADO.NET. This is not to say that the previous techniques were necessarily wrong, but that they were only applicable considering the developer&amp;#39;s toolset that was available at the time of selection.&lt;/p&gt;
&lt;p&gt;In adapting to the evolution of our field, it is important for developers to note when an accepted technique is no longer valuable in light of current alternatives. Specifically to this example, MVP was a very powerful technique for writing ground-up, test-driven ASP.NET applications but is no longer a strong candidate for consideration when compared to the time saving benefits and simplicity of Castle MonoRail and Microsoft&amp;#39;s upcoming MVC framework. Oddly, it is sometimes difficult to &amp;quot;give up&amp;quot; on something that worked perfectly fine before, but that&amp;#39;s the nature of our business...one tenet that&amp;#39;s not likely to change anytime soon.&lt;/p&gt;
&lt;p&gt;Billy McCafferty&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://devlicio.us/aggbug.aspx?PostID=38682" width="1" height="1"&gt;</description><category domain="http://devlicio.us/blogs/billy_mccafferty/archive/tags/DeepThoughtsByJackHandey/default.aspx">DeepThoughtsByJackHandey</category><category domain="http://devlicio.us/blogs/billy_mccafferty/archive/tags/Patterns/default.aspx">Patterns</category><category domain="http://devlicio.us/blogs/billy_mccafferty/archive/tags/Featured/default.aspx">Featured</category></item><item><title>Considering a View's Get/Set Roles with MVP</title><link>http://devlicio.us/blogs/billy_mccafferty/archive/2007/03/19/considering-a-view-s-get-set-roles-with-mvp.aspx</link><pubDate>Mon, 19 Mar 2007 15:40:00 GMT</pubDate><guid isPermaLink="false">40756a8b-6212-4073-9d98-6c26781577de:17256</guid><dc:creator>Billy McCafferty</dc:creator><slash:comments>11</slash:comments><description>&lt;p&gt;[Update May 7, 2007:&amp;nbsp;&amp;nbsp;Added sequence diagram,&amp;nbsp;submitted by Yanic Inghelbrecht,&amp;nbsp;to better explain &amp;quot;Use Update&amp;nbsp;Method&amp;nbsp;in lieu of&amp;nbsp;Getter&amp;quot; technique.]&lt;/p&gt;
&lt;p&gt;There are many ways to implement Model-View-Presenter; &lt;a href="http://www.martinfowler.com/eaaDev/SupervisingPresenter.html"&gt;Supervising Controller&lt;/a&gt; and &lt;a href="http://www.martinfowler.com/eaaDev/PassiveScreen.html"&gt;Passive View&lt;/a&gt; are just two implementation examples.&amp;nbsp; A question was asked on my &lt;a href="http://www.codeproject.com/aspnet/ModelViewPresenter.asp"&gt;overview of the subject&lt;/a&gt; as to whether or not a view&amp;#39;s properties should have both setters &lt;em&gt;and&lt;/em&gt; getters.&amp;nbsp; For example, consider an &amp;quot;add/edit customer&amp;quot; view.&amp;nbsp; This view first shows the available customer data,&amp;nbsp;via a setter on the view,&amp;nbsp;and then allows the user to update the information displayed.&amp;nbsp; Should the view have both a setter&amp;nbsp;&lt;em&gt;and&lt;/em&gt; a getter for the customer class?&amp;nbsp; (As I understand it, if you&amp;#39;re using Passive View, this is a moot question as the view should not be intelligent enough to interpret and/or&amp;nbsp;update the domain model directly.)&amp;nbsp; But if you&amp;#39;re using Supervising Controller or another approach which allows the view to know about the domain model (or DTOs for the domain model) then this is a&amp;nbsp;great question to discuss.&amp;nbsp; I&amp;#39;ll&amp;nbsp;list the (un)successful approaches I&amp;#39;ve used and pros/cons of each.&amp;nbsp; (Here, I use &amp;quot;entity&amp;quot; to mean any domain object that&amp;#39;s stored within the DB.)&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Return Ready-to-Save&amp;nbsp;Entity from View via Getter&lt;br /&gt;&lt;/strong&gt;With NHibernate, if you have a ready-for-storage entity, you may simply call SaveOrUpdate on that object.&amp;nbsp; If a new&amp;nbsp;entity is being created, then the view may need to work with factories and/or&amp;nbsp;be aware of&amp;nbsp;the business rules for creating a ready-to-save entity.&amp;nbsp; The internal consistency of&amp;nbsp;that object&amp;nbsp;can, obviously, be verified by the presenter or validation logic built into the domain object itself, but I never liked this approach as it gives the view a lot of responsibility for creating a new entity and creates a lot of untestable code.&lt;/p&gt;
&lt;p&gt;If an &lt;em&gt;existing&lt;/em&gt; entity is simply being updated and returned via the getter, the view&amp;nbsp;must have a handle on the existing entity to update it.&amp;nbsp;&amp;nbsp;Accordingly, the view can:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;Re-create the entity from scratch, set its ID accordingly, and return the ready-to-save object.&amp;nbsp; This approach is wrought with problems.&amp;nbsp; If the view gives the recreated object a wrong ID, you&amp;#39;ve now corrupted your data.&amp;nbsp; In my &lt;a href="http://www.codeproject.com/aspnet/NHibernateBestPractices.asp"&gt;overview of NHibernate&lt;/a&gt;, I exposed ID as a publicly, settable property.&amp;nbsp; In my upcoming update to this article, I recommend &lt;strong&gt;not&lt;/strong&gt;&amp;nbsp;exposing&amp;nbsp;the ID setter.&amp;nbsp; Only the ORM or entity-loader should be able to set this critical property.&amp;nbsp; As another drawback, if the&amp;nbsp;entity&amp;nbsp;keeps track of&amp;nbsp;auditing information, such as DateCreated, this approach will overwrite it.&amp;nbsp; There are other drawbacks to this approach and it should be avoided.&lt;/li&gt;
&lt;li&gt;The view can talk to a DAO directly to get the existing entity, update it&amp;#39;s properties, and return it to the view.&amp;nbsp; Although not as bug-prone as the&amp;nbsp;previous suggestion, this now gives the view the responsibility of coordinating with the data-access layer directly.&amp;nbsp; This grays the line between the responsibilities of the view and the other layers of the application and adds non-trivial business logic to the view which is difficult to test.&lt;/li&gt;
&lt;li&gt;The view can be given a direct handle to the loaded entity by the presenter via another setter.&amp;nbsp; This seems a bit round-about and depends on a two-step process.&amp;nbsp; Additionally, the view now has two setters which may be confusing and difficult to maintain.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;&lt;strong&gt;Return DTO from Getter&lt;/strong&gt;&lt;br /&gt;Instead of returning a fully ready-to-save&amp;nbsp;object from the view, the view could, alternatively return a DTO consisting of only the&amp;nbsp;appropriate information to be updated.&amp;nbsp; The presenter could, in turn, get the existing object from the DB (or create a new one), transfer the DTO information onto the persistent object, and save it back to the DB.&amp;nbsp; The primary benefit is that you can completely separate the view from knowing anything about the domain model while still being able to communicate more than one primitive at a time.&amp;nbsp; The major drawback is that DTOs now need to be maintained along with their domain model pairs.&amp;nbsp; So if you add a new, updateable property to the domain object, you&amp;#39;ll then need to add the property to the DTO and then&amp;nbsp;modify the DTO-to-domain-object transfer logic within the presenter.&amp;nbsp; (Alternatively, You could also add an UpdateWith(DTO) to the entity so that the transfer logic is more contained, but it still&amp;nbsp;leads to&amp;nbsp;further maintenance.)&amp;nbsp; But the bottom&amp;nbsp;line is that this is a good approach if you really need to keep your views from having a direct dependency on the domain layer.&amp;nbsp; Because of this clean separation, this brings the added benefit of removing temptation for domain logic to bleed into views since the view is limited&amp;nbsp;to communicating with the Presenters/DTO layer.&amp;nbsp; But again, it comes with a lot of additional maintenance to keep the DTOs synched with the domain model.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Use Update&amp;nbsp;Method&amp;nbsp;in lieu of&amp;nbsp;Getter&lt;br /&gt;&lt;/strong&gt;A simpler approach that I&amp;#39;m having luck with is including a separate update method on the view and not having a getter for the entity.&amp;nbsp; Going back to the &amp;quot;add/edit customer&amp;quot; example, a&amp;nbsp;&amp;quot;Customer { set; }&amp;quot;&amp;nbsp;would&amp;nbsp;be on the view interface to show the data, but not a getter.&amp;nbsp; The view interface would then also include a &amp;quot;void Update(Customer customer);&amp;quot; method.&amp;nbsp; Accordingly, the view would then accept a customer object from the presenter and&amp;nbsp;update its properties from the view.&amp;nbsp; The communications would be as follows:&lt;/p&gt;
&lt;p&gt;&lt;img width="589" src="http://www.codeproject.com/kb/architecture/ModelViewPresenter/UseUpdateMethodInLieuOfGetter.gif" height="357" style="width:589px;height:357px;" alt="" /&gt;&lt;/p&gt;
&lt;p&gt;The above image was created and submitted by Yanic Inghelbrecht via &lt;a href="http://www.tracemodeler.com"&gt;Trace Modeler&lt;/a&gt;.&amp;nbsp; Thanks Yanic!&lt;/p&gt;
&lt;p&gt;The sequence diagram&amp;nbsp;is interpreted as follows:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;User clicks &amp;quot;Save Changes&amp;quot; button which invokes btnSaveChanged_OnClick in the code-behind.&lt;/li&gt;
&lt;li&gt;Code-behind calls presenter.SaveChangesTo(customerId).&lt;/li&gt;
&lt;li&gt;Presenter talks to the Customer DAO (or service layer) to&amp;nbsp;get the loaded entity from the DB, using the ID passed to it from the view.&amp;nbsp; (If the ID was 0, then the Presenter creates a new entity via a constructor or factory.)&lt;/li&gt;
&lt;li&gt;Presenter calls view.Update(customerToBeSaved), passing the entity loaded from the DB.&lt;/li&gt;
&lt;li&gt;View updates the entity with values from a form.&lt;/li&gt;
&lt;li&gt;(Optionally,&amp;nbsp;when appropriate) Presenter, or more appropriately, the domain layer via something like the &lt;a href="http://blogs.msdn.com/tomholl/archive/2006/11/27/validation-application-block-revealed.aspx"&gt;Validation Application Block&lt;/a&gt;, verifies that the updated entity is internally valid.&lt;/li&gt;
&lt;li&gt;Presenter calls customerDao.SaveOrUpdate(customerToBeSaved).&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;With this approach, the view remains ignorant between whether a new entity is being created or an existing one is being updated.&amp;nbsp; Furthermore, separate DTOs aren&amp;#39;t being maintained while still minimizing the responsibilities of the view.&amp;nbsp; As an added bonus, there&amp;#39;s very little code that&amp;#39;s not testable.&amp;nbsp; The drawback to this is that it gives the view direct access to the&amp;nbsp;persisted objects and, thus, the domain layer itself.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;A Place for&amp;nbsp;View Getters&lt;br /&gt;&lt;/strong&gt;There are&amp;nbsp;other scenarios in which&amp;nbsp;getters on the view are valuable.&amp;nbsp; One such example is an IsDefaultView/IsPostBack getter so that the Presenter can determine if post-back-specific actions are necessary.&amp;nbsp; But in my own experiences, I usually pass contextual data, such as this, into the InitView, or other method, of the Presenter.&amp;nbsp; But at times, exposing a getter on the view can be simple and useful.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Recommendations&lt;br /&gt;&lt;/strong&gt;If your project (team) requires a very clean separation between the view and&amp;nbsp;domain layer, then I recommend considering the &amp;quot;Return DTO from Getter&amp;quot; approach.&amp;nbsp; This keeps the view very contained while allowing you to be more efficient than passing around a ton of primitives.&amp;nbsp; But like CRUD stored procs, the DTOs require a lot of maintenance.&amp;nbsp; Alternatively, if you have a smaller and/or more experienced team, you can bypass the DTO layer altogether in favor of the &amp;quot;Use Update&amp;nbsp;Method&amp;nbsp;in lieu&amp;nbsp;of&amp;nbsp;Getter&amp;quot; approach.&amp;nbsp; This is simple, minimizes responsibilities of the view but, on the&amp;nbsp;downside,&amp;nbsp;allows the view to do more damage, so to speak.&amp;nbsp; But with proper encapsulation, the view&amp;#39;s access to the domain layer can still be limited.&amp;nbsp; I&amp;#39;ve been developing/maintaining my current project for 1 1/2 years and have found the latter approach to be the most maintainable and simple.&amp;nbsp; But either way, both approaches lead to highly testable code.&lt;/p&gt;
&lt;p&gt;Billy McCafferty&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://devlicio.us/aggbug.aspx?PostID=17256" width="1" height="1"&gt;</description><category domain="http://devlicio.us/blogs/billy_mccafferty/archive/tags/Patterns/default.aspx">Patterns</category></item></channel></rss>