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

<channel>
	<title>FlashWorks</title>
	<atom:link href="http://flashworks.wordpress.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://flashworks.wordpress.com</link>
	<description>Peter Kaptein&#039;s Flash blog</description>
	<lastBuildDate>Mon, 14 Nov 2011 17:03:13 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.com/</generator>
<cloud domain='flashworks.wordpress.com' port='80' path='/?rsscloud=notify' registerProcedure='' protocol='http-post' />
<image>
		<url>http://s2.wp.com/i/buttonw-com.png</url>
		<title>FlashWorks</title>
		<link>http://flashworks.wordpress.com</link>
	</image>
	<atom:link rel="search" type="application/opensearchdescription+xml" href="http://flashworks.wordpress.com/osd.xml" title="FlashWorks" />
	<atom:link rel='hub' href='http://flashworks.wordpress.com/?pushpress=hub'/>
		<item>
		<title>Is the ship called &#8220;Flash&#8221; sinking?</title>
		<link>http://flashworks.wordpress.com/2011/11/13/is-the-ship-called-flash-sinking/</link>
		<comments>http://flashworks.wordpress.com/2011/11/13/is-the-ship-called-flash-sinking/#comments</comments>
		<pubDate>Sun, 13 Nov 2011 17:58:23 +0000</pubDate>
		<dc:creator>Peter Kaptein</dc:creator>
				<category><![CDATA[Opinions]]></category>
		<category><![CDATA[flash]]></category>
		<category><![CDATA[html5]]></category>
		<category><![CDATA[sinking ship]]></category>
		<category><![CDATA[end of flash]]></category>
		<category><![CDATA[rise of flash]]></category>

		<guid isPermaLink="false">http://flashworks.wordpress.com/?p=829</guid>
		<description><![CDATA[Flash is now 15 years of age and old news for a long time. My hopes to build entire websites in Flash lasted until 2005 / 2007. But when still nothing substantial had happened regarding SEO, memory management and performance issues in Flash I gave up. Something had not happened in Flash that I had [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=flashworks.wordpress.com&amp;blog=7295152&amp;post=829&amp;subd=flashworks&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Flash is now 15 years of age and old news for a long time.</p>
<p>My hopes to build entire websites in Flash lasted until 2005 / 2007. But when still nothing substantial had happened regarding SEO, memory management and performance issues in Flash I gave up. Something had not happened in Flash that I had hoped it would. Namely that it would mature into a compatative alternative to plain HTML. That it would become the weapon of choice for richer sites with gorgeous visual story telling (how do you move from &#8220;A&#8221; to B&#8221;?) and rock-solid content rendering.</p>
<h2>Adobe and the crisis</h2>
<p>I hate to see the results of the communication set out by Adobe in the past week.</p>
<p>People read what they want to read and right now, most people seem to simply read: &#8220;The Flash-ship is sinking!&#8221;</p>
<p>When filtering out the bottom line from the Adobe posts I read something else. They laid-off 750 people. And laying-off 750 people is not something you do when you are in your peak moment. you lay-off 750 people when your losses are bigger than your profits. Meaning that Adobe might be in a very rough financial weather right now.</p>
<p>And yes: that leads to killing projects as well. Like Flash mobile for browsers.</p>
<h2>Between my lines</h2>
<p>In the post below, based on a response on Google+ I basically state the following between the lines:</p>
<ol>
<li>HTML5 will open new interest for interactive content and better experiences. This will eventually rub off in a good way in the direction of Flash. Especially when the HTML5 hype takes place for the HTML5 reality</li>
<li>If you are good in what you are doing, Flash will very likely become your gold mine in the next years. As HTML5 will not be able to deliver everything a Client might want to communicate and Flash will not disappear as an option. If you are available and skilled, your skills will be even more in demand than before</li>
<li>I think Flash might come back with a vengeance. With all the fuzz about HTML5 and the death of Flash, Flash developers who do and did not give up might focus on things that will completely kick HTML5 ass</li>
</ol>
<div>Flash might also die. Or slowly &#8220;phase out&#8221;. But that really is too easy thing to say. And honestly a very boring opinion to express as everything ends at a certain point. Including this blog, the sun, this universe and your- and my life.</div>
<h2>Building your company on only one technology</h2>
<p>Someone on a Google+ stream I hooked into stated yesterday: &#8220;I definitely won&#8217;t advice anyone to build their business on Flash Platform technologies&#8221;</p>
<p>Building a company on just one technology only is smart / only works well when that technology is &#8220;new&#8221; and &#8220;hot&#8221; and &#8220;wanted&#8221; and still in the up-slope movements of the hype. After the peak of that hype, clients in most cases just go for what works best for a specific budget. By then that technology has revealed all its specific shortcomings and has become &#8220;nothing exciting&#8221; like happened with Flash and Java and any other technology, and most of these companies start expanding their bag of tricks (again).</p>
<p>If you have always relied on only (that) one technology, this might be your wake-up call and your time to learn something new. Which means: always have a plan &#8220;B&#8221; in your pocket. Times change, whatever you do. Whether it is due to an economical crisis, a specific technology falling out of (temporary) grace or whatever.</p>
<h2>Why this current situation is irrelevant</h2>
<p>If your client wants something, you simply deliver. If you can not, you try and find a solution.</p>
<p>I started with Visual Basic, moved into HTML and JavaScript and learned to program C#, Java and Flash for those reasons in the past ten years. Because my clients required solutions in these directions, because one market dried up and another emerged. And from each language and environment I learned something new. Right now I earn all my money writing ActionScript and MXML in Flex projects for big companies. Something I could not have predicted six years ago when I started exploring C# to up my market value because I thought by then that Flash had become a personal dead-end.</p>
<p>Instead, my Flash-experience turned out to be very valuable by the companies that started hiring me. As I was able to fix issues their teams were not. Either due to lack of people or due to abandoned projects from mergers.</p>
<h2>The hype and the reality of every day</h2>
<p>This year, the hype is HTML5. A year from now that hype has been replaced by the everyday reality of projects, budgets, disappointments, quality assurance, bug fixings and the (financial) end result below the line. From there on HTML5 will be just one of the family, old news and one of the many options to go for.</p>
<h2>Let&#8217;s see</h2>
<p>Let&#8217;s wait and see how Adobe gets through the next year. Let&#8217;s see what Flash player 12 will bring. Let&#8217;s see what people will come up with in any and all technologies. Let&#8217;s see how these results will cross-pollinate. Let&#8217;s see what else will spring up. Let&#8217;s see how people like HTML5 a year from now. Let&#8217;s see if people will put new love into Flash.</p>
<h2>Flash developer? Losing clients? Change your strategy</h2>
<p>And yes: if you are a Flash developer, this might be a tough time for you &#8211; as budgets that might have gone to Flash development are now going to HTML5 development. This only means that you might have to change your short term strategies and see where the market is to keep up your earnings.</p>
<p>If you are a skilled Flash-developer, you will be probably able to earn even more in the next years than your did until now. It&#8217;s not all tablets that counts. HTML5 can not solve all creative requests. And who knows what directions commercial Flash content on tablets will take.</p>
<h2>New to Flash? I can imagine you hold back</h2>
<p>If you are new to Flash, I can imagine you are holding back to wager your career on something that holds such an uncertain future as Flash does. Will it still be here two years from now? Will Adobe at a certain point drop the ball as a whole?</p>
<p>Will there be any work at all in Flash?</p>
<h2>Flash mobile</h2>
<p>I kind of do not understand how Adobe AIR for mobile phones will not have the trouble Flash Mobile for the Mobile browser has. In the end, it will have to run on the mobile platform.</p>
<p>Instead of browser-based solutions, Flash Mobile will be AIR-based solutions. (An Adobe Runtime Engine with some extras, that runs as an executable). As I hardly develop for mobile I have no clue what direction Flash mobile will take.</p>
<h2>Like everything, this is not the end</h2>
<p>Flash is old news. And maybe the whole ruckus about Flash and the possible death and the discontinuation of specific projects (like Flash for mobile browsers) is a huge wake-up call to those who care.</p>
<p>Not a wake-up call to drop the ball. That would be completely stupid. How many plugins are there, capable of what Flash can do? How much time will they need to reach the same coverage? What tells you they will not suffer the same fate?</p>
<p>Maybe this is a wake-up call to put our experience into new action. And the time is not bad.</p>
<p>With Flash 11, Adobe finally solved one of the biggest issues of Flash: that content was rendered over the CPU instead of the GPU. Meaning that whatever you wanted to create in Flash was already crippled by lack of performance and the lack of raw computing power the GPU gives you.</p>
<p>Now those issues are solved, new content will arise in and for Flash that was not possible before and that will not be possible in HTML by far.</p>
<p>I am not that somber about the future of Flash. I think that the entire HTML5 thing will lead to a new and even bigger interest in Flash a year from now than I experienced in the past 5, as HTML5 shows what the potential is of interactive content.</p>
<p>And I would not be surprised to see stuff emerge from the Flash site rendering and using HTML in a way not done before. Challenging the HTML5 movement heads-on from within Flash.</p>
<p>Deep inside the realms of my imagination I see brilliant Flash coders already working on the rise of a new type of Flash content that will blow everything away we knew from the past.</p>
<p>Who knows: Flash might even rise from the alleged ashes as a new bird.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/flashworks.wordpress.com/829/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/flashworks.wordpress.com/829/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/flashworks.wordpress.com/829/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/flashworks.wordpress.com/829/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/flashworks.wordpress.com/829/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/flashworks.wordpress.com/829/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/flashworks.wordpress.com/829/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/flashworks.wordpress.com/829/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/flashworks.wordpress.com/829/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/flashworks.wordpress.com/829/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/flashworks.wordpress.com/829/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/flashworks.wordpress.com/829/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/flashworks.wordpress.com/829/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/flashworks.wordpress.com/829/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=flashworks.wordpress.com&amp;blog=7295152&amp;post=829&amp;subd=flashworks&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://flashworks.wordpress.com/2011/11/13/is-the-ship-called-flash-sinking/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/cffc2ff7b980a5f5f76c22bddba4f361?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">peter kaptein</media:title>
		</media:content>
	</item>
		<item>
		<title>My thoughts on the future and past of Flash</title>
		<link>http://flashworks.wordpress.com/2011/11/10/my-thoughts-on-the-future-and-past-of-flash/</link>
		<comments>http://flashworks.wordpress.com/2011/11/10/my-thoughts-on-the-future-and-past-of-flash/#comments</comments>
		<pubDate>Thu, 10 Nov 2011 11:14:35 +0000</pubDate>
		<dc:creator>Peter Kaptein</dc:creator>
				<category><![CDATA[Opinions]]></category>

		<guid isPermaLink="false">http://flashworks.wordpress.com/?p=823</guid>
		<description><![CDATA[The current death of Flash for browsers on Mobile platforms In the past week two messages hit my Twitter stream: Adobe lays off 750 people &#8211; See here  Adobe terminates Flash for Mobile &#8211; See here To terminate Flash for mobile browsers in the light of the lay-off seems to me a sane step to [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=flashworks.wordpress.com&amp;blog=7295152&amp;post=823&amp;subd=flashworks&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<h2>The current death of Flash for browsers on Mobile platforms</h2>
<p>In the past week two messages hit my Twitter stream:</p>
<ol>
<li><strong>Adobe lays off 750 people</strong> &#8211; See <a href="http://venturebeat.com/2011/11/08/adobe-layoffs/">here </a></li>
<li><strong>Adobe terminates Flash for Mobile</strong> &#8211; See <a href="http://www.zdnet.com/blog/perlow/exclusive-adobe-ceases-development-on-mobile-browser-flash-refocuses-efforts-on-html5-updated/19226">here</a></li>
</ol>
<p>To terminate Flash for mobile browsers in the light of the lay-off seems to me a sane step to cut cost. You drop everything that does not deliver. Even if this something might hold some promise to the future.</p>
<p>As I read the announcements, Adobe will focus (recources for) Mobile Flash development on AIR. Flash for the Desktop will be continued to be supported and developed.</p>
<h2>The future (and past) of Flash</h2>
<p>The future of Flash is not dependent on the development of HTML5. It depends entirely on Adobe and the vision (or lack of vision) Adobe has with the platform.</p>
<p>To be brief: I believe Flash is taking too much time on fixing structural issues to go into the right direction. When the team finally comes up with GPU powered 3D in the second half of 2010, we have already seen demos of GPU powered 3D in WebKit nightly builds in 2009. Unity3D is already doing an awesome cross-platform job on Windows AND Apple since around 2005 without any of the performance issues Flash seems to have or any trouble to get access to the GPU for native systems: making the excuses Adobe has related to Apple and Flash performance seem rather lame. And Unity is not the first.</p>
<p>All this lagging behind has arrested the development of Flash for, for instance:</p>
<ol>
<li><strong>An abundance of solid online applications</strong> &#8211; Like Office clones providing basic but good word processing, doing spread sheets and making presentations. Like image editors and creative suites. Like Client Relationship Management tools and whatever you can think of. There are some, like Avary (online image editing) and Buzzword (text processor in Flash) but it could be better. For instance: why is the WYSIWYG text editor I use in environments like WordPress HTML based and not Flash?</li>
<li><strong>Full flash websites</strong> &#8211; I have tried. Several reasons why it did not succueed include performance of text-rendering and scrolling, memory management and &#8211; back then &#8211; lack of proper solutions for deeplinking and SEO</li>
<li><strong>Desktop applications</strong> &#8211; Everything you do online can also be done offline. Unfortunately, Flash performance also there was a big issue. More than anything else, including the sometimes awkward way to communicate with native stuff like DLLs in Windows</li>
</ol>
<p>When the Flash Virtual Machine is optimized in 2004 / 2005, it still under-performs related to HTML for content rendering and text rendering, making any site more than animations close to unsellable to the client.</p>
<p>And where are the SEO use cases for Flash? Show me a clear direction from Adobe on how to implement content in a Flash site that is warrented and supported by Google to be included in search results. Other than the half-baked: &#8220;Google spiders the content of a Flash movie&#8221; which really is no solution at all if you have a lot of content to offer.</p>
<p>All the cases I have met in 2006 and 2007 where companies were contemplating moving to Flash to run their entire corporate sites (including Vodafone and Heineken at that time) are mainly cancelled on these two issues of performance and SEO.</p>
<p>Make Flash 12 something kick-ass. Something that matches HTML rendering in speed and performance. Hell: something that includes HTML rendering and access to the Document Object Model so that I can finally build awesome stuff with a lot of content with existing standards. Something that exceeds the limitations of the Flash implementation. Something that is solid. Something that makes me want to <em>make</em> HTML sites in Flash.</p>
<p>It it not that that HTML rendering technology is so mind-blowingly new. People (including me, with a simplified sub-set) even build their own in Flash since version 5 or 6.</p>
<p>Improve even more the memory management and asset management. Let me brutally kill assets I do not need anymore, instead of making my memory management solely dependent of dependencies and garbage collection. Provide me with a render engine that is capable of dealing with the instantiation of hundred of thousands of objects on stage without even blinking and without taking more memory than absolutely needed. Hard-code specific tricks in C++ or whatever is faster to get the most out of any system for specific actions performed a lot. Make it as good and fast and performing as any game-engine and any 4th generation coding language. Give me brute performance on any level possible in my browsers.</p>
<p>Support development of cool stuff in early stages by inviting people who implement those new things you have not thought of. Like the use of the camera and image processing for AR and QR codes a while ago. Things and that challenge the limitations of Flash and let them help you make Flash better, stronger, faster. Open source your code if that helps. Have people contribute.</p>
<p>Improve Flex. Get rid of the awkwardness that is still in there. Provide me with stuff that matches, equals and overshadow the native components of an OS in performance and reliability.</p>
<p>And please: make a stable version of the Flash IDE. After increasing issues from CS3 on I feel like working in the IDE is like walking in a mine field. Anything can blow at any moment. Even if I tread softly.</p>
<p>The alternative development with all the HTML5 puha is that Flash slowly shifts into obscurity as it becomes less and less relevant due to the massive anti-hype.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/flashworks.wordpress.com/823/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/flashworks.wordpress.com/823/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/flashworks.wordpress.com/823/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/flashworks.wordpress.com/823/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/flashworks.wordpress.com/823/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/flashworks.wordpress.com/823/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/flashworks.wordpress.com/823/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/flashworks.wordpress.com/823/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/flashworks.wordpress.com/823/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/flashworks.wordpress.com/823/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/flashworks.wordpress.com/823/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/flashworks.wordpress.com/823/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/flashworks.wordpress.com/823/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/flashworks.wordpress.com/823/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=flashworks.wordpress.com&amp;blog=7295152&amp;post=823&amp;subd=flashworks&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://flashworks.wordpress.com/2011/11/10/my-thoughts-on-the-future-and-past-of-flash/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/cffc2ff7b980a5f5f76c22bddba4f361?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">peter kaptein</media:title>
		</media:content>
	</item>
		<item>
		<title>&#8220;The end of Flash&#8221;, Microsoft &#8220;Bans&#8221; and &#8220;drops&#8221; Flash in (the Metro browser of) Windows 8</title>
		<link>http://flashworks.wordpress.com/2011/09/16/the-end-of-flash-microsoft-bans-and-drops-flash-in-the-metro-browser-of-windows-8/</link>
		<comments>http://flashworks.wordpress.com/2011/09/16/the-end-of-flash-microsoft-bans-and-drops-flash-in-the-metro-browser-of-windows-8/#comments</comments>
		<pubDate>Fri, 16 Sep 2011 09:58:40 +0000</pubDate>
		<dc:creator>Peter Kaptein</dc:creator>
				<category><![CDATA[Opinions]]></category>
		<category><![CDATA[death of flash]]></category>
		<category><![CDATA[flash]]></category>
		<category><![CDATA[Windows 8]]></category>

		<guid isPermaLink="false">http://flashworks.wordpress.com/?p=800</guid>
		<description><![CDATA[In the past 16 hours there has been some commotion about Microsoft &#8220;banning&#8221; or &#8220;dropping&#8221; Flash. You can read the announcement of Microsoft in many ways and if you are biases (as I have noticed in several occasions on my own perception on things in the past) you read what you want to read. Another [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=flashworks.wordpress.com&amp;blog=7295152&amp;post=800&amp;subd=flashworks&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>In the past 16 hours there has been some commotion about Microsoft &#8220;banning&#8221; or &#8220;dropping&#8221; Flash.</p>
<p>You can read the announcement of Microsoft in many ways and if you are biases (as I have noticed in several occasions on my own perception on things in the past) you read what you <em>want</em> to read.</p>
<h2>Another storm in a glass of water</h2>
<p>The whole discussion is just another storm in a glass of water. Something insignificant blown up to biblical proportions that will &#8211; for some peoples hopes &#8211; finally be the end of Flash.</p>
<p>Simply put: Flash is not important enough on one side (HTML dominates the web completely) and caters specific solutions for specific needs on the other side where HTML and HTML5 simply (still) can not help you. Unlike HTML, Flash is not hampered by a bunch of old guys defining standards or six different flavors of web browsers who all implement those &#8220;standards&#8221; in a slightly different way. And so it can choose its own way in what it think is important to introduce and implement as new features. Streaming video, Sockets and the implementation of newer ECMA Script (OOP driven) standards for ActionScript are only three of them.</p>
<p>I deliberately count out the banners done in Flash. Killing Flash will not kill banners and all the ruckus on Flash and HTML 5 will make HTML5- and (the currently relatively processor intensive) Canvas based banners only more likely to happen.</p>
<h2>I would do the same</h2>
<p>Microsoft has made the choice to focus on HTML 5 alone for Metro. And I think it is a smart choice. Very likely the Metro-framework (if there is one) supports specific basic patterns to do stuff in HTML and JavaScript which support and which are part of the experience of Windows 8 and Metro.</p>
<p>To involve and include other technologies only obfuscates things. It breaks the consistency. It adds extra complications. It is like using Java and C# and Perl all together to create one single solution.</p>
<p>By choosing to go further on their HTML path (allegedly MS started to integrate HTML in their presentation layer with Windows XP) is a simple and clear one.</p>
<p>Too bad if you want to implement Flash stuff in Metro. And very likely you should not want to do that.</p>
<h2>Two browsers: Metro and IE 10</h2>
<p>Windows 8 will contain two default flavors of web browsers:</p>
<ol>
<li><strong>The &#8220;Metro&#8221; browser</strong> &#8211; Based in IE and bsically your main view on Windows 8</li>
<li><strong>Internet Explorer 10</strong> &#8211; With which you browse the web</li>
</ol>
<h2>Metro does not support Flash</h2>
<p>As Microsoft states in &#8220;Metro style browsing and plug-in free HTML5 &#8221; <a href="https://blogs.msdn.com/b/b8/archive/2011/09/14/metro-style-browsing-and-plug-in-free-html5.aspx">here</a>:</p>
<blockquote><p>In Windows 8, IE 10 is available as a Metro style app and as a desktop app. The desktop app continues to fully support all plug-ins and extensions. The HTML5 and script engines are identical and you can easily switch between the different frame windows if you’d like.</p></blockquote>
<p>So: Microsoft does NOT drop Flash in Windows 8.</p>
<p>What does happen is that the Metro Browser (see above for a brief on what I understand it is) does not support any plugin, including Silverlight.</p>
<blockquote><p>[..] the Metro style browser in Windows 8 is as HTML5-only as possible, and <a href="http://blogs.msdn.com/b/ie/archive/2011/08/31/browsing-without-plug-ins.aspx" target="_blank">plug-in free</a>. The experience that plug-ins provide today is not a good match with Metro style browsing and the modern HTML5 web.</p></blockquote>
<p>When we check the &#8220;plug-in free&#8221; link, we find:</p>
<blockquote><p>Because more and more browsing takes place on an ever wider variety of devices, and browsers on them, more and more consumers are browsing without plug-ins.</p></blockquote>
<p>And</p>
<blockquote><p>Lots of Web browsing today happens on devices that simply don’t support plug-ins.</p></blockquote>
<p>Regarding the choice of plugin free browsing in Metro, two factors are mentioned in the first post</p>
<blockquote><p>The experience that plug-ins provide today is not a good match with Metro style browsing and the modern HTML5 web. Running Metro style IE plug-in free improves battery life as well as security, reliability, and privacy for consumers.</p>
<p>[...]</p>
<p>Providing compatibility with legacy plug-in technologies would detract from, rather than improve, the consumer experience of browsing in the Metro style UI.</p></blockquote>
<p>I deliberately removed the self justification stuff about how plugins &#8220;were important early on in the web’s history&#8221; and &#8220;the web has come a long way <a href="http://en.wikipedia.org/wiki/NPAPI#History" target="_blank">since then</a> with HTML5&#8243; and &#8220;the reality today is that sites are already rapidly engineering for a plug-in free experience&#8221;.</p>
<h2>IE 10 will support plugins (and Flash) in Windows 8</h2>
<p>IE 10 will still support Flash (and other plugins &#8211; which are not mentioned, but many) as the Microsoft blog states clearly in &#8220;Metro style browsing&#8221;:</p>
<blockquote><p>In Windows 8, IE 10 is available as a Metro style app and as a desktop app. <strong>The desktop app continues to fully support all plug-ins and extensions</strong>.</p></blockquote>
<h2>Flash</h2>
<p>As I have written before in several posts, Flash is a niche-product. You can build entire websites in it (which I have done) but there are several reasons why Flash has not become an HTML killer where it might have been. I mention five:</p>
<ol>
<li><strong>Searchability and SEO</strong> &#8211; Even though possible (publish the content as XHTML with the Flash main movie and reload the content in Flash) SEO and Flash has never been on the map of Adobe and Macromedia as far as I know.</li>
<li><strong>Memory management</strong> &#8211; Being the real hidden issue of Flash for a long time: Flash used to suck at memory management. A simple Flash site could easily consume 200 MB without you doing anything more than loading some images in some container and effortlessly growing over 1 GB  if you did not do your memory management properly. Imagine having 5 tabs open with each one such a Flash site.</li>
<li><strong>Scalability</strong> &#8211; HTML is scalable to the max. It does not matter if your site is 1 or 1.000.000 pages big. With Flash, again, even though possible, there are only a few people using strategies to make Flash sites &#8220;endlessly deep&#8221;: able to display thousands of &#8220;pages&#8221;. Instead, in general Flash sites are developed in the same way as folders and Power Points: each piece of content gets a dedicated &#8220;page&#8221; which is usually &#8220;hard coded&#8221; in Flash. In most of these cases, all these &#8220;pages&#8221; are all plunked into one single SWF file. To follow a different strategy, where assets an congtent are loaded on demand and cleaned up for neatly after use, requires more effort and more experience than the average Flasher has at this point in time.</li>
<li><strong>Google Translate</strong> &#8211; With Google Translate you can translate Russian, Japanese and Chinese sites to something that is almost readable. Flash sites do not allow for this external additional services.</li>
<li><strong>Bookmarking and deeplinking</strong> &#8211; Bookmarking and deeplinking was not supported at all until someone found a solution for Flex and someone else implemented an open source version hacking Hash tags and injecting pseudo-links into the address bar. This meant that you could not store or share content inside a Flash site. Both are still a hack relying on JavaScript to do the job.</li>
</ol>
<p>Flash itself originally emerged because it was the ultimate Animated Gif killer. Instead of having your animations run in huge pre-baked sequences inside a GIF file, where each next frame would add more weight to the file, Flash allowed you to make animations which were incredibly light weight (in kilobytes), vector based and based on tweening and other neat tricks.</p>
<h2>The future of Flash</h2>
<p>I think it is a good thing Flash is challenged. I think the HTML 5 hype is a good thing too. There will always be cross-pollination (I think &#8211; for instance &#8211; that GPU supported 3D in Flash was put on the map once the OpenGL demos in WebKit came to the web).</p>
<p>Flash has become in many ways what HTML could not: a better environment to code and create awesome stuff for the web, running in (almost) the exact way on almost any platform.</p>
<p>Flash lacks a lot at the same time in this department. And I think that is the main reason why it stays in the corner of a niche-product.</p>
<p>Two main reasons &#8211; as mentioned above &#8211; not to choose Flash as the major technology for sites are still: (good strategies for) scalability and a proper implementation of strategies for SEO.</p>
<p>Adobe fixed some of the major memory management issues in 2010 and it has been a before that fix since I last profiled a Flash site.</p>
<p>As Flash and the future concerns, HTML did not kill Flash, and there will always be a need for specific things that Flash can- and HTML can not do. As is the other way around.</p>
<p>In the end, nothing much will change and if Flash dies, it will be very likely due to stupidity and wrong choices on Flash itself, not because Apple and Windows choose to exclude it from very specific solutions and environments.</p>
<h2>Mapping the confusion</h2>
<p>And here is what happens when you post something unclear and people read what they want to read.</p>
<p>As stated above, IE 10 under Windows 8 will still support plugins, so read carefully.</p>
<p>From PC World: &#8220;Windows 8 Update: The End of Adobe Flash?&#8221; <a href="http://www.pcworld.com/article/240095/windows_8_update_the_end_of_adobe_flash.html">here</a>. Bold added by me. The article seem to suggest that<em> if you want to use and see Flash, you need drop the Metro desktop and revert/<strong>stick to the traditional desktop</strong></em>.</p>
<blockquote><p>Nevertheless, the lack of plug-ins and possibly extensions should make IE more responsive and faster when using the Metro UI.</p>
<p><strong>This could also be a huge blow to Adobe</strong>, since the Metro-style interface will be the first thing home users see when they fire up Windows 8 on their laptops and desktops. It&#8217;s possible that Microsoft could adopt Google&#8217;s strategy and build Flash right into IE, <strong>but that would technically be using a plug-in</strong> and thus <strong>not be as plug-in free as Microsoft is promising</strong>.</p>
<p>Microsoft&#8217;s comments, while they don&#8217;t explicitly say this, suggest that Flash will not be included in the Metro-style version of Windows 8. <strong>So unless PC users at home reject the Metro-style interface and stick with the traditional desktop</strong> in Windows 8 or Windows 7, Microsoft may effectively finish what Apple started and <strong>kill Flash on the Web</strong>.</p></blockquote>
<p>You will find echos of this article on many places including <a href="http://www.macworld.co.uk/digitallifestyle/news/index.cfm?newsid=3303971&amp;olo=rss">here </a>and <a href="http://news.techworld.com/applications/3303871/windows-8-could-mean-the-end-of-adobe-flash/">here</a>.</p>
<p>There is another article in similar fashion, stating at the end that Flash might be really dead now in 3 to 5 years and that Flash developers just as well should abandon the sinking ship that is Flash and go find something else, elsewhere.</p>
<p>Unfortunately I could not find that article anymore.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/flashworks.wordpress.com/800/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/flashworks.wordpress.com/800/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/flashworks.wordpress.com/800/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/flashworks.wordpress.com/800/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/flashworks.wordpress.com/800/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/flashworks.wordpress.com/800/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/flashworks.wordpress.com/800/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/flashworks.wordpress.com/800/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/flashworks.wordpress.com/800/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/flashworks.wordpress.com/800/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/flashworks.wordpress.com/800/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/flashworks.wordpress.com/800/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/flashworks.wordpress.com/800/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/flashworks.wordpress.com/800/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=flashworks.wordpress.com&amp;blog=7295152&amp;post=800&amp;subd=flashworks&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://flashworks.wordpress.com/2011/09/16/the-end-of-flash-microsoft-bans-and-drops-flash-in-the-metro-browser-of-windows-8/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/cffc2ff7b980a5f5f76c22bddba4f361?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">peter kaptein</media:title>
		</media:content>
	</item>
		<item>
		<title>Design Patterns: Refactoring an If/Then/Else State Handler using the State Pattern</title>
		<link>http://flashworks.wordpress.com/2011/08/01/design-patterns-refactoring-an-ifthenelse-state-handler-using-the-state-pattern/</link>
		<comments>http://flashworks.wordpress.com/2011/08/01/design-patterns-refactoring-an-ifthenelse-state-handler-using-the-state-pattern/#comments</comments>
		<pubDate>Mon, 01 Aug 2011 12:54:04 +0000</pubDate>
		<dc:creator>Peter Kaptein</dc:creator>
				<category><![CDATA[Design patterns]]></category>
		<category><![CDATA[Examples]]></category>

		<guid isPermaLink="false">http://flashworks.wordpress.com/?p=791</guid>
		<description><![CDATA[Lets consider you wrote this code to save files either locally or over a network connection (the values in capitals are Constants used in your code instead of hard coded values): class MyFile() { // Set our starting position var dataState=DATA_STATE_UNCHANGED; var fileSaveState=FILE_SAVESTATE_UNSAVED; // Store our data binaryData:BinaryData=new BinaryData();  public method saveFile() {    if(dataState==DATA_STATE_UNCHANGED) [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=flashworks.wordpress.com&amp;blog=7295152&amp;post=791&amp;subd=flashworks&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<div>
<h2><span class="Apple-style-span" style="font-size:13px;font-weight:normal;">Lets consider you wrote this code to save files either locally or over a network connection (the values in capitals are Constants used in your code instead of hard coded values):</span></h2>
<pre>class MyFile()
{
<span style="color:#008000;"> // Set our starting position</span>
   var <span style="color:#0000ff;">dataState</span>=<span style="color:#ff0000;">DATA_STATE_UNCHANGED</span>;
   var <span style="color:#0000ff;">fileSaveState</span>=<span style="color:#ff0000;">FILE_SAVESTATE_UNSAVED</span>;
<span style="color:#008000;"> // Store our data</span>
   <span style="color:#0000ff;">binaryData</span>:BinaryData=new BinaryData(); 
   public method saveFile()
   {
      if(<span style="color:#0000ff;">dataState</span>==<span style="color:#ff0000;">DATA_STATE_UNCHANGED</span>)
      {
        MessageCentral.showMessage("<span style="color:#0000ff;">File has not changed. No need to save it</span>");
        return;
      }
      if(<span style="color:#0000ff;">dataState</span>==<span style="color:#ff0000;">DATA_STATE_CHANGED</span>)
      {
        if(<span style="color:#0000ff;">fileSaveState</span>==<span style="color:#ff0000;">FILE_SAVESTATE_SAVING</span>)
        {
<span style="color:#008000;"> // We decided to show a message and exit</span>
          MessageCentral.showMessage("<span style="color:#0000ff;">Already saving the file now, please try again later</span>");
          return;
        }
        if(<span style="color:#0000ff;">locationType</span>==<span style="color:#ff0000;">LOCATION_TYPE_REMOTE</span>)
        {
<span style="color:#008000;"> // Create object and open connection to save it remotely</span>
      <span style="color:#ff0000;">fileHander</span>=new FileHandlerRemote();
<span style="color:#008000;"> // Attempt to save file</span>
          remoteSaveAttemptSuccesful=<span style="color:#ff0000;">fileHandler</span>.<span style="color:#0000ff;">saveFile</span>(binaryData,location); 
<span style="color:#008000;"> // Attempt to save</span>
<span style="color:#008000;"> // Give feedback if save failed</span>
<span style="color:#008000;"> // Set flag to indicate if we succeeded in our attempt</span>
          saveAttemptSuccesful=remoteSaveAttemptSuccesful;
       }
       if(<span style="color:#0000ff;">locationType</span>==<span style="color:#ff0000;">LOCATION_TYPE_LOCAL</span>)
       {
<span style="color:#008000;"> // Open connection to save it locally</span>
         <span style="color:#ff0000;">fileHandler</span>=new FileHandlerLocal();
<span style="color:#008000;"> // Attempt to save</span>
         localSaveAttemptSuccesful=<span style="color:#ff0000;">fileHandler</span>.<span style="color:#0000ff;">saveFile</span>(binaryData,location);
<span style="color:#008000;"> // Give feedback if save failed</span>
<span style="color:#008000;"> // Set flag to indicate if we succeeded in our attempt</span>
         saveAttemptSuccesful=localSaveAttemptSuccesful
      }
<span style="color:#008000;"> // Done. Now change the state if we failed</span>
      if(saveAttemptSuccesful==false)
      {
<span style="color:#008000;"> // Make sure we set the right state</span>
        <span style="color:#0000ff;">fileSaveState</span>=<span style="color:#ff0000;">FILE_SAVESTATE_UNSAVED</span>;
<span style="color:#008000;"> // Exit</span>
        return;
      }
   }
<span style="color:#008000;">// We need an event handler when Saving (attempt) is done</span></pre>
</div>
<pre>   private method onSaveFinished(evt:Event)
   {
<span style="color:#008000;">   // Here we get feedback from our process  </span>
<span style="color:#008000;">   // As it is from an asynchronous process, we only know now if it failed or not</span>
      if(evt.success==true)
      {
         <span style="color:#0000ff;">fileSaveState</span>=<span style="color:#ff0000;">FILE_SAVESTATE_SAVED</span>;
         MessageCentral.showMessage("<span style="color:#0000ff;">Your file has been saved</span>");
      }
      if(evt.success==false)
      {
         <span style="color:#0000ff;">fileSaveState</span>=<span style="color:#ff0000;">FILE_SAVESTATE_UNSAVED</span>;
         MessageCentral.showMessage("<span style="color:#0000ff;">Oops! Something went wrong. Your file has not been saved</span>");

      }
<span style="color:#008000;"> // Done</span>
   }
}</pre>
<p>If this was a real world example, we would have handlers for IO errors as well, and be more specific on why stuff went wrong, so the user can correct if possible.</p>
<h2>Issues with the If/Then/Else approach</h2>
<p>What is &#8220;wrong&#8221; in this approach is the following:</p>
<ol>
<li><strong>Too much responsibility/things happening in one single place </strong>- Many decisions are made and managed in one block of code: saveFile</li>
<li><strong>Allows for clutter to happen</strong> - The more exceptions you get (captured with If/Then/Elses or Switch vases) the more mess your code will contain.</li>
<li><strong>Too rigid/resilient against change</strong> - If your pattern changes or new states are added, you will have to add (and change) If/Then/Else statements. This can be a very tough process and can introduce (new) bugs when done improperly or by someone else.</li>
</ol>
<h2>Looking at the parts we have</h2>
<p>To continue our review of the code above: we can split the if/then/else in &#8220;saveFile&#8221; into two main decision making:</p>
<ol>
<li><strong>The save- and data-state of the file</strong> &#8211; Data is changed/unchanged and the file is saved/unsaved.</li>
<li><strong>The way we store the data</strong> &#8211; Remote or locally. As there is no business logic present for this, for now, we can use a &#8220;Simple Factory&#8221; to select a handler. There are two advantages to that:</li>
<ol>
<li><strong>Extendability</strong> &#8211; We can extend the number of possible handlers to any possible number</li>
<li><strong>Clean code</strong> &#8211; We move the (potential) clutter to another class and pass only the known stuff to have it resolved.</li>
</ol>
</ol>
<h2>The File Handler</h2>
<p>The way we store data, can be outsourced to an external class, called &#8211; for instance &#8211; &#8220;FileHandler&#8221;.</p>
<p>We will skip this class and assume it is there in the next parts, to keep this example simple.</p>
<h2>Using State Pattern - The MyFile State Handlers</h2>
<p><strong>Before we start:</strong> As we are going to implement multiple Handlers, we need a generic interface. There are several ways to do this, including inheritance of a Interface, extending an Abstract class or extending a Template class.</p>
<p><strong>We use an Interface:</strong> As we assume that we do not share any generic code, we use an Interface to allow the application to use all different SavedState Classes as if they are the same thing. An Interface is basically a class with just the definition of the Methods but no code.</p>
<p><strong>Two State Types interacting:</strong> We also have two state types interacting with each other and influencing the possible next steps of each other:</p>
<ol>
<li><strong>Changed state</strong> &#8211; The file  is changed/unchanged/being saved</li>
<li><strong>Saved state</strong> &#8211; The file is saved/unsaved/in the process of being saved</li>
</ol>
<p>One of the solutions might be to create a state for each combination as we have defined it now. Currently leading to 3 x 3 = 9 different possible states.</p>
<p><strong>State Manager:</strong> Instead we do something else: we use a State Manager &#8211; introduced later in this example. I explain later the reasoning behind this.</p>
<p><strong>State Handler for <span style="text-decoration:underline;">unsaved</span> files:</strong></p>
<pre>class <span style="color:#ff0000;">FileState_UnsavedHandler</span> <span style="color:#0000ff;">implements</span> <span style="color:#ff0000;">IFileStateHandler</span>
{
    public method <span style="color:#ff0000;">saveFile</span>(fileData, location, method, 
                           callBackSuccessful,callBackFailed)
    {
<span style="color:#008000;">        // The file is unsaved</span>

<span class="Apple-style-span" style="color:#008000;">        // Create a File Handler </span><span class="Apple-style-span" style="color:#008000;"><span style="color:#000000;"><span style="color:#0000ff;">        </span></span></span>
<span class="Apple-style-span" style="color:#008000;"><span style="color:#000000;"><span style="color:#0000ff;"> fileHandler</span>:FileHandler= new FileHandler()</span></span>
<span style="color:#008000;">        // Attempt save with passed parameters</span>
        <span style="color:#0000ff;">fileHandler</span>.<span style="color:#ff0000;">saveFile</span>(binaryData,location, method,
                             callBackSuccessful,callBackFailed)
        <span style="color:#008000;">// Notify the user</span>
        MessageCentral.showMessage("<span style="color:#0000ff;">Attempting to save the file</span>");
       <span style="color:#008000;"> // Return the new state</span>
        return <span style="color:#ff0000;">FILE_SAVESTATE_SAVING</span>; 
<span style="color:#008000;">        // Done</span>
   }
}</pre>
<p><strong>State Handler for <span style="text-decoration:underline;">saved</span> files:</strong></p>
<pre>class <span style="color:#ff0000;">FileState_SavedHandler </span><span style="color:#0000ff;">implements </span><span style="color:#ff0000;">IFileStateHandler</span>
{
    public method saveFile(fileData, location, method,
                           callBackSuccessful,callBackFailed)
    {
       <span style="color:#008000;"> // Notify the user</span>
        MessageCentral.showMessage("<span style="color:#0000ff;">File is already saved, no action taken</span>");
<span style="color:#008000;"> // Return the state</span>
        return <span style="color:#ff0000;">FILE_SAVESTATE_SAVED</span>; 
   }
}</pre>
<p><strong>State Handler for files which are <span style="text-decoration:underline;">in the process of saving</span>:</strong></p>
<pre>class <span style="color:#ff0000;">FileState_SavingHandler </span><span style="color:#0000ff;">implements </span><span style="color:#ff0000;">IFileStateHandler</span>
{
    public method <span style="color:#ff0000;">saveFile</span>(fileData, location, method,
                           callBackSuccessful,callBackFailed)
    {
<span style="color:#008000;"> // The fileData is already being saved</span>
<span style="color:#008000;"> // Notify the user</span>
        MessageCentral.showMessage("<span style="color:#0000ff;">File is already being saved,  </span><span style="color:#0000ff;"> no action taken</span>");
<span style="color:#008000;"> // Return state</span>
        return <span style="color:#ff0000;">FILE_SAVESTATE_SAVING</span>; 
   }
}</pre>
<p><strong>What we have so far:</strong> We have three basic State Handlers for all three currently defined Saved states. Two are basically doing nothing more than giving feedback to the user. The question that might have arisen in your mind at this point is: what is the use of this?</p>
<p><strong>What we did:</strong> We encapsulated different possible scenarios for when the user wants to save stuff into separate classes, which are interchangeable as they all use the same interface.</p>
<p><strong>What this delivers:</strong> Clean code and a clear purpose. Later, when your application starts growing and decisions are becoming increasingly complex, encapsulation and separation of State specific actions will help you keep control over the processes that you manage in these classes.</p>
<p><strong>What we do not have yet:</strong> We still need to deal with the Changed State.</p>
<p><strong>What we avoided:</strong> In many textbook examples you will find:</p>
<ol>
<li>References to the class we handle the State Specific processes for. In our case case that would be the Class: &#8220;MyFile&#8221;.</li>
<li>Direct manipulation of variables on &#8220;MyFile&#8221; by the State Handlers</li>
<li>Interference with other processes. For instance: we could also set the File Changed State to &#8220;unchanged&#8221; when a file is saved.</li>
</ol>
<p>This leads to tight coupling and rigid code.</p>
<p><strong>What can go wrong:</strong> Each State returns or sets the next state to be executed (including itself, if nothing changed). If we make a mistake in this (for instance stating the new state is &#8220;Saved&#8221; while we are actually still saving the file), the process will &#8220;get lost&#8221; or &#8220;break&#8221; and the application might end up in places we did not intend it to go.</p>
<p><strong>Why you might want to consider the Mediator Pattern:</strong> This dependency of &#8220;internal decision making per State Handler&#8221; and the fragility of the chain is one of the reasons you might want to consider using the Mediator Pattern.</p>
<p><strong>Using a State Manager:</strong> Another alternative is using/adding a State Manager to your State Pattern. The State Manager adds the benefits of centralized decision making and centralized sanity checks to the clarity that encapsulation of State Specific responses delivers.</p>
<p><strong>Tight Coupling?:</strong> Means that both your: &#8220;MyFile&#8221; Class and your State Handlers have awareness of each others existence. This might seem OK at the beginning, but can lead to a lot of trouble in later stadia of your code. Your code and your solutions to a problem should be disposable. I will explain in the next blocks why.</p>
<p><strong>Rigid code:</strong> Meaning that one specific type of solution is hardcoded into many places, leading to a lot of trouble if we want to discard of it.</p>
<h2>Avoiding three issues: Adding The State Manager to the equasion</h2>
<p><strong>Purpose of the State Manager:</strong> As our decision making process covers two State Types (Changed and Saved) we might want a Manager to deal with the potential complexity that arises from managing the different states in different combinations.</p>
<p><strong>What it solves:</strong> We have three issues when dealing with the State Pattern:</p>
<ol>
<li><strong>Are we still doing the right thing?</strong> &#8211; The State Manager can execute sanity checks on States which are centralized. These sanity checks can help you avoid entering the wrong state when specific Exceptions occur.</li>
<li><strong>How do we deal with dependencies between mixed State Types?</strong> &#8211; Like the possibility of having any combination of: &#8220;Saved State&#8221; and: &#8220;Changed State&#8221; in our example, already leading to 9 different possible combined States. State Handlers are relatively single minded. And the purpose of a State Handler is to replace If/Then/Else constructions by encapsulating specific responses to specific states in specific classes.</li>
<li><strong>How do we decouple our State Handlers from the &#8220;MyFile&#8221; Class?</strong> &#8211; Tight Coupling of a solution to the Class that requires that solution generates a lot of problems when change is required. We rather decouple the State Handlers from the &#8220;MyFile&#8221; Class, to become more Agile in our solution.</li>
</ol>
<div>In contrary to each State Handler, our State Manager is able to oversee the total result of any State Change and take action when one State Change affects the State of another State Type. For instance: when a file is saved, the state for Saved should be changed to: &#8220;file is saved&#8221; and (only) when the File Data was not changed in the mean time (having the status &#8220;being saved&#8221;) we can then reset the File Data state to &#8221;data is not changed&#8221;.</div>
<div>
<p><strong>Disposable code: </strong>When you start building code with refactoring in mind, your code and your solution should be disposable. Meaning that if something better comes along, you can drop the old one and inject the new.</p>
<p><strong>Plug and Play:</strong> What we create via our State Manager is a &#8220;plug and play&#8221; variant of a State Pattern, achieving that exact goal.</p>
<p>Using a State Manager, we decouple the State Handlers from the Class we manage the state of. This leads to several useful results:</p>
<ol>
<li><strong>The managed object can remain simple</strong> - As it is only required to do what it is intended to do</li>
<li><strong>We become more agile in our possible solutions</strong> - As we do not force a specific solution onto the managed object, bet let something else deal with that, we can remove one approach plug any other into it instead</li>
</ol>
</div>
<p>Here we go:</p>
<pre><strong>class FileStateManager</strong>
{
<span style="color:#008000;">   // Define the variables to keep our state</span>
   var <span style="color:#ff0000;">savedState</span>:String=<span style="color:#ff0000;">FILE_SAVESTATE_SAVED</span>;
   var <span style="color:#ff0000;">changedState</span>:String=<span style="color:#ff0000;">DATA_STATE_UNCHANGED</span>;
<span style="color:#008000;"> // Mappings</span>
   <span style="color:#0000ff;">fileStateHandlers</span> <img src='http://s0.wp.com/wp-includes/images/smilies/icon_biggrin.gif' alt=':D' class='wp-smiley' /> ictionary&lt;String,IFileStateHandler&gt;=
            new Dictionary&lt;String,IFileStateHandler&gt;()
   <span style="color:#0000ff;">changedStateHandlers</span> <img src='http://s0.wp.com/wp-includes/images/smilies/icon_biggrin.gif' alt=':D' class='wp-smiley' /> ictionary&lt;String,IChangedStateHandler&gt;=
            new Dictionary&lt;String,IDataStateHandler&gt;()
   public method init()
   {
<span style="color:#008000;"> // Did we already do this?</span>
      if(<span style="color:#0000ff;">fileStateHandlers</span>.length&gt;0)
      { 
<span style="color:#008000;"> // Already done</span>
        return;
      }
<span style="color:#008000;"> // Map it!</span>
      <span style="color:#0000ff;">fileStateHandlers</span>[<span style="color:#ff0000;">FILE_SAVESTATE_UNSAVED</span>]=new <span style="color:#0000ff;">FileState_UnsavedHandler</span>();
      <span style="color:#0000ff;">fileStateHandlers</span>[<span style="color:#ff0000;">FILE_SAVESTATE_SAVED</span>]=new <span style="color:#0000ff;">FileState_SavedHandler</span>();
      <span style="color:#0000ff;">fileStateHandlers</span>[<span style="color:#ff0000;">FILE_SAVESTATE_SAVING</span>]=new <span style="color:#0000ff;">FileState_SavingHandler</span>();
      <span style="color:#0000ff;">changedStateHandlers</span>[<span style="color:#ff0000;">DATA_STATE_CHANGED</span>]=new <span style="color:#0000ff;">DataState_ChangedHandler</span>();
      <span style="color:#0000ff;">changedStateHandlers</span>[<span style="color:#ff0000;">DATA_STATE_SAVEATTEMPT</span>]=new <span style="color:#0000ff;">DataState_SaveAttempt</span>();
      <span style="color:#0000ff;">changedStateHandlers</span>[<span style="color:#ff0000;">DATA_STATE_UNCHANGED</span>]=new <span style="color:#0000ff;">DataState_UnchangedHandler</span>();

   }
<span style="color:#008000;">// Handle edit event from Class "MyFile"</span>
   public method <span style="color:#ff0000;">changeEventHandler</span>(evt:Event)
   {
<span style="color:#008000;"> // Get the handler</span>
<span class="Apple-style-span" style="color:#008000;"> <span style="color:#000000;"> var <span style="color:#0000ff;">handler</span>:<span style="color:#ff0000;">IChangedStateHandler</span>=<span style="color:#0000ff;">changedStateHandlers</span>[this.<span style="color:#ff0000;">changedState</span>];</span></span>
<span style="color:#008000;"> // Perform the actions required and return our new state</span>
<span style="color:#008000;"> <span style="color:#000000;"> this.<span style="color:#ff0000;">changedState</span>=<span style="color:#0000ff;">handler</span>.<span style="color:#ff0000;">handleEdit</span>(evt.data);</span></span>
<span style="color:#008000;"><span style="color:#000000;"><span style="color:#008000;"> // Handle busines logic when file is changed and was saved</span></span></span>
<span style="color:#008000;"><span style="color:#000000;"> if(this.<span style="color:#ff0000;">savedState</span>==<span style="color:#ff0000;">FILE_SAVEDSTATE_SAVED</span> &amp;&amp; this.<span style="color:#ff0000;">changedState</span>==<span style="color:#ff0000;">DATA_STATE_CHANGED</span>)</span></span>
     {
 <span style="color:#008000;">// Data State is changed and no longer "saved"</span>
        this.<span style="color:#ff0000;">savedState</span>=<span style="color:#ff0000;">FILE_SAVEDSTATE_UNSAVED</span>;
      }
   } 
<span style="color:#008000;">// Handle call to save file</span>
   public method <span style="color:#ff0000;">saveFile</span>(fileData, method,
                          callBackSuccessful,callBackFailed)
   {
<span style="color:#008000;">  // Get the handler</span>
      var <span style="color:#0000ff;">handler</span>:<span style="color:#ff0000;">IFileStateHandler</span>=<span style="color:#0000ff;">fileStateHandlers</span>[this.<span style="color:#ff0000;">savedState</span>];
      <span style="color:#008000;">// Perform the action</span>
      this.<span style="color:#ff0000;">savedState</span>=<span style="color:#0000ff;">handler</span>.<span style="color:#ff0000;">saveFile</span>(fileData, method, this.<span style="color:#ff0000;">changedState</span>
                       <span style="color:#ff0000;">saveSuccesfulCallback</span>, saveFailedCallback) 
      <span style="color:#008000;">// We deal with the changed state when we get the call back</span>
<span style="color:#008000;"> // Make sure we reflect the save state for data too</span>
      if(this.<span style="color:#ff0000;">savedState</span>==<span style="color:#ff0000;">FILE_SAVEDSTATE_SAVING</span>)
      {
         this.<span style="color:#ff0000;">changedState</span>=<span style="color:#ff0000;">DATA_STATE_SAVEATTEMPT</span>;
      }
   }
   private method <span style="color:#ff0000;">saveSuccessfulCallback</span>(evt:Event)
   {
      <span style="color:#008000;">// Save is succesful, we can set our state to saved</span>
      this.<span style="color:#ff0000;">savedState</span>=<span style="color:#ff0000;">FILE_SAVEDSTATE_SAVED</span>;

<span style="color:#008000;"> // If the data has not changed in the meantime we can set it to unchanged</span>
      if(this.<span style="color:#ff0000;">changedState</span>==<span style="color:#ff0000;">DATA_STATE_SAVEATTEMPT</span>)
      {
         this.<span style="color:#ff0000;">changedState</span>=<span style="color:#ff0000;">DATA_STATE_UNCHANGED</span>; 
      } 
<span style="color:#008000;"> // In all other cases, the data either is unchanged</span>
<span style="color:#008000;"> // or new changes were made after our save-attempt</span>
   }
}</pre>
<p><strong>What we have:</strong> We now have a simple State Manager to manage the dependencies of our two different state types.</p>
<p>All our decision making is externalized in interchangeable classes which we can expand as much as we want, without making our central State Management.</p>
<p>If we want to implement a different process or different rules to manage the responses of our application to the state of a file, we can simply replace this manager for another that implements that process or those (new) rules.</p>
<p><strong>Did we really win something?</strong> We started with a simple If/Then/Else solution where we solved this in maybe 20 lines of code and ended up with more than six classes and a hell of a lot more than those six lines of code.</p>
<p><strong>What we won with the State Manager:</strong> Three things:</p>
<ol>
<li><strong>Centralized decision making on mixed states</strong> &#8211; We decoupled all decision making on mixed states from the State Handlers, so that they can focus on their main task: handling one specific state</li>
<li><strong>One single point of entry</strong> &#8211; for our &#8220;MyFile&#8221; Class to have its States handled and managed.</li>
<li><strong>Disposable solution</strong> &#8211; Which is easy to replace by something completely new and improved.</li>
</ol>
<h2>Revisiting the &#8220;MyFile&#8221; Class</h2>
<div>
<pre>class MyFile()
{
<span style="color:#008000;"> // Get a File State Manager for this file</span>
   var <span style="color:#0000ff;">stateManager</span>:FileStateManager=new FileStateManager();

<span style="color:#008000;"> // File data</span>
   var binaryData:BinaryArray=new BinaryArray(); 
   <span style="color:#008000;">// Constructor</span>
   public MyFile()
   {
<span style="color:#008000;"> // Add an eventlistener and bind it to the stateManager  </span><span class="Apple-style-span" style="color:#008000;"> // (to keep the example simple)</span>
     binaryData.<span style="color:#ff0000;">onChange</span>=<span style="color:#0000ff;">stateManager</span>.<span style="color:#ff0000;">changeEventHandler</span>;
   }
   public method <span style="color:#ff0000;">saveFile</span>(method)
   {
<span style="color:#008000;"> // We now have a manager to save our file:</span>
<span class="Apple-style-span" style="color:#008000;"> // dealing with any possible reaction to any</span>
<span class="Apple-style-span" style="color:#008000;"> // of our possible strategies and States</span>
      <span style="color:#0000ff;">stateManager</span>.<span style="color:#ff0000;">saveFile</span>(this.binaryData, method)

<span style="color:#008000;"> // "Method" is either stating to save it Remote or Local</span>
   }</pre>
</div>
<pre>}</pre>
<p><strong>What we have:</strong> We now have a simplified Class: &#8220;MyFile&#8221;. Its purpose has become more clear as  all our decision making and action code has moved elsewhere.</p>
<p><strong>What we won:</strong> Our code in the &#8220;MyFile&#8221; class is incredibly clean.</p>
<p>We can now easily switch from one State Manager to another, allowing us to completely revise our strategy in solving things and saving files, for instance when the requirements change from:</p>
<ol>
<li><strong>Blocking state - </strong>Files can not be edited while being saved.</li>
</ol>
<div>To</div>
<div>
<ol>
<li><strong>Non blocking state</strong> &#8211; Files can be edited while being saved to a remote location</li>
<li><strong>Ignore &#8220;save&#8221; when saving still in progress</strong> &#8211; When a file has been edited but the previous version is still being saved, we ignore the press on the &#8220;Save button&#8221;</li>
</ol>
<div>To</div>
<div>
<ol>
<li><strong>Que &#8220;save&#8221; when saving is till in progress and execute last &#8220;save&#8221; instruction after &#8220;save&#8221; is done</strong> &#8211; Where we assure that when the user presses: &#8220;save&#8221;, this instruction is executed.</li>
</ol>
<h2>Closing thoughts on this refactoring</h2>
<ol>
<li><strong>There are many ways to implement the State Pattern </strong>- I choose the way closest to my own likings. This includes the use of Mapping of my State Objects and the use of String variables to define the current State (instead of injecting the State Object into a variable in the Class I &#8220;manage&#8221; with the State Pattern)</li>
<li><strong>The basic State Pattern is assumed to be Self Managing</strong> &#8211; You will find most textbook examples (including those in &#8220;Design Patterns&#8221; and &#8220;Design Patterns for Dummies&#8221;) to be self managing Single State Type solutions. You will not find a State Manager.</li>
<li><strong>The text book State Pattern fails on combinations of State Types</strong> &#8211; When your application has multiple State Types (like &#8220;Changed State&#8221; and &#8220;Saved State&#8221;), your number of potential combination of states grows. If you do not add a middle-layer (like the State Manager) to your solution, your State Pattern is going to be a very complicated mess.</li>
<li><strong>Not every If/Then/Else construction is a State Pattern</strong> &#8211; What makes it State is the State (a part of) your application is in. States? &#8220;Logged in/Logged out&#8221; is a state. &#8220;Saved/Unsaved&#8221; is a state. &#8220;Changed/Unchanged&#8221; is a state. &#8220;Going up/down/left/right&#8221; is a state.</li>
<li><strong>Do some refactorings on chains of If/Then/Else statements</strong> &#8211; And see if a State Pattern emerges. Verify it with the given example is clear and if you can find better ways to do it than I did.</li>
<li><strong>Verify my refactoring to a State Pattern</strong> &#8211; Using &#8220;Design Patterns for Dummies&#8221; and &#8220;Design Patterns&#8221;. See if I am right or wrong.</li>
</ol>
</div>
</div>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/flashworks.wordpress.com/791/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/flashworks.wordpress.com/791/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/flashworks.wordpress.com/791/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/flashworks.wordpress.com/791/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/flashworks.wordpress.com/791/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/flashworks.wordpress.com/791/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/flashworks.wordpress.com/791/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/flashworks.wordpress.com/791/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/flashworks.wordpress.com/791/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/flashworks.wordpress.com/791/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/flashworks.wordpress.com/791/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/flashworks.wordpress.com/791/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/flashworks.wordpress.com/791/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/flashworks.wordpress.com/791/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=flashworks.wordpress.com&amp;blog=7295152&amp;post=791&amp;subd=flashworks&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://flashworks.wordpress.com/2011/08/01/design-patterns-refactoring-an-ifthenelse-state-handler-using-the-state-pattern/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/cffc2ff7b980a5f5f76c22bddba4f361?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">peter kaptein</media:title>
		</media:content>
	</item>
		<item>
		<title>Design Patterns: Using Maps to cancel out Switch statements</title>
		<link>http://flashworks.wordpress.com/2011/07/30/design-patterns-cancelling-out-switch-statements/</link>
		<comments>http://flashworks.wordpress.com/2011/07/30/design-patterns-cancelling-out-switch-statements/#comments</comments>
		<pubDate>Sat, 30 Jul 2011 22:14:14 +0000</pubDate>
		<dc:creator>Peter Kaptein</dc:creator>
				<category><![CDATA[Design patterns]]></category>

		<guid isPermaLink="false">http://flashworks.wordpress.com/?p=754</guid>
		<description><![CDATA[Cancelling out Switch statements [Removed from other post - requires editing] If you take the code example from &#8220;Design Patterns for Dummies&#8221;, &#8220;Design Patterns&#8221; or &#8220;C# Design Patterns&#8221; and many other resources you will find by default a Switch statement like this: // The default Switch Statement you find in a lot of code (examples) [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=flashworks.wordpress.com&amp;blog=7295152&amp;post=754&amp;subd=flashworks&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<h2>Cancelling out Switch statements</h2>
<p>[Removed from other post - requires editing] If you take the code example from &#8220;Design Patterns for Dummies&#8221;, &#8220;Design Patterns&#8221; or &#8220;C# Design Patterns&#8221; and many other resources you will find by default a Switch statement like this:</p>
<pre>// The default Switch Statement you find in a lot of code (examples)
Switch ( myValue)
{
   case  SOME_CONSTANT1:
      // Do something if this condition is met
      break;
   case SOME_CONSTANT2:
      // Do something else
      break; 
      // and so on...
   default:
      // capture when no condition is met
}</pre>
<p>Or an if/then construction</p>
<pre>// Your run of the mill if/then else if you do not switch
if(myValue==SOME_CONSTANT1)
{
   // Do something
}
if(myValue==SOME_CONSTANT2)
{
   // Do something else
}</pre>
<p>Instead I (started to consistently) use the following:</p>
<pre>// map whatever you want to do on a specific value
public method mapActionToValue(method:Method, myValue:String)
{
   // Map action to value, which is in most cases a constant 
   actionToValueLookopTable[myValue]=method; 
}
// Execute the action we need
public method actOnSpecificConstantValue(myConstantValue:String)
{
   // get the method we mapped to the value
   var myMappedMethod:Method = actionToValueLookupTable[myConstantValue];
   // Exit gracefully if we have no method (or throw an exception)
   if(myMappedMethod==null)
   {
       return "";
   } 
   // Execute the action - internally we know how
   var myReturnValue:String = myMappedMethod() ;
   // Return the result
   return myReturnValue; 
}</pre>
<p>The code above is simplified. One thing missing for instance are the sanity checks to assure that the injection and retrieval are not crashing the application due to illegal actions which a specific language does not allow.</p>
<h2><em>Mapping objects, classes and methods</em></h2>
<p>The example above maps Methods to Constants. You are not limited to that, however in most languages. Java, JavaScript, ActionScript and C# allow you to map the following:</p>
<ol>
<li><strong>References to methods</strong> - Allowing you to invoke these methods later, provided that you use the proper number and types of parameters. The reason to avoid this is that you obscure the methods themselves. In contradiction to Objects, you can not always explicitly state what &#8220;type&#8221; of method you get back from your map.</li>
<li><strong>References to objects</strong> - Allowing you to prepare a set of Handlers which deal with the context-specific requests, as we did with our example above.</li>
<li><strong>References to classes</strong> - Allowing you to create new objects based on the class, or invoke static methods.</li>
</ol>
<div>
<h2><em>Why mapping is a better approach &#8211; in specific cases</em></h2>
<ol>
<li><strong>Scalability and maintainability</strong> - When you expand your library of options, you do not have to add new Switch or If/Then statements. Simply map your (constant) values to your actions and trust your code to execute the proper actions.</li>
<li><strong>Reduction of code</strong> - As a project grows, Switch and If/Then/Else statements can grow to hundreds of lines, just to cover all situations.</li>
<li><strong>The possibility to extend your existing lists of options from outside</strong> - Using injection. Especially when you build a framework which allows other to add and extend your original code base with extra classes and handlers, your base code does not need a rewrite (as long as they stick to your rules) as each</li>
</ol>
</div>
<h2><em>When mapping is a better approach</em></h2>
<div>
<ol>
<li><strong>If you use a set of specific objects to handle stuff</strong> -  For instance to parse data in different ways, or when you want to retrieve a specific view state in your application.</li>
<li><strong>Creation of specific objects based on context or value</strong> - If you want to create new objects of a specific type in specific situations, see: &#8220;Which patterns benefit directly from mapping&#8221;</li>
<li><strong>If you want or need Dynamic lists</strong> - For instance to allow the user of your code to create Environments with 3, 5 and 200 colors.</li>
</ol>
<div>
<h2><em>When it is better not to use mapping</em></h2>
<div>
<ol>
<li><strong>If you call methods within your current Class</strong> - you will only create code overhead without winning anything.</li>
</ol>
</div>
</div>
<h2><em>A list of Design Patterns which benefit directly from mapping</em></h2>
<p>The following Desing Patterns benefit directly from Mapping:</p>
<ol>
<li>Strategy</li>
<li>Factory</li>
<li>Builder</li>
<li>Interpreter</li>
</ol>
<div>The Mediator and State Pattern might benefit, but that depends on what they are supposed to do.</div>
</div>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/flashworks.wordpress.com/754/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/flashworks.wordpress.com/754/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/flashworks.wordpress.com/754/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/flashworks.wordpress.com/754/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/flashworks.wordpress.com/754/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/flashworks.wordpress.com/754/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/flashworks.wordpress.com/754/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/flashworks.wordpress.com/754/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/flashworks.wordpress.com/754/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/flashworks.wordpress.com/754/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/flashworks.wordpress.com/754/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/flashworks.wordpress.com/754/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/flashworks.wordpress.com/754/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/flashworks.wordpress.com/754/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=flashworks.wordpress.com&amp;blog=7295152&amp;post=754&amp;subd=flashworks&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://flashworks.wordpress.com/2011/07/30/design-patterns-cancelling-out-switch-statements/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/cffc2ff7b980a5f5f76c22bddba4f361?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">peter kaptein</media:title>
		</media:content>
	</item>
		<item>
		<title>Design Patterns: Getting things done (1) Managing processes with the Mediator and State Pattern</title>
		<link>http://flashworks.wordpress.com/2011/07/30/design-patterns-context-specific-results-and-objects/</link>
		<comments>http://flashworks.wordpress.com/2011/07/30/design-patterns-context-specific-results-and-objects/#comments</comments>
		<pubDate>Sat, 30 Jul 2011 22:13:11 +0000</pubDate>
		<dc:creator>Peter Kaptein</dc:creator>
				<category><![CDATA[Design patterns]]></category>
		<category><![CDATA[Getting things done]]></category>
		<category><![CDATA[design patterns]]></category>
		<category><![CDATA[managing processes]]></category>
		<category><![CDATA[mediator pattern]]></category>
		<category><![CDATA[state pattern]]></category>
		<category><![CDATA[strategy pattern]]></category>

		<guid isPermaLink="false">http://flashworks.wordpress.com/?p=750</guid>
		<description><![CDATA[In this post and the next series of posts we will look at 6 patterns to get thing done. The Mediator and State Pattern This post will focus on the Mediator and State Pattern and provides you a brief overview of the similarities and differences in use and approach. To improve some of the shortcomings [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=flashworks.wordpress.com&amp;blog=7295152&amp;post=750&amp;subd=flashworks&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>In this post and the next series of posts we will look at 6 patterns to get thing done.</p>
<h2>The Mediator and State Pattern</h2>
<p>This post will focus on the Mediator and State Pattern and provides you a brief overview of the similarities and differences in use and approach.</p>
<p>To improve some of the shortcomings of the State Pattern (centralized management of State) I also briefly go into two different additonal &#8220;patterns&#8221; called the: &#8220;State Maanger&#8221; and: &#8220;State Machine&#8221;.</p>
<h2>Next posts</h2>
<p>Next posts will go into the Strategy and (Simple Factory) and the Builder and Interpreter and Decorator Patterns.</p>
<h2>Overview</h2>
<p>I separate the patterns &#8220;to get things done&#8221; in three different groups, based on the use. A fourth group contains supporting patterns that help you refine specific strategies in the first three categories.</p>
<p>Each of the first three groups are patterns to offer you a context specific and dynamic way to deal with specific situations. It allows you to move from &#8220;single option processing&#8221; to &#8220;multiple option processing&#8221;:</p>
<ol>
<li><span class="Apple-style-span" style="font-weight:800;">How do you want to manage and handle (user/system based) actions?</span> &#8211; Depending on the state of (a part of) your application, the type of response to a specific action changes. A simple example: when you are saving a file, pressing &#8220;Save&#8221; again should result in no action at all.</li>
<ol>
<li><strong><strong>Mediator Pattern</strong></strong> - Use when you need to manage complex processes. Can be used as an logical alternative for a State Pattern.</li>
<li><strong>State Pattern</strong> &#8211; Use when the behavior of (a part of) your application changes based on the state (of a part of) your application.</li>
</ol>
<li><strong>How do you want to process stuff? </strong>- Where the Mediator and State Pattern are used to &#8220;manage&#8221; processes based on (business) logic, Strategy and (Simple) Factory are mostly used to offer dynamic ways to <span style="text-decoration:underline;">handle</span> stuff and <span style="text-decoration:underline;">produce</span> context-specific objects.</li>
<ol>
<li><strong> Strategy Pattern</strong> &#8211; Use when you have several ways to solve one problem (your strategy) and you want an easy way to choose that strategy dynamically</li>
<li><strong>(Simple) Factory</strong> &#8211; Use when you want to create specific objects of a specific type. The (Simple) Factory is/seems very similar to the Strategy Pattern, with this different: the intention of the Strategy Pattern is to select one out of multiple ways (strategies) to solve a problem.</li>
</ol>
<li><strong>How do you want to construct (composite) objects? </strong>- The area where I find most use of the Builder and Interpreter Pattern is in building dynamic/configurable Graphical User Interfaces based on XML input. Each GUI is in the basis a Composite of nested objects (Forms, containing fields, buttons and checkboxes for instance). Using a Builder or Interpreter and (XML) input allows you to &#8220;inject&#8221; any GUI you want and need.</li>
<ol>
<li><strong>Builder Pattern</strong> &#8211; The Builder Pattern creates a dynamic (object) model based on rules or fixed patterns. It is most similar to a kid using LEGO.</li>
<li><strong>Interpreter Pattern</strong> &#8211; Uses clear text instructions as a basis to construct composite objects or handle data in specific ways. Parsing HTML code into a working web page can be a simple example of an Interpreter.</li>
</ol>
<li><strong>Supporting patterns</strong></li>
<ol>
<li><strong>Decorator Pattern</strong> &#8211; Encapsulates objects to extend their possibilities. While on the edge of: &#8220;does it really belong in this list?&#8221;, the way you can use the Decorator Pattern says &#8220;yes&#8221;.</li>
<li><strong>Composite Pattern</strong> &#8211; In the context of this series I consider the Composite Pattern as a possible tool for two other Patterns: Interpreter and Builder Pattern.</li>
<li><strong>State Machine</strong> &#8211; The State Machine (see this <a href="http://en.wikipedia.org/wiki/Automata-based_programming">WikiPedia entry</a> on the software implementation) can help you fix one of the possible weaknesses (depending on your implementation) of the State Pattern: that management and state changes are localized in each State Handler in the State Pattern</li>
</ol>
</ol>
<h2>Mapping it</h2>
<div id="attachment_752" class="wp-caption alignnone" style="width: 604px"><a href="http://flashworks.files.wordpress.com/2011/07/designpatterns_11.png"><img class="size-full wp-image-752" title="designpatterns_1" src="http://flashworks.files.wordpress.com/2011/07/designpatterns_11.png?w=594&#038;h=450" alt="" width="594" height="450" /></a><p class="wp-caption-text">Result and Object based</p></div>
<h2>What do you need: Results or Objects? &#8211; a separation</h2>
<div>When you look at your needs: what is it that will drive the solution to your problem?</div>
<div>
<ol>
<li><strong>You need a Result</strong> &#8211; For instance: parsing XML to Objects, or a specific behavior in a specific state of (a part of) your application. Both State and Strategy can help you, where State is more focused on Actions and Strategy more suited to process or handle stuff.</li>
<li><strong>You need Objects</strong> &#8211; for instance: to present something, or to deal with specific situations. You will find these &#8211; and similar &#8211; patterns a lot when you work with front-end code.</li>
</ol>
<h2>Brief on State and Mediator: when do you need them?</h2>
<h2><em>A uses case: saving a file</em></h2>
<p>Imagine the example given earlier: where you have an application that saves a file to a specific location. The action of saving a file has different states:</p>
<ol>
<li><strong>Not saved, not changed</strong> &#8211; File is not saved (yet), but the user did not change anything</li>
<li><strong>Not saved, changed</strong> &#8211; File is not savedm but the user (or the system) changed something</li>
<li><strong>Saving</strong> &#8211; The system is saving the file</li>
<li><strong>Saved</strong> &#8211; The system has saved the file</li>
</ol>
<div>While saving, you want to implement the following rules:</div>
<div>
<ol>
<li><strong>The user can not repeat the Save request while the file is saving</strong> &#8211; To avoid issues due the the fact that a requested process is already running, you either want to</li>
<ol>
<li><strong>Postpone the request</strong> &#8211; Until the previous one is done</li>
<li><strong>Ignore the request</strong> &#8211; As the system is blocking anyway and no supplemental changes are done, or because you will request the user to try again when saving is done</li>
</ol>
<li><strong>The user can make successive edits while the file is saving</strong> &#8211; As:</li>
<ol>
<li><strong>The process is asynchronous</strong> &#8211; And can take several seconds to finish as the file might be saved over a network connection</li>
<li><strong>You want a non-blocking system</strong> &#8211; To allow the user to &#8220;work while waiting&#8221;</li>
<li><strong>The file that is saved is an isolated copy</strong> &#8211; Of the file to be saved and additional changes do not corrupt the data you are saving at the same time</li>
</ol>
</ol>
</div>
<p>For each State (Not saved/not changed, Not saved/changed, etcetera) you have different responses to the same user action.</p>
<p>Additionally, you might want to add an additional set of states to respond to, to assure the best response, based on the situation the user is in. For instance:</p>
<ol>
<li><strong>Remote location, fast connection</strong> &#8211; When the user saves the file, it is done in seconds</li>
<li><strong>Remote location, slow connection</strong> &#8211; When the user saves the file, it can take minutes</li>
<li><strong>Local storage, fast</strong> &#8211; When the user saves the file, it is done in seconds</li>
<li><strong>Local storage, slow</strong> &#8211; (Like a pen drive.) When the user saves the file, it can take minutes</li>
</ol>
<p>It might be that you want to incorporate the situational states (fast or slow storage, remote and local) into your decision-making process as well. And it might be that you want to change your strategy half way through the process as your original line of thought when you started turns out to be wrong when you test it.</p>
<p>If your first choice is to solve this case with &#8220;If/Then/Else&#8221; statements, inline code and method calls to do the actual work, you are on your way to create a State or Mediator Patterns.</p>
<h2><em>State and Mediator Pattern to the </em><em>rescue</em></h2>
<p>The State and Mediator Pattern help you cut this case into clear parts and a clear pattern.</p>
<p>Each of these two patterns has a specific approach to it</p>
<p>State and Mediator differ mostly in the way they manage State and State Specific Actions:</p>
<ol>
<li><strong>State: Internal resolve and Distributed <strong>Control -</strong></strong> The State Pattern puts the responsibility of managing the (next) State into the hands of each individual State Handler. As there can be many State Handlers each capable of- and allowed to decide what the next , management is distributed over the State Handlers themselves. The State Handlers in most implementations of a State Pattern (at least in the text book examples) resolve the management of the process internally.</li>
<li><strong><strong>Mediator: Delegation and Centralized Control </strong></strong>- Instead the Mediator manages the state of an application centrally and (usually) delegates the real implementation of the state related actions to separate objects, handlers or classes. These handlers should not be allowed to decide what step is next, nor should they be allowed to manipulate any data in the Mediator. To keep control over all processes (and to avoid stuff from happening somewhere, derailing stuff elsewhere) the Mediator should never allow other components to &#8220;Mediate&#8221; as well.</li>
</ol>
<div>
<h2><em>Summarizing</em></h2>
<div>
<p>The State and Mediator Pattern are most valuable in situations where you have:</p>
<ol>
<li><strong>Context specific responses to actions, based on the state of (a part of) the application</strong> - Where the state of (a part of) an application can be: &#8220;user is logged in/out&#8221;, &#8220;user is looking at tab 1 of the application&#8221;, &#8220;user is filling in part one of a form&#8221;, &#8220;user pressed on submit&#8221;, &#8220;system is unable to connect to the database&#8221; and so on. And where the response might be: hiding and showing elements the user does not- and does need at that stage of the application, blocking specific actions until the state changes to one where those actions are allowed, removing or moving or adding elements based on drag and drop or click actions (think visual editors).</li>
<li><strong>Bloated classes due to situation specific responses</strong> - Where specific actions based on If/then/else becomes start to bloat your classes towards 500 lines of code and more.</li>
</ol>
</div>
</div>
</div>
<h2>Changing the color of your screen &#8211; a simple use case for a code example</h2>
<p>Lets say you have a button that flips the color of your screen through three different colors in a fixed sequence:</p>
<ol>
<li>From Red</li>
<li>To Green</li>
<li>To Blue</li>
<li>To Red again (and the cycle repeats)</li>
</ol>
<p>Each color presented can be seen as a &#8220;state&#8221;.</p>
<p>Let&#8217;s assume further that each State has a very specific next step. I can only move from Red to Green to Blue to Red.</p>
<h2>Using the State Pattern &#8211; localizing decision making in State Handlers</h2>
<p>In the State Pattern, each State is represented in a specific object, that holds all logic and data for that specific state.</p>
<p>For instance (pseudo-code):</p>
<pre>class ColorState
{     
      <span style="color:#008000;">// We inject the next state via the Environment</span>
      public var <span style="color:#ff0000;">nextState</span>: ColorState;
      private var environment:Environment;
      private var color:uint;
      public method ColorState(environment, color)
      {
            <span style="color:#008000;">// Set environment. so we can pass next state</span>
            this.environment=environment;
            <span style="color:#008000;">// set Color</span>
            this.<span style="color:#ff0000;">color</span>=<span style="color:#ff0000;">color</span>
      }
      public method setColor()
      {
              environment.backgroundColor=this.color;
<span style="color:#008000;">             // Inject next state so next time the user presses button,</span>
<span class="Apple-style-span" style="color:#008000;">             // the next state will handle the color</span>
              environment.<span style="color:#ff0000;">state</span>=this.<span style="color:#ff0000;">nextState</span>;
      }
}</pre>
<p>Our main Class might look something like this:</p>
<pre>class Environment
{
       private var redState, greenState, blueState : ColorState;
       private var currentState :ColorState; 
       public Environment()
       { 
              <span style="color:#008000;">// Define the states</span>
              <span style="color:#0000ff;">blueState</span>=new ColorState (this,#<span style="color:#ff0000;">0000ff</span>);
              <span style="color:#0000ff;">redState</span>=new ColorState(this,#<span style="color:#ff0000;">ff0000</span>); 
              <span style="color:#0000ff;">greenState</span>=new ColorState(this,#<span style="color:#ff0000;">00ff00</span>);
              <span style="color:#008000;">// Define the next state - this is to illustrate</span>
              blueState.<span style="color:#ff0000;">nextState</span>=<span style="color:#0000ff;">redState</span>;
              redState.<span style="color:#ff0000;">nextState</span>= <span style="color:#0000ff;">greenState</span>;
              greenState.<span style="color:#ff0000;">nextState</span>=<span style="color:#0000ff;">blueState</span>; 
              <span style="color:#008000;">// Set current state - this will set the color and inject the next state</span>
              currentState =blueState
              <span style="color:#008000;">// Activate the state to start the process</span>
              state.<span style="color:#ff0000;">setColor</span>();
              <span style="color:#008000;">// Set the button click handler</span>
              colorChangeButton.<span style="color:#0000ff;">onClick</span>=<span style="color:#ff0000;">onButtonClick</span>; 
       }
       public method <span style="color:#ff0000;">onButtonClick</span>(evt:Event)
       {
<span style="color:#008000;">               // As our state objects deal with all state specific administration,</span>
<span style="color:#008000;">               // we just call the method and trust our State Object to deal with the rest</span>
               currentState.<span style="color:#ff0000;">setColor</span>();
<span style="color:#008000;">               // Done</span>
         }
}</pre>
<p>In this very simple example we define the different states when we initialize the Environment.</p>
<p>Each time the user clicks the Color Change Button, the State Objects will determine what to do on a specific method call (in our case only one) and if a new state needs to be injected.</p>
<p>In this example we also used only one class for our State Object, as we only needed to do two things:</p>
<ol>
<li><strong>Inject the next state</strong> &#8211; Into our Environment</li>
<li><strong>Change the color</strong> &#8211; Of our screen</li>
</ol>
<div>It is possible that your State Objects are created from several different Classes, as the behaviors per State are very different. In that case, using Inheritance and implementing Interfaces are your first actions per class.</div>
<h2><em>Two things I do not like on this textbook example</em></h2>
<ol>
<li><strong>We have a double reference between Environment and the State Handler</strong> &#8211; The State Handler references to the Environment and the Environment references to a (the current) State Handler. Which is a form of tight coupling that can be avoided and when avoided leads to cleaner and more agile code.</li>
<li><strong>We store (a part of) the State of the Environment in the Environment itself</strong> - Which seems OK when it is only one state per Environment. Unfortunately, things are seldom that simple. In practice, this approach leads to an increasing mess when more and more states for specific situations (think of specific states hiding and showing specific buttons) are added. Better is to externalize all state-specific stuff to a separate class that then manages the object you manage the state of. See: &#8220;Using State Machines&#8221; further down this post.</li>
</ol>
<h2>The Mediator Pattern &#8211; centralizing decision making</h2>
<p>The Mediator Pattern follows a (completely) different approach to deal with issues. Where the State Pattern allows for decentralized management, the Mediator Pattern centralizes that decision making into one place.</p>
<p>Lets look at our color-example.</p>
<pre>class ColorMediator
{
   private var environment:Environment;
   private var colorHandlerList:Dictionary&lt;string,ColorHandler&gt;=new Dictionary&lt;string,ColorHandler&gt;(); 
<span style="color:#008000;">  // As we want to keep full control we keep the state internal</span>
   public var currentColorHandler;
   public ColorMediator(environment: Environment) 
   {
     <span style="color:#008000;">  // Set environment</span>
       this.environment=environment;
   }
   public injectColorHandler(fromColorHandler, toColorHandler) 
   {
<span style="color:#008000;">     // We simplify management in this example by using a lookup table</span>
      colorHandlerList.add(fromColorHandler.color, toColorHandler);
   }
   public method init()
   {
      <span style="color:#008000;">// We activate the current handler</span>
      this.currentColorHandler.go();
   } 
   public method setNextColor()
   {
<span style="color:#008000;">      // One of the options to manage/mediate is to supply the information</span>
<span style="color:#008000;">      //  we need to decide which next color/handler to use</span>
<span style="color:#008000;">      // As we use a lookup table, we can avoid the dreaded Switch statements</span>
<span style="color:#008000;">      // you normally see in an example like this.</span>
      var nextColorHandler:ColorHandler= colorHandlerList[this.currentColorHandler];
      if(nextColorHandler==null)
      {
 <span style="color:#008000;">        // OOPS! you configured the color sequence wrongly</span>
<span style="color:#008000;">         // As this is a Mediator, you can choose to solve this by offering an alternative path</span>
          nextColorHandler = colorHandlerList.Values[0]; // get first value
       }
      <span style="color:#008000;"> // Active the next color handler and set the color on the environment</span>
       nextColorHandler.go(this.environment);
   }
}</pre>
<p>There is a lot of things to say about this approach. I limit myself to 9 points:</p>
<ol>
<li><strong>This is a very simple Mediator</strong> &#8211; When your application grows, more and more business rules will pop up in your application. Those situations are out of scope of this post, but will be clarified in a later post.</li>
<li><strong>We map the next Color Handler in a Lookup Table</strong> &#8211; Against the previous Color. This is a neat trick Dictionaries allow you to do. We could also have used the Color Handler itself, but that felt less clean.</li>
<li><strong>Do not fixate on this solution</strong> &#8211; There are many ways to write a (simple) Mediator and this is only one of them.</li>
<li><strong>I assume the colorHandlerList has values</strong> &#8211; Which is very naive. The code should first check if there are any values in the color Handler List.</li>
<li><strong>The color manager only knows one direction</strong> &#8211; Which is forward. It might also be allowed to branch on specific conditions, or move backwards.</li>
<li><strong>If you want to be able to navigate colors in more directions, discard this approach</strong> &#8211; Or the mapping issues it creates will drive you nuts</li>
<li><strong>I inject the Environment into the Color Handler</strong> &#8211; Which reduces depencencies and makes the Color Handler a neutral object, only required to deal with its internal stuff.</li>
<li><strong>I no longer keep State in the Environment</strong> &#8211; Which is smart if your application becomes more and more complex. The Environment can become a dumb object with just one simple task. All (state) management is done in your mediator.</li>
<li><strong>We now need 3 classes instead of 2</strong> &#8211; As the management part is now externalized and centralized in the Color Mediator Class</li>
</ol>
<div>
<p>Our ColorHandler might look like this:</p>
<pre>class ColorHandler
{
     private var color;
     public ColorHandler(color) 
     {
<span style="color:#008000;">             // Store the color</span>
             this.color = color;
     }
     public go(environment:Environment)
     {
<span style="color:#008000;">             // Set the stored color on the given environment</span>
             environment.backgroundColor=this.color;
<span style="color:#008000;">             // Done</span>
      }
}</pre>
<p>Our main Class now might look something like this:</p>
<pre>class Environment
{
   private var redHandler, greeHandler, blueHandler : ColorHandler;
<strong><span style="color:#ff0000;">   // Removed: private var currentState :ColorState;</span></strong>
<span style="color:#000000;"><span style="color:#008000;"> // Added</span> <strong> private var mediator: ColorMediator=new ColorMediator()</strong></span>
   public Environment()
   { 
<span style="color:#008000;">      // Define the handlers</span>
       blueHandler=new ColorHandler (#<span style="color:#ff0000;">0000ff</span>);
       redHandler=new ColorHandler(#<span style="color:#ff0000;">ff0000</span>); 
       greenHandler=new ColorHandler(#<span style="color:#ff0000;">00ff00</span>);
       <span style="color:#008000;">// Add them to the Mediator, with "from" color and "to" color handler </span>
<strong>      mediator.injectColorHandler(redHandler,greenHandler);</strong>
<strong>       mediator.injectColorHandler(greenHandler, blueHandler);</strong>
<strong>       mediator.injectColorHandler(blueHandler, redHandler);</strong>

       <span style="color:#008000;">// Set current state - this will set the color and inject the next state</span>
       <strong>mediator.currentColorHandler =blueHandler</strong>

       <span style="color:#008000;">// Activate the state to start the process</span>
       <strong>mediator.init();</strong>
       <span style="color:#008000;">// Set the button click handler</span>
       colorChangeButton.onClick=onButtonClick; 
   }
   public method onButtonClick(evt:Event)
   {
<span style="color:#008000;">        // As our mediator deals with all state specific administration,</span>
<span style="color:#008000;">       // we just call the method and trust our mediator to deal with the rest</span>
      <strong>  mediator.setNextColor();</strong>
<span style="color:#008000;">       // Done</span>
    }
}</pre>
</div>
<p>Both Mediator and State externalize and encapsulate the logic to deal with context-specific (user) actions.</p>
<h2><em>Three main benefits of the Mediator &#8211; in this example</em></h2>
<p>This delivers you a series of benefits of which I name 3:</p>
<ol>
<li><strong>Cleaner code</strong> &#8211; Instead of having a Environment Class with a load of code dealing with each specific state (the colors) we now have State Handlers and/ore Color Handlers and a Mediator to deal with this</li>
<li><strong>Agilitiy</strong> &#8211; As you externalized and encapsulated the decision making logic, your code becomes more agile. Meaning that if you want to try a different approach to your decision making process, you simply create a new or different set of State Handlers and/or Mediators which you can plug in and remove to your own liking</li>
<li><strong>More stable code base and less errors due to mess</strong> &#8211; As each Handler (should have) a clear purpose, changes are either an improvement on existing code, or done in a new class that (possibly) extends your current code. This allows for code changes and changes of mind to be isolated and reversible. &#8211; If you do not like solution &#8220;Y&#8221; in Class &#8220;Z&#8221;, you simply use solution &#8220;A&#8221; in Class &#8220;B&#8221; instead. As your code stays clean, the risk of messing up code that worked well previously is reduced as well.</li>
</ol>
<h2>Where I do things differently &#8211; using Maps to cancel out Switch statements</h2>
<p>You might have noticed my use of a Dictionary in the Mediator and injection of Handlers using mediator.inectHandler. If you take the code example from &#8220;Design Patterns for Dummies&#8221;, &#8220;Design Patterns&#8221; or &#8220;C# Design Patterns&#8221; and many other resources you will find in examples like the one above (almost by default) a Switch statement like this:</p>
<pre><span style="color:#008000;">// The default Switch Statement you find in a lot of code (examples)</span>
Switch ( myValue)
{
   case  SOME_CONSTANT1:
<span style="color:#008000;">      // Do something if this condition is met</span>
      break;
   case SOME_CONSTANT2:
<span style="color:#008000;">      // Do something else <span style="color:#000000;"> break; </span></span>
<span style="color:#008000;">   // and so on...</span>
   default:
<span style="color:#008000;">      // capture when no condition is met</span>
}</pre>
<p>This seems quite harmless and &#8211; as many people and many authors of books on coding use it and &#8211; completely OK.</p>
<p>Think twice. Think clean code. Think of what is happening here: using hardcoded references to map events or objects to return specific values or perform specific actions.</p>
<p>See the specific post on &#8220;<a title="Design Patterns: Using Maps to cancel out Switch statements" href="http://flashworks.wordpress.com/2011/07/30/design-patterns-cancelling-out-switch-statements/">Using Maps to Cancel out Switch Statements</a>&#8221; for more information on mapping objects, classes and methods to values and constants.</p>
<h2>Using State Machines</h2>
<p>One weakness of the implementation of the State Pattern as shown above is &#8211; as mentioned in the brief on the Mediator Pattern &#8211; is that the State of (a part of) the application is set in the Environment the State Handler controls. The more State variables you will have to remember for a specific Environment (think of tabs hiding and showing specific content, buttons and (text) fields being shown and hidden in specific states, and so on) the more your Environment becomes cluttered with variables you might want to manage somewhere else. (Think MVC here, where the View is just presenting data and has no awareness of any State it might be in)</p>
<p>Another weakness is that the State Handlers themselves hold references to the Environment.</p>
<p>When you start refactoring your project, this entanglement of objects might be something you want to clean up and/or get rid of. For this purpose you can use a State Machine.</p>
<p>The State Machine lives between the Environment and your State Handlers. It is the proxy between your Controller (in an MVC situation) your State Handlers and your View. Any reference to any object is managed by the State Machine and when any State Handler wants to switch states and show or hide elements (for instance) it invokes a method on the State Machine, which will do the actual work on the actual objects.</p>
<p>This decoupling makes your State Handlers more versitile and more re-usable.</p>
<p>Think for instance of generic Application Wide State Handlers which take care of  showing and hiding data and specific visual elements when a User is logged in or just visiting as a Guest.</p>
<div>
<h2>Concluding</h2>
<p>The State and Mediator Pattern are most valuable in situations where you have:</p>
<ol>
<li><strong>Responses to actions are based on the state of (a part of) the application</strong> - Where the state of (a part of) an application can be: &#8220;user is logged in/out&#8221;, &#8220;user is looking at tab 1 of the application&#8221;, &#8220;user is filling in part one of a form&#8221;, &#8220;user pressed on submit&#8221;, &#8220;system is unable to connect to the database&#8221; and so on. And where the response might be: hiding and showing elements the user does not- and does need at that stage of the application, blocking specific actions until the state changes to one where those actions are allowed, removing or moving or adding elements based on drag and drop or click actions (think visual editors).</li>
<li><strong>Bloated classes due to situation specific responses</strong> &#8211; Where specific actions based on If/then/else becomes start to bloat your classes towards 500 lines of code and more.</li>
</ol>
<p>State and Mediator differ mostly in the way they manage State and State Specific Actions:</p>
<ol>
<li><strong>State: Distributed <strong>management -</strong></strong> Of State and State Specific actions. The State Pattern puts the responsibility of managing the (next) State into the hands of each individual State Handler.</li>
<li><strong><strong>Mediator: Centralized management</strong></strong> - Of State and State specific actions. Instead the Mediator manages the state of an application centrally and (usually) delegates the real implementation of the state related actions to separate objects, handlers or classes.</li>
</ol>
</div>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/flashworks.wordpress.com/750/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/flashworks.wordpress.com/750/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/flashworks.wordpress.com/750/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/flashworks.wordpress.com/750/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/flashworks.wordpress.com/750/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/flashworks.wordpress.com/750/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/flashworks.wordpress.com/750/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/flashworks.wordpress.com/750/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/flashworks.wordpress.com/750/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/flashworks.wordpress.com/750/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/flashworks.wordpress.com/750/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/flashworks.wordpress.com/750/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/flashworks.wordpress.com/750/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/flashworks.wordpress.com/750/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=flashworks.wordpress.com&amp;blog=7295152&amp;post=750&amp;subd=flashworks&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://flashworks.wordpress.com/2011/07/30/design-patterns-context-specific-results-and-objects/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/cffc2ff7b980a5f5f76c22bddba4f361?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">peter kaptein</media:title>
		</media:content>

		<media:content url="http://flashworks.files.wordpress.com/2011/07/designpatterns_11.png" medium="image">
			<media:title type="html">designpatterns_1</media:title>
		</media:content>
	</item>
		<item>
		<title>Design patterns: an introduction</title>
		<link>http://flashworks.wordpress.com/2011/07/30/design-patterns-an-introduction/</link>
		<comments>http://flashworks.wordpress.com/2011/07/30/design-patterns-an-introduction/#comments</comments>
		<pubDate>Sat, 30 Jul 2011 12:15:38 +0000</pubDate>
		<dc:creator>Peter Kaptein</dc:creator>
				<category><![CDATA[Design patterns]]></category>
		<category><![CDATA[anti patterns]]></category>
		<category><![CDATA[c design patterns]]></category>
		<category><![CDATA[clean code]]></category>
		<category><![CDATA[design patterns]]></category>
		<category><![CDATA[steve holzner]]></category>
		<category><![CDATA[william sanders]]></category>

		<guid isPermaLink="false">http://flashworks.wordpress.com/?p=743</guid>
		<description><![CDATA[It has taken me a while to wrap my head around design patterns. I read four books recently, including &#8220;Design patterns&#8221; by the Gang of Four (referred to as &#8220;Design Patterns&#8221;, &#8220;Design Patterns for Dummies&#8221; by Steve Holzner, &#8220;C# Design Patterns&#8221; by Judith Bisshop and &#8220;ActionScript 3.0 Design Patterns&#8221; by William Sanders and Chandima Camarantunge. [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=flashworks.wordpress.com&amp;blog=7295152&amp;post=743&amp;subd=flashworks&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>It has taken me a while to wrap my head around design patterns.</p>
<p>I read four books recently, including &#8220;<a href="http://www.amazon.com/Design-Patterns-Elements-Reusable-Object-Oriented/dp/0201633612/ref=pd_sim_b_3">Design patterns</a>&#8221; by the Gang of Four (referred to as &#8220;Design Patterns&#8221;, &#8220;<a href="http://www.amazon.com/Design-Patterns-Dummies-Steve-Holzner/dp/0471798541">Design Patterns for Dummies</a>&#8221; by Steve Holzner, &#8220;<a href="http://www.amazon.com/3-0-Design-Patterns-Judith-Bishop/dp/059652773X/ref=sr_1_1?s=books&amp;ie=UTF8&amp;qid=1312018035&amp;sr=1-1">C# Design Patterns</a>&#8221; by Judith Bisshop and &#8220;<a href="http://www.amazon.com/ActionScript-3-0-Design-Patterns-Programming/dp/0596528469/ref=sr_1_1?s=books&amp;ie=UTF8&amp;qid=1312018136&amp;sr=1-1">ActionScript 3.0 Design Patterns</a>&#8221; by William Sanders and Chandima Camarantunge.</p>
<p>&#8220;Design Patterns&#8221; by the Gang of Four is the must have book for reference. If you are in doubt, or confused, go back to that one. &#8220;Design Patterns for Dummies&#8221; is the must have book to start with. I read them parallel and switched from one to the other to check accuracy on &#8220;..dummies&#8221; and decipher the meanings of cryptic writings in &#8220;Design Patterns&#8221;.</p>
<h2>I am not an Design Pattern expert</h2>
<p>I am a coder, a programmer and a software designer. I have written several frameworks for my own use, allowing me to re-use specific tricks and solutions I implemented before, while avoiding Copy &amp; Paste.</p>
<p>One of the main flaws in most of my frameworks was the lack of clean coding and a proper understanding of standards. Either due to lack of experience or due to lack of time.</p>
<h2>Refactoring, Clean Code and Distribution of Responsibility</h2>
<p>From over 15 years of programming experience my main tools to get to stable and solid code (as you will find in this post) are (and have become) Refactoring, Clean Code and Distribution of Responsibility.</p>
<h2>Why this series on Design Patterns?</h2>
<p>As I am working on two new Open Sourced frameworks, which are both completely rewritten revisions of older versions, Design Patterns and a proper understanding of Design Patterns have become increasingly important to me, to avoid stupid solutions and to allow others to get a better grip and a better point of entry on what I have done.</p>
<p>In a series of articles in FlashWorks I will explore the main Design Patterns as described in &#8220;Design Patterns&#8221; from a practical point of view: &#8220;I want this, what pattern is most suited?&#8221;</p>
<p>These articles are part of my own learning process to start mastering the Design Patterns which are there and which are most useful for my own use. Either to avoid or use them properly where they fit.</p>
<h2>Why I warn so much &#8220;against&#8221; Design Patterns</h2>
<p>As I have encountered several people in the past who claimed that Design Patterns were the start and beginning of all bliss in awesome coding, I give you a lot of warnings in this post, related to that point of view, as I have seen the bad side (and sometimes very bad coding) of that single minded attitude in projects I cleaned up: after the original team had abandoned it for whatever reasons (including lay-offs due to company restructurings).</p>
<h2>Why Design Patterns are hard to begin with</h2>
<p>I personally found three main reasons:</p>
<ol>
<li><strong>First encounter of patterns? Cryptic writings</strong> &#8211; Design patterns are (refactored) abstractions of recurring themes. The goal is to open that description as much as possible, so that the use is not limited to one single case. If we would apply that to a glass of water, the glass could become: &#8220;a container for fluids, made of several possible materials&#8221; &#8211; as we do not want to limit to a glass alone &#8211; &#8220;shaped to be held in a human hand&#8221; &#8211; as it is for human use &#8211; &#8220;for which one of the uses&#8221; &#8211; as we can use a glass also for other purposes &#8211; &#8220;is to move fluids from the container to the mouth&#8221;</li>
<li><strong>Contradictions,  white noise and limited views</strong> &#8211; Any writing on design patterns should be concise, clear and as open minded as possible. There are many ways to implement a design pattern, without breaking it. It is possible the writer of a book on design patterns focuses only on a few of those, lacks deeper experience, was battling the deadline or is a very linear thinker (all leading to limited views).  And there are many ways to misunderstand a design pattern (leading to contradictions). Anything that makes stuff even more complicated and that creates more work to decipher the real intents of the examples (white noise) is not helping but driving you further away from your goal.</li>
<li><strong>Hard to map with reality</strong> - When you are coding, you write code. You are solving several problems using methods, objects and specific tricks you know from your past. While your code<em> is going somewhere</em>, it is probably not following the rules of any design pattern. When you read design patterns it is hard to twist your minde around and find out which one applies and which one should apply.</li>
</ol>
<h2>Refactoring, code organization and design patterns</h2>
<p>When you read &#8220;Design Patterns&#8221;, one of the things mentioned in the introduction is that: <em>design patterns are an emerging result of your coding</em>. This is very important to understand.</p>
<p><span style="text-decoration:underline;">Design Patterns are &#8211; and should &#8211; never be a starting point</span>.</p>
<h2><em>Why design patterns should never be a starting point</em></h2>
<div>
<ol>
<li><strong>The type of your solutions change during a project</strong> &#8211; Where you start with Assumption &#8220;A&#8221;, this might change to Assumption &#8220;B&#8221; as your understanding grows and end up in Assumption &#8220;C&#8221; when you release the application. Where &#8220;A&#8221; is best to be done in a State pattern, &#8220;B&#8221; is best done with a Proxy and a Simple Factory, while the final solution, &#8220;C&#8221;, has discarded both State and Simple Factory (because both ended up being &#8220;anti patterns&#8221;: making things only more complicated) and relies complete on a Mediator with a mix of Factories and using Composition (as in using Composition instead of Inheritance) and a simple State Machine (which is not a State Pattern).</li>
<li><strong>Choosing the wrong Patterns can be your downfall</strong> &#8211; Brief: do not try to ram a round peg through a square hole. Each pattern is for a very specific approach to a very specific problem. Choosing the wrong pattern leads to code-overhead as you try to solve a problem with a tool that is made for something else.</li>
<li><strong>Code should be as short and simple as possible</strong> &#8211; More important than boasting about your use of design patterns is how clear your code is. The more lines you need to solve a problem, the more red flags should be raised in your mind that you might be heading in the wrong direction.</li>
</ol>
<h2><em>Why organizing your code and refactoring are your real friends</em></h2>
<p>If the type of your solutions change during your project and Design Patterns can work against you, what <em>can</em> you rely on?</p>
<p>I found two important friends in coding:</p>
<ol>
<li><strong>Organizing your code in a &#8220;Meta Pattern&#8221;</strong> &#8211; Which is &#8211;  in my case &#8211; based on the principle of Distribution of Responsibility and the promotion and demotion of code. In this meta-pattern I have (for instance): Managers, Handlers and Parsers, which are organized purely on what they <em>do </em>and what I<em> want them to do</em>. For instance: Handlers handle stuff, but do not make decisions. Parsers are very specific Handlers with a very specific role: to parse data from one format or structure to another. Managers are like Handlers, but smart. Managers run the show and make all the decisions. When refactoring I constantly move code from one place to another, until I feel that each Class is doing exactly what it is intended to do.<br />
The Meta-pattern is agnostic to any design pattern and completely open to any choice and any change in the choice of a design pattern. Its main goal is to help me clean up my code in constant runs: by using clearly defined places to put my stuff and find that stuff back.</li>
<li><strong>Refactoring</strong> &#8211; Refactoring is another word for: &#8220;cleaning up- and restructuring your code project and making stuff more simple to understand and better to read&#8221;. There are several books on/related to Refactoring and two books I recommend are: &#8220;<a href="http://www.amazon.com/Refactoring-Improving-Design-Existing-Code/dp/0201485672/ref=sr_1_1?s=books&amp;ie=UTF8&amp;qid=1312022272&amp;sr=1-1">Refactoring: improving the design of existing code</a>&#8221; by Martin Fowler and co. and &#8220;<a href="http://www.amazon.com/Clean-Code-Handbook-Software-Craftsmanship/dp/0132350882/ref=sr_1_1?s=books&amp;ie=UTF8&amp;qid=1312022227&amp;sr=1-1">Clean Code</a>&#8221; by Robert C. Martin and co. Bottom line: Do not be afraid to regularly (completely) revise your code base. Especially when your coding tools assist you in that. Most current tools (like Visual Studio and those based on and plugged into Eclipse) do. They show you what you break and where you broke it and help you rename and fix stuff in a matter of minutes by feedback and proper mapping of your code.</li>
</ol>
<div>Bottom line:</div>
<div>
<ol>
<li><strong>Code should be clear</strong> &#8211; Clear namings, clear responsibilities, clear what is going on, clear what is needed, clear what comes out, clear what it does not.</li>
<li><strong>Code should be clean</strong> &#8211; No dead code, no repetition, no fuzzy or distracting naming conventions like: &#8220;m_SomeVariable&#8221; and: &#8220;aSomething&#8221; which you find in Java for instance, no getters and setters where you do not need them. No useless comments: &#8220;because you boss told you that you have to comment stuff&#8221;</li>
<li><strong>Code should be organized</strong> &#8211; Clear placement, clear purpose, clear (class) structure. Simple to find back, consistent conventions.</li>
<li><strong>Refactoring is your best friend</strong> &#8211; When refactoring, your are constantly moving stuff around and cleaning stuff up to achieve a Clear, Clean and Organized code base. By doing this you (can) achieve several very useful &#8220;byproducts&#8221;:</li>
<ol>
<li><strong>Re-useable code</strong> &#8211; As code is cleaned up, restructured and extracted (read the books) it becomes more and more re-useable</li>
<li><strong>Reduction of vulnerabilities</strong> &#8211; As you refactor, clarify and clean up your code, your code becomes more and more &#8220;unbreakable&#8221; as you go. Where most &#8220;dirty code&#8221; has five or more places where one specific thing can go wrong (due to repetition of code and messy procedures) refactored code has one or two, which are usually very simple to fix.</li>
<li><strong>Easier to restructure</strong> &#8211; Messy and un-refactored code has a lot of entanglements of dependencies. When you change &#8220;A&#8221;, &#8220;B&#8221; and &#8220;C&#8221; will probably break. In most cases, that is why change is something you rather do not. In your refactoring process, breaking your code &#8211; with the purpose to reduce those dependencies- is part of your (daily) routine. You will find that the cleaner your code becomes, the more agile you will become. Re-routing a process from &#8220;A&#8221; to &#8220;B&#8221; will not increase the mess and the headaches, but lead to even better and cleaner code.</li>
</ol>
<li><strong>Design Patterns are an emerging result, not a purpose</strong> &#8211; As you refactor and clean up your code, more and Code Patterns will start to emerge: repeating patterns in several places in your code. In some cases, these will look very much like the 23 as mentioned in &#8220;Design Patterns&#8221;. In most cases they will not. Fear not: when Code Patterns emerge -</li>
<ol>
<li><strong>Smile! You are on the Right Path</strong> &#8211; The design patterns in &#8220;Design Patterns&#8221; are only 23 out of several hundreds. And none are a holy truth or &#8220;The Only Way&#8221;.</li>
<li><strong>You should refactor more</strong> &#8211; To clean those emerging Code Patterns until they tell their story of structure and approach loud and clear each time you encounter them in your code.</li>
</ol>
</ol>
<h2>Why should you study Design Patterns?</h2>
<p>I believe studying Design Patterns &#8211; WITH CLEAN CODE THROUGH REFACTORING AS YOUR MAIN FOCUS &#8211; help you become a better coder.</p>
<ol>
<li><strong>Existing solutions for recurring issues</strong> &#8211; The existing Design Patterns show you which recurring issues have been identified in code project and how they have been addressed. Once you start understanding the issue they try to solve and how they solve that issue, they become your friends. Either to avoid them like hell, or to implement them in an early stage as they offer the best structure you can find.</li>
<li><strong>Avoiding stupid mistakes</strong> &#8211; If you use Design Patterns without understanding them properly, you will create a mess and achieve the inverse of what you should strive fore: clean code.</li>
</ol>
<h2>If you don&#8217;t get it, don&#8217;t use it (yet)</h2>
<div>In general, if you don&#8217;t get it, don&#8217;t use it (yet). It will work against you. With design patterns this is even more the case.</div>
<h2>How to get to that understanding fast?</h2>
<ol>
<li><strong>Read</strong> &#8211; Read all references you can find</li>
<li><strong>Understand</strong> &#8211; Make drawings, reflect the stuff you read on the work you do</li>
<li><strong>Refactor</strong> &#8211; Refactoring your code (cleaning up) is the best way. Force yourself to think and work in certain ways. It is how design patterns are discovered.</li>
</ol>
<h2>What Design Patterns do not deliver</h2>
<div>In contrary to popular belief, Design Patterns (as the primary focus and driver) do not deliver:</div>
<div>
<ol>
<li><strong>Better code (NOT)</strong> &#8211; As it is easy to misunderstand Design Patterns, it is easy to apply them at the wrong place. The result of this is in most cases messy code.</li>
<li><strong>Better project structures (NOT)</strong> &#8211; Design Patterns are close-up (micro) solutions. They show you a very specific solution for a very specific problem. None of the books I know on Design Patterns show you how to build and organize an entire project with 30 to 500 separate classes.</li>
<li><strong>A project that can be understood by others (NOT)</strong> &#8211; When design patterns are implemented by messy coders, the result is messy code and a messy project.</li>
</ol>
<p>Here is why:</p>
<ol>
<li><strong>Lack of understanding</strong> &#8211; Most coders do not understand Design Patterns.</li>
<li><strong>Limited understanding</strong> &#8211; Most coders who do understand Design Patterns only have a limited understanding of design patterns, based on a previous (set of) project(s).</li>
<li><strong>Wrong understanding</strong> &#8211; As most coders learn by doing, the first implementations and understanding of Design Patterns &#8220;because we have to&#8221; will be wrong.</li>
</ol>
<h2>When you do Design Patterns, but do not clean up</h2>
<p>In the past five years I have been fixing other peoples code in projects that went wrong. These were the things I found:</p>
<ol>
<li><strong>Messy code</strong> - Like: a real complete mess. Duplications of code, vulnerabilities leading to cascades of failures as time progressed and things changed, working night shifts to meet deadlines, rewriting entire blocks of code out of endless failures to make the existing mess work properly and loss of valuable time.</li>
<li><strong>Wrong interpretation of design patterns</strong> &#8211; Leading to even more mess than working entirely without any design patterns.</li>
<li><strong>Wrong design patterns in the wrong place</strong> - You can force round pegs into square holes, but something will get damaged. In code, wrong design patterns in the wrong place leads to code overhead and obfuscation of purpose. Where you might have been able to solve the issue with 5 lines of code, the compulsive use of &#8220;a design pattern&#8221; or &#8211; even worse &#8211; &#8220;Design pattern X, Y and Z&#8221; can lead to 3 or more classes and 20 to 150 added lines of code.</li>
</ol>
<h2>Why I keep hammering on Refactoring and Clean Code</h2>
<p>In the past 14 months I have been working on a big Flex project for a big scientific publisher, involving a team of 15 to 20 people. The base architecture and the base classes driving that application and used by others as stepping stones were designed and written by me. The demands on both back and front end led to a design where a lot of rules were &#8220;broken&#8221; to avoid overload on the Servers as each request from Client to Server involved queries on over 200 million records, with over 30 possible combinations per record (leading to over 6 billion possible combinations to be queried per request).</p>
<ol>
<li><strong>Clean code and Clear Structure is more important than anything else</strong> &#8211; If your code is messy, nobody understands what is going on. If your most important actions are performed in some obscure classes hidden in obscure packages in your structure and mixed with other activities for other parts, nobody will be able to find them or what is going on where. If nobody understands what is going on, the mess will only become bigger</li>
<li><strong>Cleaning up code on regular basis is more important than anything else</strong> &#8211; Regardless of what your design process is and how awesome your architecture looks on paper, there will always be coders in your team who have limited experience and limited understanding of what you are trying to achieve. Leading to additional mess in your code, by doing stuff in places they should not work.</li>
<li><strong>Design Patterns emerge</strong> &#8211; I can not keep repeating this enough. Especially because I have met people who hammer on the use of <em><strong>Design Patterns as a starting point in the design</strong></em> (because they read the book, believe in the holiness of it, or are used to work in that specific way). Design Patterns emerge. Period.</li>
<li><strong>Change occurs, so which Design Patterns is best to solve a problem changes too</strong> &#8211; As the solution itself might change as time progresses. Where State Pattern might be good at first sight, Mediator might be the only way forward to keep it simple and sane. Or vice versa.</li>
</ol>
<h2>What is next?</h2>
<div>In the next blogs I will look at several design patterns, using a specific approach to try and make sense out of them:</div>
<div>
<ol>
<li><strong>Scope</strong> &#8211; What do each cover? What not?</li>
<li><strong>Use</strong> &#8211; When to use them? What for?</li>
<li><strong>Clarification</strong> - What makes that pattern that pattern? When does it stop to be that pattern?</li>
<li><strong>Differences and similarities</strong> &#8211; What patterns solve similar issues, what makes them different and what are the benefits of each chosen solution?</li>
<li><strong>Smarter approach </strong>- Some patterns can be coded in a different way than most if not all code examples show, adding more flexibility and reducing code and dependencies</li>
</ol>
<div>I assume you read and refer to two books at least: &#8220;Design Patterns&#8221; and &#8220;Design Patterns for Dummies&#8221; to fill in the gaps I leave open and keep your independence, as others already wrote about it and I might make mistakes in my understanding at this time.</div>
</div>
</div>
</div>
</div>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/flashworks.wordpress.com/743/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/flashworks.wordpress.com/743/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/flashworks.wordpress.com/743/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/flashworks.wordpress.com/743/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/flashworks.wordpress.com/743/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/flashworks.wordpress.com/743/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/flashworks.wordpress.com/743/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/flashworks.wordpress.com/743/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/flashworks.wordpress.com/743/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/flashworks.wordpress.com/743/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/flashworks.wordpress.com/743/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/flashworks.wordpress.com/743/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/flashworks.wordpress.com/743/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/flashworks.wordpress.com/743/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=flashworks.wordpress.com&amp;blog=7295152&amp;post=743&amp;subd=flashworks&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://flashworks.wordpress.com/2011/07/30/design-patterns-an-introduction/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/cffc2ff7b980a5f5f76c22bddba4f361?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">peter kaptein</media:title>
		</media:content>
	</item>
		<item>
		<title>Self-managing objects &#8211; To support Agile development processes</title>
		<link>http://flashworks.wordpress.com/2011/07/08/self-managing-objects-to-support-agile-development-processes/</link>
		<comments>http://flashworks.wordpress.com/2011/07/08/self-managing-objects-to-support-agile-development-processes/#comments</comments>
		<pubDate>Fri, 08 Jul 2011 11:53:38 +0000</pubDate>
		<dc:creator>Peter Kaptein</dc:creator>
				<category><![CDATA[Design patterns]]></category>

		<guid isPermaLink="false">http://flashworks.wordpress.com/?p=739</guid>
		<description><![CDATA[The main issue: avoiding entanglement of dependencies When you build software, at a certain point you will start building (managed) lists of objects. You might even have one or more managers taking care of this. For instance: Person &#8211; Is a Value Object (VO) containing a person. PeopleManager &#8211; Is a manager containing a List [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=flashworks.wordpress.com&amp;blog=7295152&amp;post=739&amp;subd=flashworks&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<h2>The main issue: avoiding entanglement of dependencies</h2>
<p>When you build software, at a certain point you will start building (managed) lists of objects.</p>
<p>You might even have one or more managers taking care of this.</p>
<p>For instance:</p>
<ol>
<li><strong>Person</strong> &#8211; Is a Value Object (VO) containing a person.</li>
<li><strong>PeopleManager</strong> &#8211; Is a manager containing a List of people (List&lt;People&gt; in C#)</li>
</ol>
<p>So far nothing is wrong as there are two clearly paired Classes.</p>
<p>But what if you create a third object called &#8220;Department&#8221; with a manager?</p>
<ol>
<li><strong>Department</strong> &#8211; Contains a list of people (List&lt;People&gt;)</li>
<li><strong>DepartmentManager</strong> &#8211; Contains methods to find out which person is in what department</li>
</ol>
<div>So far, again nothing seems really wrong.</div>
<h2><em>Here comes the catch</em></h2>
<p>What if you remove/delete a person?</p>
<p>Since you now have two lists with people (in PeopleManager and Department) you will have to remove that person from two places. And this is only a simple example.</p>
<h2><em>What we can learn from data models</em></h2>
<p>When you create a database, the database data model deals in a different way with dependencies than we are used in Object Oriented Programming (OOP).</p>
<p>The main reason is to keep data management simple and prevent data from becoming inconsistent.</p>
<p>If there is a One to Many relationship between Department and Person, the link is created in Person, by adding a departmentID. Department will not have a list of people, but will query Person to see who is referring to its ID. (query=&#8221;SELECT * FROM person WHERE departmentID = &#8220;+ this.departmentID)</p>
<p>In OO (Object Oriented) environments, it might be tempting to insert the Department Object into a person, but again management of data consistancy might become troublesome. My preference is to refer to a Department via a String or Integer value.</p>
<h2><em>Review</em></h2>
<ol>
<li>We add a department of type Department to the person: <em><strong>person.<span style="color:#0000ff;">department</span></strong></em></li>
<li><span style="color:#000000;">We add a (static) method to PeopleManager: <em><strong>List&lt;People&gt; getPeopleInDepartment(Department department)</strong></em></span></li>
<ol>
<li><span style="color:#000000;">This (static) method will go through the People list and extract all people in the Department.</span></li>
</ol>
</ol>
<p>All management regarding people will be done in PeopleManager.</p>
<p>This might seem counter-intuitive. But once you start refactoring, distributed dependencies to specific data and objects will start to break you up.</p>
<h2>The goal: simplifying your project</h2>
<p>I have noticed that the most common models for events only work for small projects. The moment you start something big, these models become a problem.</p>
<ol>
<li><strong>Boilerplate code</strong> &#8211; They force you to create a lot of boiler plate code, just to make it work within that (limited and usually rigid) model</li>
<li><strong>Loss of control</strong> &#8211; When your project grows, it becomes less and less clear what happens where and why specific updates you KNOW happened in some object are not reflected elsewhere.</li>
</ol>
<h2>Events</h2>
<p>Another issue with the classic approach are Events.</p>
<p>When I update an object somewhere, and this information is required elsewhere, I usually shoutcast an Event: &#8220;My object has been updated!&#8221;. Attached to the event is the object or object list I changed.</p>
<p>With persistant Objects I can simplify the Event Model thoroughly.</p>
<p>Take this example:</p>
<pre><span style="color:#008000;">// Some code on Class "A"</span>
Person myPerson = Person.getPerson(12);
<span style="color:#008000;">// Add observer that will take action when this specific person </span>
<span style="color:#008000;">// is updated. For instance: when presented in a list</span>
myPerson.<span style="color:#ff0000;">addUpdateObserver</span>(myUpdateHandler)

<span style="color:#008000;">// Some code in class "B"</span>
Person myPerson = Person.getPerson(12);
<span style="color:#008000;">// Change some values</span>
myPerson.firstName="Joe";
myPerson.<span style="color:#ff0000;">dispatchUpdateEvent</span>();</pre>
<p>All observers on Person with ID 12 will now automatically receive a dispatched event and will be able to take action.</p>
<p>As you also might want to observe global events on Person, it is not too hard to create a global, static Event Dispatcher on Person. So when a global observer is attached to the Person Class, that observer will also be informed of any change.</p>
<pre><span style="color:#008000;">// Using a global event listener</span>
Person.<span style="color:#ff0000;">add<strong>Global</strong>UpdateObserver</span>(myGlobalPersonUpdateHandler)</pre>
<p>All events are created behind the scenes and can be default events, dispatched over local Dispatchers. This way, the dispatched events never leave the scope of the Object or Class. Naturally all observers are registered against the local Dispatcher as well.</p>
<h2>Moving it one step further: cutting all dependencies</h2>
<p>You probably know the concept of multitons and Object Pools.</p>
<p>Multitons and Objects in Object Pools are objects with a specific ID or state, addressed through a static method.</p>
<p>For instance on ID:</p>
<pre>string personID=12;
<span style="color:#008000;">// Get the person</span>
Person person = Person.getPerson(personID)</pre>
<p>Or state:</p>
<pre>List&lt;Person&gt; people = Person.getDeletedPeople(); 
<span style="color:#008000;">// Where getDeletedPeople will return the objects in the pool flagged as "deleted".</span></pre>
<p>What we do is get an instance of a specific Person object and put it in a temporary variable.</p>
<p>Regardless where we are in our project, when we call for a person with ID 12, we will always get the same object.</p>
<h2><em>Lookup tables</em></h2>
<p>The main trick is to register objects against a Lookup Table. For a Person that Lookup table might be indexed against the Person ID. For a Deaprtment, that might be a Department ID.</p>
<pre><span style="color:#008000;">// A C# lookup table</span>
Dictionary&lt;int, Person&gt; peopleList = new Dictionary&lt;int, Person&gt;();
<span style="color:#008000;">// Getting a person</span>
public Person getPerson(int personID)
{
<span style="color:#008000;">     // For simplicity sake we left out the check if the person is really there</span>
     return peopleList[personID]
}</pre>
<p>If you want to find a list of people in a Department, you can do the following:</p>
<pre><span style="color:#008000;">// Getting people in a department</span>
public List&lt;People&gt; getPeopleInDepartment(Department department)
{
      List&lt;People&gt; <span style="color:#ff0000;">peopleInDepartment</span> = new List&lt;People&gt;();
      <span style="color:#008000;">// Loop through all people</span>
      foreach (Person person in peopleList)
      {
           if(person.department == department)
           {
                   <span style="color:#ff0000;">peopleInDepartment</span>.Add(person);
            }
    }
    return <span style="color:#ff0000;">peopleInDepartment</span>;
}</pre>
<h2><em>Benefits</em></h2>
<ol>
<li><strong>Dependencies to objects are temporary</strong> &#8211; You are not maintaining persistent references to multiple objects on multiple places.</li>
<li><strong>Garbage collection is more reliable </strong>- As your persistant references are only on one place: the Class or Class Manager, releasing references only have to be done at one place.</li>
<li><strong>Simplified code</strong> &#8211; I found that at a certain point I was shipping shitloads of object references through all kind of chains of objects and method calls, to have it end up at the right place. Currently the only thing I ship are String and Int values representing the ID of an object. And in most cases If a store and object in class &#8220;A&#8221; and need to retrieve it in class &#8220;C&#8221;, I simply use a specific static method on the Class itself: &#8220;<em><strong>someClass.getObjectListBasedOnSomeParameters(parameterA, parameterB)</strong></em>&#8220;</li>
<li><strong>Increase in application stability</strong> &#8211; As your maintenance of objects is done centrally and managed in one object, strange stuff and lost objects are less likely to happen</li>
<li><strong>Increase in code stability when refactoring</strong> &#8211; Another reason for me to drop the classic approach was that my code tended to break a lot when refactoring. While the compiler had all flags on green, parts of my application simply did not work anymore due to some broken dependency.</li>
</ol>
<h2><em>Disadvantages</em></h2>
<ol>
<li><strong>Performance</strong> &#8211; The main disadvantage of lookup tables is performance. Each time you loop, you pay.</li>
</ol>
<h2>Concluding</h2>
<p>From OOP principles it might seem counter-intuitive to manage Objects in the Objects themselves (or in a specific and paired Object Manager) and only use temporary references.</p>
<p>The advantages of lookup tables and centralized/localized object management become clear and increasingly bigger when:</p>
<ol>
<li><strong>You do a lot of refactoring</strong> &#8211; As you will take apart your code, move parts elsewhere and so on.</li>
<li><strong>Your project becomes increasingly complex</strong> &#8211; Querying objects where you need them becomes more beneficial than sending lists of objects from somewhere and hoping that the right lists arrive at the right place though chains of objects and method calls.</li>
<li><strong>You use persistent data and persistent objects</strong> &#8211; As any and multiple objects can contain &#8220;Joe Bloggs, ID =2&#8243;, using centralized lookup lists and object management assures that when you update &#8220;Joe Bloggs, ID=2&#8243; ALL objects representing &#8220;Joe Bbloggs, ID = 2&#8243; are updated.</li>
<li><strong>Your event model starts to work against you</strong> &#8211; Events are usually linked to objects. The more granular your event model becomers, the more event types you will have to maintain to keep things up to date and the more bloated your code becomes. The event: PersonEvent(&#8220;A person has been updated&#8221;) with the specific object attached is less clear than person.dispatchUpdatedEvent(); where only all specific listeners to that object and that class will receive that event dispatch.</li>
</ol>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/flashworks.wordpress.com/739/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/flashworks.wordpress.com/739/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/flashworks.wordpress.com/739/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/flashworks.wordpress.com/739/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/flashworks.wordpress.com/739/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/flashworks.wordpress.com/739/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/flashworks.wordpress.com/739/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/flashworks.wordpress.com/739/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/flashworks.wordpress.com/739/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/flashworks.wordpress.com/739/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/flashworks.wordpress.com/739/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/flashworks.wordpress.com/739/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/flashworks.wordpress.com/739/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/flashworks.wordpress.com/739/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=flashworks.wordpress.com&amp;blog=7295152&amp;post=739&amp;subd=flashworks&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://flashworks.wordpress.com/2011/07/08/self-managing-objects-to-support-agile-development-processes/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/cffc2ff7b980a5f5f76c22bddba4f361?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">peter kaptein</media:title>
		</media:content>
	</item>
		<item>
		<title>Refactoring: When, what and where?</title>
		<link>http://flashworks.wordpress.com/2011/07/07/refactoring-when-what-and-where/</link>
		<comments>http://flashworks.wordpress.com/2011/07/07/refactoring-when-what-and-where/#comments</comments>
		<pubDate>Thu, 07 Jul 2011 18:28:58 +0000</pubDate>
		<dc:creator>Peter Kaptein</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://flashworks.wordpress.com/?p=726</guid>
		<description><![CDATA[The basis of refactoring Refactoring or Core Refactoring is a process in which code and the organization of code and classes are restructured, to: Increase clarity &#8211; As a project grows, code can become more and more messy, as chosen paths changes and solutions that once were sufficient had to be expanded or changed as [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=flashworks.wordpress.com&amp;blog=7295152&amp;post=726&amp;subd=flashworks&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<h2>The basis of refactoring</h2>
<p>Refactoring or Core Refactoring is a process in which code and the organization of code and classes are restructured, to:</p>
<ol>
<li><strong>Increase clarity</strong> &#8211; As a project grows, code can become more and more messy, as chosen paths changes and solutions that once were sufficient had to be expanded or changed as a whole.</li>
<li><strong>Remove redundancy</strong> &#8211; Like checks and double checks on specific values, or repetition of code.</li>
<li><strong>Remove dead code</strong> &#8211; During the process of change, dead code will remain. In general dead code is code not removed &#8220;because it might become useful someday&#8221; or &#8220;because we do not know what it does exactly&#8221;</li>
<li><strong>Reduce complexity</strong> &#8211; Sometimes a specific solution seems to be the best at that time, but in time grows into a Kafka-eske structure of over-complication.</li>
<li><strong>Assure application stability</strong> &#8211; Unclear processes, redundant code, dead code and unneeded complexity lead to an increase of potential places where the code can fail.</li>
</ol>
<h2>Not only for Agile</h2>
<div>While refactoring is an important part of Extreme Programing and Agile, it is not limited to those approaches. Any process that results on code should involve periods of clean up.</div>
<h2>Why and when code becomes messy</h2>
<p>There are several reasons. I will try to list a complete list of the most common reasons here:</p>
<ol>
<li><strong>More than one person is involved</strong> &#8211; As soon as two or more codes are working on the same code base, different approaches will be introduced to solve a problem, name variables and using design patterns. Each will lead to increasingly messy code.</li>
<li><strong>Requirements change</strong> &#8211; With each functional change, code has to change. And usually changes on several places. Each change introduces small pieces of messy code, which &#8211; if not cleaned up from time to time &#8211; leads to messy code.</li>
<li><strong>Understanding of requirements change</strong> &#8211; As your understanding of requirements grow, it might be that your initial approach is not covering it and needs to be revised or even completely redone. The size and impact of the changes also determines the size of the mess left behind.</li>
<li><strong>Requirements are misunderstood</strong> &#8211; See: &#8220;understaning of requirements change&#8221;. The impact of the code changes when requirements change is usually deep. usually existing code is re-used or bent into the new direction, as that seems a more sane solution at that point than simply throwing the old code away.</li>
<li><strong>Code for another purpose is re-used for something else</strong> &#8211; See: &#8220;Requirements are misunderstood&#8221;. When starting it seems logical to use &#8220;A&#8221; for &#8220;B&#8221; as they follow similar processes and re-use is preferred before starting from scratch. This usually leads to messy code.</li>
<li><strong>Bug fixes and patches are stacked onto bug fixes and patches</strong> &#8211; As fixes continue, they will overlap other fixes and patches. Introducing more mess</li>
<li><strong>Programmers have no clue what they are doing</strong> &#8211; Proper and clean coding takes experience. Understanding OOP takes even more time and experience. In most cases, coders do what they can do to solve a problem to their best knowledge. This can lead to a lot of messy code that HAS to be refactored.</li>
<li><strong>Refactoring is postponed indefinitely due to fear or lazyness</strong> &#8211; The fear can be : &#8220;If we refactor now, we might not make the deadline&#8221;. Lazyness can be: &#8220;I want to finish this and will fix the mess some day later&#8221;.</li>
</ol>
<h2>The negative impact of refactoring</h2>
<p>Refactoring hase some negative impacts for the short term:</p>
<ol>
<li><strong>It blocks progress</strong> &#8211; As long as code is refactored, no new things can be done. Everyone who is not refactoring has to wait until refactoring (on their part) is done.</li>
<li><strong>It breaks the project</strong> &#8211; During the process of refactoring, the code and the project is broken as things are moved around and exctracted and replaced into other parts of the code.</li>
<li><strong>It takes time</strong> &#8211; A refactoring can take from 3 hours to 3 days and 3 weeks. During that period, no progress is made, except from the code being cleaned up.</li>
<li><strong>It can impact negatively on the deadline</strong> &#8211; As it takes time to refactor, a deadline might be missed due to it.</li>
</ol>
<h2>The negative impact of <span style="text-decoration:underline;">not</span> refactoring</h2>
<ol>
<li><strong>Code becomes increasingly messy</strong> &#8211; To the point where it is no longer maintainable.</li>
<li><strong>Code becomes increasingly overly complicated</strong> &#8211; Due to entanglements of dependencies that should not be there. Straight lines become messy and wobbly. Processes that can be handled in three steps in one or two classes are done in five ore more, over three or more objects.</li>
<li><strong>More and more strange bugs and strange behavior are introduced</strong> &#8211; As code becomes more messy, it becomes more and more unclear who does what and what happens where.</li>
<li><strong>Bugs that were solved start re-appearing over and over</strong> &#8211; More mess means it is easier to lose stuff and undo stuff that was fixed for specific situations as it is unclear what it does and what it is meant to do.</li>
<li><strong>Changes and change request take more and mote time</strong> &#8211; Due to the increased complexity and increased entanglement of dependecies in the messy code.</li>
</ol>
<h2>Why you MUST clean up messy code</h2>
<ol>
<li><strong>On the long run messy code jeopardises your project</strong> &#8211; The more mess, the more entanglements of dependencies, the more steps needed to fulfill a process, the bigger the chance your code will work against you by:</li>
<ol>
<li><strong>Breaking down on you</strong> &#8211; Due to bugs and strange side effects of messy code</li>
<li><strong>Halting progess</strong> &#8211; Due to the increased amount of time it takes to find and implement a solution</li>
<li><strong>Blocking any new development</strong> &#8211; As the old code has become so big and messy that any big change will break the entire project</li>
</ol>
<li><strong>Messy code slows down progress</strong> &#8211; Imagine a house full of boxes you have to move aside every time you want to move from &#8220;A&#8221; to &#8220;B&#8221;. That is what coding in messy code is like. The more mess, the more time you will waste just dealing with that mess.</li>
<li><strong>Messy code becomes unmanageable </strong>- Any change, any improvement, any new person joining the team will have increased costs, to the point where that cost is larger than the benefits.</li>
<li><strong>Messy code creates (unwanted) dependencies on a specific set of people</strong> &#8211; If &#8220;A&#8221;, &#8220;B&#8221; and &#8220;C&#8221; are the only ones understanding what is going on inside the code, the project becomes dependent of them. Clean code makes people replaceable as clean code is easier to understand by others. This is mostly crucial when people will be bound to a project for only a limited time, or people leave for another job at another company.</li>
</ol>
<h2>When to refactor</h2>
<div>There is no real rule. I use the following four indicators:</div>
<div>
<ol>
<li><strong>When the direction of my solution changes</strong> &#8211; Say I was moving towards solution &#8220;A&#8221; but halfway through discover that &#8220;B&#8221; is actually better or what the requirements ask from me.</li>
<li><strong>When stuff is happening in the wrong places</strong> &#8211; Say we have a handler for incoming calls. And we have a book of rules stating which calls to redirect to what person. Originally it seems logical to have all this in one place. The part that deals with the incoming calls also deals with the rules. But at a certain point, other parts also need access and start using the same Class that handles incoming calls. &#8220;IncomingCalls&#8221; suddenly has become &#8220;IncomingCallsAndRulesToDistributeIncomingCalls&#8221;. Clearly time to separate the responsibilities.</li>
<li><strong>When code becomes messy/if I no longer understand what is going on</strong> - Usually due to rows and rows of &#8220;if/then/else&#8221; based on specific rules, situations and exceptions. In most cases, the responsibility of this decision making is delegated to other places and specific classes are created to deal with this. I started applying a principle I called separation of responsibility to deal with this and defined five base type of classes to deal with specific tasks. Read more about that <a href="http://daymoframework.wordpress.com/2010/07/01/the-daymo-approach-to-model-view-controller/">here</a> on the Daymo Approach to MVC. Scroll down to find the section on: &#8220;Separation of responsibilities&#8221;.</li>
<li><strong>When debugging a relatively simple issue or implementing a change takes too much time</strong> &#8211; It should be like tooth brushing: you pick up the brush, put some tooth paste on it and start brushing away the errors. Unless you first have to do a lot of other things first, every time you even want to find that brush and your tooth paste. Things shoulod be clear, easy to find and easy to change. Even &#8211; and certainly! &#8211; when the project becomes increasingly complex.</li>
</ol>
<h2>What I gain from refactoring</h2>
<div>
<ol>
<li><strong>Clean, clear code</strong> &#8211; The difference of my code before and after refactoring is sometimes like night and day. Where the old code can be like heaps of crumpled paper &#8211; including junk mail from my post box &#8211; where each part might or might not be related and relevant, the new code strives to more like straight sheets of paper organized in logical stacks on a clean surface: where all waste is disposed of.</li>
<li><strong>Agility and increased speed of working</strong> &#8211; In the sense of: If I want to change direction now, I can do so. All parts are neatly compartmentalized. If I change parts, it will not break my project. If I want to move stuff around, in radical ways, I can do so in a matter of minutes or hours. My code does not block me. Clutter in my code does not block me.</li>
<li><strong>Less code and less bugs in the code</strong> &#8211; Messy code also introduces a lot of redundant code. Less code means that things go wrong on fewer places.</li>
<li><strong>Increased stability</strong> &#8211; Messy code can lead to messy and unpredictable results. Clean code is predictable. The cleaner the code, the more predictable the results. Even when major changes are made, as everything has a clear place and a clear purpose and when disconnected and re-connected will not crash due to entanglement of dependencies that should not be there.</li>
<li><strong>Easier to understand by other people</strong> &#8211; As I work on some projects that have (Reed Elsevier in 2010 and 2011) and will involve (HotForestGreen, the Flash RAD framework) other people, clean code is almost a MUST.</li>
</ol>
<h2>Limiting factors</h2>
<div>
<ol>
<li><strong>Deadlines</strong> &#8211; Deadlines are the biggest factor limiting your refactoring efforts. If you have to deliver tomorrow, you will not do a last minute thorough refactoring. You will do what is possible without endangering the project.</li>
<li><strong>Coding environment</strong> &#8211; Tools with limited support allow only limited type of refactorings. Tools with a very rich support allow you to unleash the Refactoring Beast. Eclipse (and the coding tools built with and on Eclipse) is quite good. Refactoring, Java and Eclipse seem to be invented for each other. Moving from AS3 projects in FDT (which is quite good), Flex3 (which is horrid), Flex4 (which improved a lot) and Visual Studio 2010 (which did not impress me much) the tools make a huge difference in how far, how deep, how drastic and how thorough you can be in moving stuff around. Another view on refactoring I use &#8211; thanks to FDT and Eclipse &#8211; is: &#8220;breaking the code in a smart way, moving stuff around and fix all broken parts again until it works again&#8221;. Good tools help you by telling you immediately what is broken, the moment you break it and by offering full support when you move and rename parts. On the other side of this spectrum is TextPad, with no understanding at all and where you &#8211; as a person &#8211; have to go through all your code manually. Until it stops giving you compiler errors.</li>
</ol>
</div>
<h2>Simplicity &#8211; And frameworks that do not really solve a problem</h2>
<p>I have ranted about frameworks that introduce and promote specific approaches like Injection of Dependency (Swiz, RobotLegs, Mate for ActionScript, Spring for Java).</p>
<p>As they do help you to work faster within a specific context, they &#8211; in contrary what they claim in most cases &#8211; are not a solution for maintainable code.</p>
<p>Maintainable code is made by people. As people also produce a complete unmanageable mess.</p>
<h2>Boilerplate code</h2>
<p>Some approaches lead to extra code and the addition of extra classes, because it is part of the approach, or because they are required to make it work with that framework.</p>
<p>This code is called boilerplate code.</p>
<p>If your project explodes into an increase of a lot of additional classes: &#8220;because you need them within that framework&#8221;, the question is if you are doing the right thing and using the right approach.</p>
<p>Maintainable code is mainly:</p>
<ol>
<li>Clear</li>
<li>Short</li>
<li>Simple</li>
<li>Without redundancy</li>
</ol>
</div>
<h2>Abusing design patterns and &#8220;best practices&#8221;</h2>
<p>Design patterns are what evolves from your initial coding. And usually your code project is a mix. See again <a href="http://daymoframework.wordpress.com/2010/07/01/the-daymo-approach-to-model-view-controller/">this post</a>: where I explore the different approaches of MVC from &#8220;The Daymo point of view&#8221;.</p>
<p>There is not one approach to solve all problems and sometimes, by trying to force everything into specific design patterns you achieve the exact opposite of what you want to achieve: code that is maintainable by yourself and others.</p>
<p><strong>Some examples:</strong></p>
<ol>
<li><strong>Throwing exceptions is not a solution for every unhandled situation</strong> - If something happens in your application that is not supposed to happen, the main question is not: what exception shall we throw? But: &#8220;Do we really need to put our responsibility to solve this somewhere else?&#8221; Sometimes an exception can be solved locally by coding in alternative strategies or returning empty data sets or a status object as part of a &#8220;soft failure&#8221;: telling the caller something went wrong and he or she needs to do a retry later on.</li>
<li><strong>MVC is not the answer for everything</strong> &#8211; MVC might seem cool once you get the hang of it, but it is a very limited model for a very limited use: to separate presentation logic (your View) from the logic that deals with your data and business logic (Model) and the part that deals with user input (your Controller).</li>
<li><strong>Events are not your binding glue for all things that happen within your applications</strong> &#8211; Events have a limited use and should be carefully used. Events are mainly shout-casts accross your application. Someone shouts: &#8220;Something has happened&#8221; and others can respond to that. But when all your processes depend on events, unexpected things can start happening, as they can be fired from anywhere and do not have centralized business logic dealing with specific exceptions and situations. Another issue is: &#8220;Who is referencing what via what Event?&#8221; Since Events do not have strong binding or references to your Classes, it is hard to find out who is referencing what as well.</li>
<li><strong>Sometimes a design patterns simply sucks for what you really need</strong> &#8211; As said, design patterns usually emerge when coding. What might start as &#8220;A&#8221; might slowly move towards &#8220;B&#8221; because &#8220;B&#8221; is simpler and more suited and effective. Trying to stick to specific patterns: &#8220;because it is according to the book&#8221; is usually only introducing more complexity in a &#8211; vary likely &#8211; already overly complex project.</li>
</ol>
<h2>Concluding</h2>
<p>Above and beyond any design pattern or development method: &#8220;from the book&#8221; is refactoring.</p>
<p>Good code &#8211; in my book &#8211; is code that is:</p>
<div>
<ol>
<li><strong>Clear</strong> &#8211; In structure, naming of classes, methods and variables, purpose and rule sets applied and in separation of responsibilities or: &#8220;Who does what&#8221;?</li>
<li><strong>Clean</strong> &#8211; No redundancy, no dead code, no over complexity, no mess.</li>
<li><strong>Well structured</strong> &#8211; Regardless and apart from any Design Pattern that might be applied.</li>
</ol>
<p>Any project with people who think code is &#8220;good&#8221;: &#8220;because specific principles are used&#8221; but which is an internal mess due to everything it is not according to my list of three (clear, clean, well structured) will automatically raise a lot of resistance in me. And my first intention is to walk away from such projects.</p>
<p>I did not in the past five years as I needed the money.</p>
<p>I have seen a lot of bullshit code due to that under the pretense of: &#8220;proper coding&#8221; or: &#8220;use of standards&#8221;. And I have cleaned up a lot of mess.</p>
<p>It has made me very wary of any &#8220;framework&#8221; including some stuff in Flex that does not solve a clear problem like: &#8220;Reading QR codes&#8221; or &#8220;Converting bitmaps to JPG&#8221; or &#8220;Connecting to a Server via binary sockets over port 80&#8243;. I really have to practice a lot of patience when my questions and input on: &#8220;proper coding principles&#8221; are continuously understood by the other side as &#8220;using this awesome framework that is the new shit&#8221;.</p>
<p>It also made me grow as a coder.</p>
<p>In 2008 I knew absolutely nothing about design patterns. MVC, mediators, factories, proxies and the concept of observer patterns would completely confuse me. Partly because the examples made no sense, partly due to my own ignorance and in some cases because the people showing me those examples had no fucking clue what they were talking about.</p>
<p>The move to AS3 and my work on cleaning up other peoples mess gave me the head start to grow into this. And I am thankful for that.</p>
<p>As said: claer, clean, well structured code is king above all else.</p>
<p>Refactoring is the only tool to get there: by rewriting and cleaning up what does not work.</p>
</div>
</div>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/flashworks.wordpress.com/726/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/flashworks.wordpress.com/726/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/flashworks.wordpress.com/726/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/flashworks.wordpress.com/726/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/flashworks.wordpress.com/726/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/flashworks.wordpress.com/726/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/flashworks.wordpress.com/726/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/flashworks.wordpress.com/726/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/flashworks.wordpress.com/726/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/flashworks.wordpress.com/726/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/flashworks.wordpress.com/726/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/flashworks.wordpress.com/726/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/flashworks.wordpress.com/726/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/flashworks.wordpress.com/726/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=flashworks.wordpress.com&amp;blog=7295152&amp;post=726&amp;subd=flashworks&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://flashworks.wordpress.com/2011/07/07/refactoring-when-what-and-where/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/cffc2ff7b980a5f5f76c22bddba4f361?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">peter kaptein</media:title>
		</media:content>
	</item>
		<item>
		<title>Breaking Object Dependencies via String References, static variables and Dictionaries</title>
		<link>http://flashworks.wordpress.com/2011/04/14/breaking-object-dependencies-via-string-references-static-variables-and-dictionaries/</link>
		<comments>http://flashworks.wordpress.com/2011/04/14/breaking-object-dependencies-via-string-references-static-variables-and-dictionaries/#comments</comments>
		<pubDate>Thu, 14 Apr 2011 14:39:55 +0000</pubDate>
		<dc:creator>Peter Kaptein</dc:creator>
				<category><![CDATA[Design patterns]]></category>
		<category><![CDATA[Flash RAD Framework]]></category>
		<category><![CDATA[Mandarine]]></category>

		<guid isPermaLink="false">http://flashworks.wordpress.com/?p=701</guid>
		<description><![CDATA[When you run a project with many objects clustering and cross-referring, the trick is to keep it simple, to avoid a complex mess of objects and object references. Here is the base-list of what I started doing for just such a project in Flex in the past year: Define the main identifiers &#8211; Preferably as [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=flashworks.wordpress.com&amp;blog=7295152&amp;post=701&amp;subd=flashworks&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>When you run a project with many objects clustering and cross-referring, the trick is to keep it simple, to avoid a complex mess of objects and object references.</p>
<p>Here is the base-list of what I started doing for just such a project in Flex in the past year:</p>
<ol>
<li><strong>Define the main identifiers</strong> &#8211; Preferably as String values</li>
<li><strong>Create a unique key using these identifiers</strong> &#8211; Preferably by concatenating, to avoid boilerplate code</li>
<li><strong>Register each of your objects in a Static Dictionary within that class</strong> &#8211; To allow for direct access using the key</li>
</ol>
<h2>What do you normally do?</h2>
<p>When you want to refer to other objects, the classic approach is to either use:</p>
<ol>
<li><strong>Event Listeners and Event Dispatchers</strong> &#8211; Advantage is that you capture and process the even where needed, deal with the data there.</li>
<li><strong>Object references</strong> &#8211; Telling any object that needs to know what the objects are it might want to refer to</li>
</ol>
<h2>What is the problem here?</h2>
<ol>
<li><strong>Event dispatching</strong> &#8211; Disadvantages of dispatching events are many. I mention two.
<ol>
<li><strong>Overhead </strong>- You are broadcasting to a lot of objects who will either ignore the event, or capture the event and discard of it, wasting your resources while doing it.</li>
<li><strong>Who? What? Why?</strong> &#8211; Events can be dispatched from anywhere and the reasons why you received an event are not always clear. Especially when some event dispatch was not cleaned up and is fired when you do not expect that. Also when dispatching it, who will receive it? When you want to see who might respond, you will have to find the places where the event is captured.</li>
</ol>
</li>
<li><strong>Object references</strong> &#8211; Especially when you start to have multiple levels in your code, you will start to have dependencies that are harder and harder to maintain.</li>
</ol>
<h2>What is the goal?</h2>
<p>To create a simplified way to refer to objects from other objects and get things done faster and simpler when you want interactions between objects.</p>
<p>As one of the side-effects, double-binding objects becomes a lot easier: allowing you to do stuff from &#8220;A&#8221; to &#8220;B&#8221; and from &#8220;B&#8221; to &#8220;A&#8221;.</p>
<h2>WTF? Static variables and static methods!?</h2>
<p>We use static variables, Dictionaries to be more specific, to solve this issue. &#8220;Using static variables&#8221; and Static Methods is regarded as suspect coding behavior for the following reasons:</p>
<ol>
<li>When a static variable is changed somewhere, it can fuck up the app somewhere else &#8211; Potentially fucking up Unit Testing as it is unclear who changed what when, when the value of a static variable is suddenly changed</li>
<li>When creating new objects extending the class, static methods are crap &#8211; Potentially fucking up one of the glorious option of OOP: Polymorphism</li>
</ol>
<p>When you look at the code below, you will see that the static variables and methods are used in a different type of way than what is described above. The Design Pattern used is closest to an Object Pool and a Multiton.</p>
<h2>Let&#8217;s get down: Example</h2>
<p>Lets assume:</p>
<ol>
<li>You have a WorldMapChart object you use at least twice in your project.</li>
<li>WorldMapChart 1 is called &#8220;WorldMap1&#8243;, WorldMapChart 2 is called &#8220;WorldMap2&#8243;. We capture that in <strong>mapID</strong></li>
<li>In each of these worldmaps you have County Polygons with datasets stored in: CountryDatasetVO</li>
<li>Each of these countries is represented with an item in a list. We represent countries with a <strong>countryID</strong>.</li>
<li>Each item in the list gets highlighted when you mouse over a country and vice versa</li>
<li>We use <strong>mapID </strong>and <strong>countryID </strong>as our main keys to avoid leaking events to other instances of the world map.</li>
</ol>
<h2>Code example</h2>
<p>We only take one aspect to avoid overloading this post: the Country Dataset Value Object.</p>
<p>The code given only deals with registering the object in a Dictionary and offering a Static method to retrieve a specific VO.</p>
<pre>class CountryDatasetVO
{
   <strong><span style="color:#0000ff;">private </span><span style="color:#ff0000;">static </span>var <span style="color:#ff0000;">countryDictionary</span> <img src='http://s0.wp.com/wp-includes/images/smilies/icon_biggrin.gif' alt=':D' class='wp-smiley' /> ictionary=new Dictionary()</strong>
   private var _<span style="color:#0000ff;">mapID</span>:String;
   private var <span style="color:#0000ff;">_countryID</span>:String;
   public function <span style="color:#0000ff;">CountryDatasetVO</span>(mapID:String):void
   {
       <span style="color:#0000ff;">_mapID</span>=mapID;
   }
   public function <span style="color:#ff0000;">set countryID</span>(id:String):void
   {
      <span style="color:#008000;">// Set country ID</span>
      <span style="color:#0000ff;">_countryID</span>=id;

      <span style="color:#008000;">// Add Country Data Set to mapping</span>
<strong>      var <span style="color:#ff0000;">key</span>:String=<span style="color:#0000ff;">_mapID</span> + "_" + <span style="color:#0000ff;">_countryID</span>;
      <span style="color:#ff0000;">countryDictionary</span>[<span style="color:#ff0000;">key</span>]=<span style="color:#ff0000;">this</span>;
</strong>   }
   public <span style="color:#ff0000;">static </span>function <span style="color:#ff0000;">getCountryDatasetVO</span>(<span style="color:#0000ff;">countryID</span>,<span style="color:#0000ff;">mapID</span>):void
   {
       var <span style="color:#ff0000;">key</span>:String=<span style="color:#0000ff;">mapID + "_" + countryID</span>
       <strong>return <span style="color:#ff0000;">countryDictionary</span>[<span style="color:#ff0000;">key</span>];
</strong>   }
}</pre>
<p>By using a direct call on the class and using the proper keys, we can get any object we want.</p>
<pre>var <span style="color:#ff0000;">countryDatasetVO</span>:<span style="color:#0000ff;">CountryDataSetVO</span>;
<span style="color:#ff0000;">countryDatasetVO </span>= <span style="color:#0000ff;">CountryDataSetVO</span>.<span style="color:#ff0000;">getCountryDatasetVO</span>(<span style="color:#0000ff;">mapID</span>, <span style="color:#0000ff;">countryID</span>)</pre>
<p>Simple as that.</p>
<p>When we are consistent in our classes, each class will at least have the basic keys to refer to any other object via these generic identifiers. And naturally we do everything the exact same way anywhere else. Leaving us with an incredibly simple and solid Object Reference Model across our entire application.</p>
<p>We do not have to worry about nesting objects N levels deep or when and where they are instantiated. We do not have to create extra classes and resolvers for object specific events. As long as we pass our keys and do a check on null values we are going for solid gold.</p>
<pre>if (<span style="color:#ff0000;">countryDatasetVO </span>== null)
{
   <span style="color:#008000;">// the object does not exist, take action or exit here</span>
}</pre>
<h2>Moving it a step further</h2>
<p>Let&#8217;s say that the CountryDataSetVO is updating the view when data is received and lets assume each Country is setup the same way.</p>
<pre><span style="color:#008000;">// In countryDatasetVO</span>
private function <span style="color:#0000ff;">onDataUpdate</span>(e:Event):void
{
   <span style="color:#008000;">// Getting the country polygon</span>
   var <span style="color:#ff0000;">countryPolygon</span>:CountryPolygon;

   <span style="color:#008000;">// As they share the same key values, you can use that</span>
   <span style="color:#ff0000;">countryPolygon</span>=<span style="color:#0000ff;">CountryPolygon</span>.<span style="color:#ff0000;">getCountry</span>(this.<span style="color:#0000ff;">_mapID</span>, this.<span style="color:#0000ff;">_countryID</span>);

   <span style="color:#008000;">// Check if we have contact</span>
   if(<span style="color:#ff0000;">countryPolygon</span>==null)
   {
      <span style="color:#008000;">// No polygon, exit</span>
      return;
   }

   <span style="color:#008000;">// Reflect data</span>
   <span style="color:#ff0000;">countryPolygon</span>.<span style="color:#0000ff;">reflectData</span>(this);

   <span style="color:#008000;">// Also in the list item</span>
   var <span style="color:#ff0000;">countryListItem</span>:<span style="color:#0000ff;">CountryListItem</span>
   <span style="color:#ff0000;">countryListItem</span>=<span style="color:#0000ff;">CountryListItem</span>.<span style="color:#ff0000;">getListItem</span>(this._mapID,this,_countryID)

   <span style="color:#008000;">// as we create the object when not there, we always have result</span>
   <span style="color:#ff0000;">countryListItem</span>.<span style="color:#0000ff;">reflectData</span>(this);
}</pre>
<h2>Moving it even further: BlazeDS</h2>
<p>When you use BlazeDS, objects you send to the Server are not the same as the ones you receive. By using the String References to identify Data Objects you already use in the application, you can easily retrieve the Client Side object it represents and inject the values you received from the Server.</p>
<h2>Result</h2>
<p>As we store object references in the classes they are created with, available in a Static Dictionary and available via a Static Method, the need to pass specific Object References is removed.</p>
<p>We also simplify the application for anyone else who comes after us. When extending the application with new parts, knowing that passing- and using Key Referrer values is all you need to access specific objects is enough to make sense of it.</p>
<p>In the example above we can easily add more items in the onDataUpdate even handler. As we only need the key referrers and the objects we want to refer to resolve the actual object, we have no limits except our needs.</p>
<h2>Comparison (no code)</h2>
<p>When using events, we need to dispatch these over some kind of pipeline. As Flex and Flash uses the Display List for that by default, you might want to choose using a Static Dispatcher in a specific Class. So that your non-DisplayObjects can receive these too.</p>
<p>When you receive the event, you need to crack the contents to see if this event was for you, or if you can ignore it. With about 250 countries in a World Map that is doable.</p>
<h2>Benefits</h2>
<ol>
<li><strong>Simplification of the project code </strong>- No need to inherit classes or class-references, no hard coded dependencies or chains of dependencies</li>
<li><strong>No Dependency Chains</strong> &#8211; When you pass object references to child objects, you create dependency chains. Dependency chains will break your balls at some point when you start refactoring or when</li>
<li><strong>More agile</strong> &#8211; Changes can be made easier due to the reduction of dependencies and dependency chains in the application</li>
<li><strong>Clear reference to key identifiers </strong>- Each project has a specific structure with primary and secondary objects</li>
<li><strong>Easier to do double binding</strong> &#8211; When you want objects to refer to each other and when they share the same key values, using these key values is all you need to find the object you want to manipulate</li>
<li><strong>Less headaches</strong> &#8211; Complex applications can become like advanced math: very complex and hard to crack down. Knowing that key values reflect the application structure and knowing which key values help you find the right objects is enough.</li>
</ol>
<h2>Things to take care of</h2>
<p>The moment real performance becomes your game, you will need to optimize the code. You do not want to constantly have to resolve &#8220;object C&#8221; when you can do that once and save further overhead once done.</p>
<p>Double-binding is another tricky friend when optimizing. Especially when you do not know who will be there first. Each of the objects doing double binding will have to be able to receive and to create a binding.</p>
<p>This post does not cover that aspect.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/flashworks.wordpress.com/701/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/flashworks.wordpress.com/701/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/flashworks.wordpress.com/701/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/flashworks.wordpress.com/701/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/flashworks.wordpress.com/701/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/flashworks.wordpress.com/701/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/flashworks.wordpress.com/701/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/flashworks.wordpress.com/701/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/flashworks.wordpress.com/701/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/flashworks.wordpress.com/701/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/flashworks.wordpress.com/701/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/flashworks.wordpress.com/701/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/flashworks.wordpress.com/701/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/flashworks.wordpress.com/701/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=flashworks.wordpress.com&amp;blog=7295152&amp;post=701&amp;subd=flashworks&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://flashworks.wordpress.com/2011/04/14/breaking-object-dependencies-via-string-references-static-variables-and-dictionaries/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/cffc2ff7b980a5f5f76c22bddba4f361?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">peter kaptein</media:title>
		</media:content>
	</item>
	</channel>
</rss>
