<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>architecture &#8211; Software, Fitness, and Gaming &#8211; Jesse Warden</title>
	<atom:link href="https://jessewarden.com/tag/architecture/feed" rel="self" type="application/rss+xml" />
	<link>https://jessewarden.com</link>
	<description>Software &#124; Fitness &#124; Gaming</description>
	<lastBuildDate>Tue, 19 Apr 2016 16:03:13 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	

<image>
	<url>https://jessewarden.com/wp-content/uploads/2016/08/cropped-Lambda2-32x32.png</url>
	<title>architecture &#8211; Software, Fitness, and Gaming &#8211; Jesse Warden</title>
	<link>https://jessewarden.com</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>Why Rewrite InsertBackendHere to Node?</title>
		<link>https://jessewarden.com/2016/04/why-rewrite-insertbackendhere-to-node.html</link>
		
		<dc:creator><![CDATA[JesterXL]]></dc:creator>
		<pubDate>Tue, 19 Apr 2016 15:58:38 +0000</pubDate>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[architecture]]></category>
		<category><![CDATA[arhictecture]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[node]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[springboot]]></category>
		<guid isPermaLink="false">http://jessewarden.com/?p=5146</guid>

					<description><![CDATA[There are always fads, but sometimes the fads have reasons they are fads. Question from a reader: &#8220;I&#8217;m fine re-architecting our various software applications used internally usingÂ Backbone/Angular for the front-end. However, why would I use Node for the back-end when my Spring MVC SOAP Java business layer works just fine?&#8221; First, Backend for Frontend It&#8217;s [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>There are always fads, but sometimes the fads have reasons they are fads. Question from a reader:</p>
<blockquote><p>&#8220;I&#8217;m fine re-architecting our various software applications used internally usingÂ Backbone/Angular for the front-end. However, why would I use Node for the back-end when my Spring MVC SOAP Java business layer works just fine?&#8221;</p></blockquote>
<p><span id="more-5146"></span></p>
<h1>First, Backend for Frontend</h1>
<p>It&#8217;s hard for Java Developers to get &#8220;why&#8221; if they are the same ones doing the front-end an the API for it. People like me (who are rare) and grew up on the front-end love this stuff. Case in point Sam Newman&#8217;s lovely &#8220;<a href="http://samnewman.io/patterns/architectural/bff/">Backend for Frontend</a>&#8221; article which summarizes a few of our challenges that Node (or Ruby&#8230; orÂ <a href="https://www.djangoproject.com/">Python</a>&#8230; just easier with <a href="https://nodejs.org/en/">Node</a>) solves.</p>
<p>Given a variety of devices, OR just different designs need different data, it&#8217;s easier to tweak in the back-end once, and have the client get it vs. munging things around all over the place on the client.</p>
<h1>Second, LanguageÂ Reuse</h1>
<p>It&#8217;s easier for the team if they already know JavaScript to code the same language in both places vs. &#8220;Here, use <a href="https://www.sublimetext.com/">Sublime</a> for here, but <a href="https://eclipse.org/downloads/">Eclipse</a> + JDK 7 for there&#8230; and <a href="http://gulpjs.com/">Gulp</a> + Node for here, but <a href="https://maven.apache.org/">Maven</a> for there&#8230; Gulpfile.js for here, but pom.xml &amp; friends all over there&#8230;&#8221;. Same goes for the libraries &amp; API; most are the same.</p>
<p>You get into this weird zone when talking about <a href="https://www.typescriptlang.org/">TypeScript</a>. Many a Java dev has been fine with Java on the back, Flex/ActionScript 3 on the front. Years later, Java on the back, TypeScript + <a href="https://angularjs.org/">Angular</a> on the front. That&#8217;s also ok&#8230; but again, the languages are still different. A good Java dev or team can leverage theÂ strengths of both.</p>
<p>If you have a &#8220;JavaScript Developer&#8221; open role however, you can now put into a:</p>
<ul>
<li>front end role</li>
<li>backend role</li>
<li>devops role (manage Gulp/<a href="https://www.docker.com/">Docker</a>/<a href="https://jenkins.io/">Jenkins</a>)</li>
<li>testing role (use <a href="http://www.seleniumhq.org/">Selenium</a>)</li>
<li>fullstack role via the <a href="http://mean.io/#!/">MEAN</a> stack or its ilk</li>
</ul>
<p>That&#8217;s insanely flexible, price conscious for on/near/off shore, and staff scalable hence why language reuse is a huge deal because of the tools + roles that surround it.</p>
<h1>Third, Scalability in Node is easier for Some Use Cases</h1>
<p>&#8230; sort of. If you&#8217;re doing String parsing, Node does that well. However, for enterprise applications, no one argues the JVM is the shiz, hence Scala &amp; Clojure. The point here, though, is most front-ends nowadays send JSON back and forth and munge it. All the work around that is just easier in Node. Parsing XML, JSON, etc. That&#8217;s what most REST API&#8217;s do.</p>
<p>The low-level work like Database access, security around SQL/NoSQL injection, etc. is all Java&#8217;s and the JVM realm for a lot of Enterprise clients. That&#8217;s why a lot of time you have people like me building my own REST API&#8217;s for my Angular application hitting Java back-ends. It&#8217;s just the norm most of our LLP clients have, many are legacy, a lot new, but both are heavily vested in Java. That&#8217;s fine, but it takes me 5 seconds to write an <a href="http://expressjs.com/">Express</a> GET url to give me exactly what I need vs. begging some Java dev team already overwhelmed to get a node name changed that takes 2 weeks to deploy to QA.</p>
<p>Heck withÂ that mess, orchestration layers for the win.</p>
<p>Finally, although not <a href="http://elixir-lang.org/">Erlang</a>, Node&#8217;s awesome at Web Sockets. Given our ability to only use 1 core, we can write async code VERY easy (much like C# and Scala). Unlike them, ours doesn&#8217;t do parallel processing, but rather, tends to never &#8220;lock&#8221; the CPU since it&#8217;s just a pointer on the stack&#8230; unless you do gigantor for loops without using generator functions.Â Once you start forking processes, it makes it easier for non-longterm server guys (read <a href="http://jessewarden.com">Jesse Warden</a> with the Associates in Art Degree) to scale back-end systems to the enterprise levels. Things like <a href="http://redis.io/">Redis</a> make it uber easy to expedite fast REST API&#8217;s even when the legacy backend is slow. It also has pubsub to allow the cores to talk to each other behind load balancers.</p>
<p>&#8230; and again, sockets are just string parsing. Nowadays, you want to real-time data changes vs. stale front-end data (i.e. <a href="http://samnewman.io/patterns/architectural/bff/">Meteor</a>), and Node is often the one handling the sockets where Java handles the heavy REST data lifting.</p>
<p>I don&#8217;t know multithreading. I know how to easily scale Node to multiple cores with a simple pubsub using Redis to communicate and do basic clustering. That&#8217;s huge compared to what you need to know in multithreadingÂ to pull that off.</p>
<h1>Fourth, Efficient Data</h1>
<p><a href="https://en.wikipedia.org/wiki/SOAP">SOAP</a>Â is garbage. It&#8217;s bloated, no one uses the strong typing on the client, and contracts are never enforceable, especially nowadays with <a href="http://martinfowler.com/articles/microservices.html">microservices</a>. <a href="https://www.youtube.com/watch?v=ynflf9W01vM">JSON</a> won the war. Flash &amp; Flex developers knew that a decade ago.</p>
<h1>Fifth, Spring vs. Spring Boot</h1>
<p>Yes, Spring is old and not based on industry trends. Don&#8217;t re-write it, just update it. IfÂ you ain&#8217;t going full-reactive norÂ Scala/<a href="https://golang.org/">Go</a>/Node, etc, heck yeah, <a href="http://projects.spring.io/spring-boot/">Spring Boot</a> FTW.</p>
<h1>Sixth, Microservices</h1>
<p>Some things Erlang does well. Some things Scala does well. Node &amp; Java the same. With containers taking over the world, &#8220;if it ain&#8217;t broke, don&#8217;t fix it&#8221;. Some people don&#8217;t really care and choose a language/platform for other reasons years ago. That doesn&#8217;t mean you shouldn&#8217;t containerize it. If your back-end does in fact work, you have talent there to work on it, then just allow stuff that grows around it to just add to the microservice ecosystem you have. If another team wants to use [Node or New Framework], fine, have their microservice call your Java microservice. Hotness. Scalable.</p>
<p>&nbsp;</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Consulting Chronicles #7: The Priority Pyramid</title>
		<link>https://jessewarden.com/2012/04/consulting-chronicles-7-the-priority-pyramid.html</link>
		
		<dc:creator><![CDATA[JesterXL]]></dc:creator>
		<pubDate>Wed, 04 Apr 2012 14:09:37 +0000</pubDate>
				<category><![CDATA[Consulting Chronicles]]></category>
		<category><![CDATA[Flex]]></category>
		<category><![CDATA[architecture]]></category>
		<category><![CDATA[consulting]]></category>
		<category><![CDATA[consultingchronicles]]></category>
		<category><![CDATA[leadership]]></category>
		<category><![CDATA[priority]]></category>
		<category><![CDATA[prioritypyramid]]></category>
		<category><![CDATA[pyramid]]></category>
		<category><![CDATA[refactoring]]></category>
		<category><![CDATA[software]]></category>
		<guid isPermaLink="false">http://jessewarden.com/?p=3099</guid>

					<description><![CDATA[Introduction The Priority Pyramid is a tool I use to stay on track with new consulting clients. It prioritizes how, who, and what I engage in at any given time. It can be overwhelming when thrust into a challenging situation, a code base in dire straits, and a frustrated team. You need a strong pillar [&#8230;]]]></description>
										<content:encoded><![CDATA[<p><img fetchpriority="high" decoding="async" style="padding-right: 8px;" src="http://jessewarden.com/archives/blogentryimages/priority-pyramid-4.4.2012.jpg" alt="The Priority Pyramid - The 8 Tiers of Software Consulting" width="320" height="483" align="left" /><strong>Introduction</strong></p>
<p>The Priority Pyramid is a tool I use to stay on track with new consulting clients. It prioritizes how, who, and what I engage in at any given time. It can be overwhelming when thrust into a challenging situation, a code base in dire straits, and a frustrated team. You need a strong pillar of guidance.</p>
<p>This article goes over what parts make up the Priority Pyramid from a high level. I&#8217;ll talk about what milestones make up each section and how you navigate back and forward between the priorities.</p>
<p>When done, you should know how to engage your client&#8217;s team and tackle working on a large code base at a frustrated client site with 99 problems.</p>
<p><span id="more-3099"></span><strong>Why?</strong></p>
<p>Over the years, I&#8217;ve prioritized what I need to be doing when working my consulting clients. There are countless things I need beyond &#8220;coding&#8221;, and all have to do with &#8220;people&#8221;. Code in its own right is challenging enough. Add people to the mix and it gets more complicated than it already is.</p>
<p>Every engagement is different, even with repeat clients. This is why I like consulting. Meet new people, travel new places, learn new things.</p>
<p>While I enjoy and thrive on improv, what I didn&#8217;t like was not having a set of guidelines to deal with each new client. The business blogs &amp; books I&#8217;ve read are pretty dry, and don&#8217;t really focus on the people issues coders encounter and have to deal with. Most also assume YOU are the one creating &amp; maintaing the app, not fixing/modifying a large one extremely behind schedule. It&#8217;s either sales, management, or product management. This includes the consulting books. Some approach it from a larger consulting perspective, where you come in, listen to the client&#8217;s problems, write up a plan, and pass it off to India. If you are involved, it&#8217;s just to either head off major disaster and/or provide face time for the client.</p>
<p>This is NOT what I, and my colleagues I&#8217;ve worked with over the years do. We&#8217;re in the trenches, working alongside our clients, playing the politics games whilst coding.</p>
<p>So, I made my own rules for engagement, prioritized based on importance, with verification points to ensure I&#8217;m on the right track. If I cannot work towards getting through all tiers of the pyramid, I will not be working for the client long, whether by my choice or theirs. It&#8217;s important I flush out these red flags early and tackle them full bore.</p>
<p>That&#8230; and it has D&amp;DÂ connotations.</p>
<p><strong>Quantitative vs.Â Qualitative Foundations</strong></p>
<p>I&#8217;ve used both quantitative and qualitative results from case studies, white papers, and my own experience to base this set of priorities on.</p>
<p><a href="http://en.wikipedia.org/wiki/Brooks%27_law">Mythical Man Month/Brooks&#8217; Law</a>: &#8220;Adding manpower to a late software project makes it later&#8221;. Some of the bad projects I&#8217;ve been on had too many people on them. Your goal at that point is to delegate refactoring to the team to compensate, lead with good architecture, and leverage your trust currency to guide the various teams into a direction you need them to go. Also known as software chaos management. This requires you be at a high enough level to be in charge of various teams. If you&#8217;re not, God help you.</p>
<p>Code Review: One person, reading code for up to but not exceeding 1 hour finds more code defects than unit testing. This is not peer review, but that is also effective. Citations: <a href="http://support.smartbear.com/resources/cc/book/code-review-cisco-case-study.pdf">Code Review at Cisco Systems</a>, <a href="http://www.cnx-software.com/pdf/klocwork-research-code-review-study.pdf">Klocwork/Forrester &#8220;The Value and Importance of Code Reviews&#8221;</a>, and some other <a href="http://www.codinghorror.com/blog/2006/01/code-reviews-just-do-it.html">stats</a> from <a href="http://www.amazon.com/exec/obidos/ASIN/0735619670/codihorr-20">Code Complete</a>. Keep in mind while most of the studies mention that defects do notÂ significantlyÂ decrease after 1 person, the ability to learn from your peers and getting architecture suggestions are very well documented in the blogosphere.</p>
<p>Cheaper to Find Defects Early: Whether you are ruthless about upfront requirements gathering and/orÂ initialÂ architecture, or are adamant about short development iterations that includes scope reduction, both allow the ability to find more defects early. It&#8217;s easier to both find, and fix problems earlier than later for a variety of reasons (code size, feature acceptance, contractual obligations, etc). Beyond the IBM studies back in the 70&#8217;s here&#8217;s an <a href="http://www.methodsandtools.com/archive/archive.php?id=29">excerpt</a> from <a href="http://www.methodsandtools.com/archive/archive.php?id=29">High Quality Low Cost Software Inspections</a>. Also, crazy charts from <a href="http://sqgne.org/presentations/2011-12/Jones-Sep-2011.pdf">Capers Jones</a> (they have some other good studies). This is why I&#8217;m so adamant about getting the visual design (wireframes/design comps/ux/information architecture, etc.) right from the get go, even if 6 months into the project. Lowest hanging fruit and saves tons of time/money.</p>
<p><a href="http://dl.acm.org/citation.cfm?id=1536639">DistributedÂ Development</a> (<a href="http://cs.queensu.ca/~ahmed/home/teaching/CISC880/F10/papers/DistributedDevelopment_CACM2009.pdf">PDF</a>): The result that physical distance between developers doesn&#8217;t matter. Different room/building/country&#8230; not a big deal at all. What matters is how far the software developer(s) are from the stakeholder(s) in the organization management hierarchy. This is extremely important. I am firm believer in both telecommuting as well as on-site visits with clients for communication &amp; leadership reasons. This is central to identifying the power structure of the organization in Tier #2 and garnering trust with those who can help you talk to who you need to talk to in Tier #3. I&#8217;ve been ineffective at more than one consulting engagement because I wasn&#8217;t Â high enough to affect the required positive change.</p>
<p><a href="http://en.wikipedia.org/wiki/Toyota_Production_System">Toyota Production System</a>: Their continuousÂ improvementÂ philosophyÂ and respect for people are what really ring true to me. While <a href="http://blog.digitalbackcountry.com/2007/01/a-look-at-the-rich-internet-application-consulting-landscape/">It Takes a Village</a>Â to build great software, sometimes you have a crowded, drama filled city that you have to work within. Doing your best to get the team motivated to constantly improve, and SEE the improvement occur over time for motivation reinforcement, is just a small way to continually improve. You can only do this if you do in fact respect the people you work with. Empowering leaders amongst those who actually do the work can lead to effective production. You can use these <a href="http://www.fastcompany.com/magazine/111/open_no-satisfaction.html">Toyota Process strategies</a> in your own team delegation.</p>
<p><strong>The Priority Pyramid</strong></p>
<p>The 8 steps are in order of importance:</p>
<ol>
<li>Report</li>
<li>Understanding</li>
<li>Trust</li>
<li>Lead</li>
<li>Build</li>
<li>Explosions</li>
<li>Diagnostics</li>
<li>Architecture</li>
</ol>
<p>While it implies 4 are about coding, make no mistake: The Priority Pyramid is all about people. It&#8217;s built on your relationships with them and those relationships ensure you can do your job.</p>
<p>Lets break down the tiers the following way: What milestones do you need to complete, how to do you move on to the next tier, and when should you move back? I make the assumption if you&#8217;re on a team, you&#8217;ll divide tasks appropriately.</p>
<p><strong>A Note on Tier Foundations</strong></p>
<p>Each tier works on top of the foundation of the former. If the foundation is weak, it won&#8217;t strongly support the one on top. If you don&#8217;t have the trust of management and your co-workers, it&#8217;sÂ difficultÂ to lead them. If you don&#8217;t have a good understanding of the company andÂ peopleÂ who work within it, it becomes veryÂ difficultÂ to affect positive visual design changes to make architecture easier. It&#8217;s ok to be in Tier #8 and realize you need more understanding of how the application will be deployed from Tier #2; just like refactoring code over time, you can continue to strengthen the foundation tiers over time as well.</p>
<h2><strong>Tier #1: Report</strong></h2>
<p><strong>Milestones Before Arriving</strong></p>
<ol>
<li>You&#8217;ve talked to stakeholder(s) on the project to have an idea of what you&#8217;re getting into.</li>
<li>Verify you actually want to get into it. Some consulting gigs are hard to get out of. Some can reflect poorly on your firm/you even if you do a good job. Make sure you&#8217;re willing to make the plunge. We&#8217;re looking for red flags here to save you tons of money and stress. I&#8217;m not saying be choosy, I&#8217;m saying be careful.</li>
<li>Where you&#8217;re going, who you&#8217;re supposed to see, and when.</li>
</ol>
<p><strong>Milestones</strong></p>
<p>You/your firm has scored a client, you&#8217;ve booked your airfare + hotel, and you&#8217;re 1st day on-site has arrived. You look sharp, are excited, and looking forward to making a good first impression.</p>
<ol>
<li>First question out of your mouth after small talk should be &#8220;Who&#8217;s do I report to?&#8221;. Yes, it&#8217;s ok to follow up this question once you&#8217;ve scored more rapport with &#8220;Great, so&#8230; who&#8217;s my boss?&#8221;. This ensures you don&#8217;t do good things that get you in bad trouble.</li>
<li>Second question: &#8220;What will make you happy when I leave?&#8221;. This helps verify why you&#8217;re really here, and what they&#8217;re really paying you for. Sometimes this takes alcohol to get the true answer. Sometimes just a neutral setting outside of the office/building.</li>
</ol>
<p><strong>Successful Exit</strong></p>
<p>Know who you work for and your true goal in life for the next 8 months.</p>
<h2><strong>Tier #2: Understanding</strong></h2>
<p>The best communicators are good listeners. Your task now is to look people in the eye, lean forward, and listen well.</p>
<p><strong>Milestones</strong></p>
<ol>
<li><strong>Listen</strong>: Get people talking, asking questions, and listen to what they say. This is the most important step in the entire pyramid.</li>
<li><strong>Goals</strong>: You need to understand what the goals are for the project, both stated and real. What are you and the client really trying to accomplish? Answering &amp; documenting this will guide your actions for the rest of the project,Â overriddenÂ only by &#8220;Who do you report to?&#8221;.</li>
<li><strong>Problems</strong>: What are the problems and challenges the company has run into? Do any relate to why you&#8217;re here? Do they have a thorough list or are there more? Solving problems earns trust, and helps in the next tier. It also validates your paycheck. Why does the client have those problems? Where do you fit in? Who&#8217;s accountable for identifying solution(s) for and solving those problem(s)? These are your first challenges in the game.</li>
<li><strong>Dissect People</strong>: This is also an opportunity for you to start learning who the players are in the game. You need to understand what makes someone tick to best interact with them. Do they like business first, small later or the opposite? Do they have ulterior motives? Can they be trusted? Can they give you valuable intel on the project others won&#8217;t? What will it take to make them comfortable enough to tell you more? How can you possibly help them? You&#8217;re going to be spending the next 3 to 18 months with these people. Get to know them, make a good first impression, and understand them. These are the people you want on your team, who you want to do certain things for you, who you want to trust you. Once you understand them, you can effectively engage them. Sometimes this is done simply by watching how they interact with others. Ask questions to get them talking; their personality whilst reveal itself. Finally, figure out who reports to whom for real? What is the power structure? You&#8217;ll need to play within this framework; best to know how it works for real vs. what the label says on their door.</li>
<li><strong>Explore</strong>: Finally, code stuff. Time for initial reconnaissance. Taken what you&#8217;ve learned, it&#8217;s time to verify what you heard is recent, relevant, and can be corroborated with the code. This should still be framed from a &#8220;learning the company&#8221; perspective. You need to:</li>
<ol>
<li><strong>Learn the Data Model</strong>: The VO&#8217;s, the Services it calls, and what those business objects actually mean to the organization.</li>
<li><strong>Learn The Framework</strong>: How is the codeÂ architected; what framework did they use?</li>
<li><strong>Understand The Story</strong>: With another developer, preferably one who worked on the code base and/or your client, ask the developer questions to learn the story. Even the worst code base has a reason how it got there. Like an archeologist, you want to understand this history, the pivotal decisions, or lack thereof, that made it the way it is. You&#8217;ll learn the to respect, and pity, even the worst code base once you&#8217;re armed with this knowledge.</li>
<li><strong>Look For Red Flags</strong>: Both the currentlyÂ benign, and the &#8220;holy eff we&#8217;re eff&#8217;d&#8221;. Whether that&#8217;s everything being a hashmap in Java, Angular &amp; Backbone both being used in the same code base, or ActionScript 2. You don&#8217;t want surprises, you want to frame your perspective of the code base with your client&#8217;s. This is a VERY important step. Don&#8217;t say it, but talk about it internally in my mind. Find out why there is aÂ disparityÂ in perception.</li>
<li><strong>Look For Mines</strong>: Like red flags, these are things that down the line of a project, based on what you learned above could go boom. They aren&#8217;t aÂ priorityÂ but need to be documented.</li>
<li><strong>Look For Validation</strong>: Did everything you learned in Steps 1 &#8211; 4 get validated or where you completely off? If so, continue to dig, and redo steps 1 &#8211; 4 to re-verify.</li>
</ol>
</ol>
<p><strong>Successful Exit</strong></p>
<p>When you firmly understand the client&#8217;s reality, the reality the code reflects, and the real reality once you&#8217;ve resolved the two, you&#8217;re ready to move on. If they still don&#8217;t mesh, keep asking questions &amp; researching.</p>
<h2><strong>Tier #3: Trust</strong></h2>
<p>Assuming you&#8217;ve made good first impressions with those you&#8217;ve met, it&#8217;s now time to validate those initial impressions in those you&#8217;ve met. It&#8217;s time to start building trust.</p>
<p><strong>Milestones</strong></p>
<ol>
<li><strong>Provide Immediate Value</strong>: Check in code into the company&#8217;s source control your 1st week there. Preferably the code fixes a bug. Do NOT try to save the world in the code base. Pick some litter instead. If you clean the entire thing in a day, great, but get your feet wet and see what happens. A lot of drama and things you couldn&#8217;t predict happen AFTER you&#8217;ve checked in code and it goes into production. Start small and work your way up. Just ensure it&#8217;s immediate.</li>
<li><strong>Make Professional Friends</strong>: Respect those you work with and get to know them. Whether this is small talk that&#8217;s sincere orÂ genuineÂ interest, whatever works to build a positive relationship. People trust those they like. Trust is a currency you&#8217;ll sometimes have to spend in buckets to make positive headway so start investing in earning some now.</li>
<li><strong>Visible Logger</strong>: Invest in a visible logger. Even if the code doesn&#8217;t currently have problems, when it does, you want it to talk to you. Not only you, but the company. You want to corroborate this communication with your boss. When production explodes, and you know within seconds because your little secret keyboard shortcut debug window shows the error, that inspires confidence. It also provides a kind of transparency to your client when others start using it proactively to find problems. You just empowered a company to work together; well done, that&#8217;ll earn some trust. Make the code talk to you so you can trust what it&#8217;s saying, then expose this communication channel to your client.</li>
<li><strong>Provide Transparency</strong>: As you start getting your feet wet, whether this is struggling to get your environment setup so you can compile, or are deep in the bowels of fixing your first bug, let your boss know. Keep them appraised of what you&#8217;re doing on regular intervals, even if she doesn&#8217;t ask. Come across with confidence; you KNOW what you need to be working on, and you&#8217;re informing your boss as such. Additionally, she has a chance toÂ re-prioritizeÂ if you need to be working on something more pressing. No communication, and neither of these things happen. If they know and have confidence in you doing what you say you&#8217;re going to do, they can play defense and keep their boss off your, and your team&#8217;s back.</li>
</ol>
<p><strong>Successful Exit</strong></p>
<p>Do you think people trust you? Have you checked in working code that fixes a problem and your boss has verified this? Can you even compile? Do you know the names of those you&#8217;re working with/near? If yes to all, you&#8217;re ready to move on.</p>
<p><strong>NOTE</strong>: If you ever lose trust, fall back to continually adding immediate value. Trust isn&#8217;t given, it&#8217;s earned. If you lose it, the only way to get it back to is re-earn it from scratch.</p>
<h2><strong>Tier #4: Lead</strong></h2>
<p>At this point you know enough about the goals of the project to start formulating plans on moving forward, whether this is how to implement new features or how to fix/refactor existing ones. You&#8217;ve provided enough value to earn a modicum of trust. It&#8217;s time to lead people forward.</p>
<blockquote><p>A manager puts people in a line, puts the guy with the machete at the front, and leads people through the jungle effectively. A leader climbs the tree, and tells everyone they need to go left instead.</p></blockquote>
<p><strong>Milestones</strong></p>
<ol>
<li><strong>Short Term Goals</strong>: You&#8217;ve assessed the situation and identified priorities that need to be refactored (using my previous article). You need the team to agree on a common logging interface, both in code and visually. Finally, you need the team to agree on an architecture.</li>
<li><strong>Long Term Goals</strong>: You&#8217;ve identified architecture holes that need to be plugged. Sometimes there are design problems that if changed could save months of work and hardship. You need to start work and documentation on it now. Solidify the long term goal into something defendable, and get the teams input. <span><span style="color: #000000;">Be careful how you go about talking about it. While you need client feedback (remember transparency), it must be attainable to company-relevant, short term steps. You can spend trust currency for longer term refactoring/re-architectureÂ endeavors, but I recommend against it.</span></span></li>
<li><strong style="color: #000000;">Resources</strong><span style="color: #000000;">: Sometimes you need to hire additional people, whether from internal client teams, additional consultants/contractors from your firm, or hiring on behalf of your client. This could be staff augmentation or hiring a specificÂ </span>skill set<span style="color: #000000;">Â you need/want. Identify these early and ask your boss.</span></li>
<li><strong>Divide, Delegate, and Conquer</strong>: Whether the client&#8217;s employee&#8217;s or your firms, you need to divide up the massive amount of work amongst people. Offer up tasks first, and then assign to those you deem appropriate if no volunteers materialize. Building upon Tier 2 and 3, you should have a gut feeling for who&#8217;s best for what task. You cannot save the world by yourself. It may seem that you spend more time aiming people in the same direction then actually walking that direction yourself. Don&#8217;t fret; you&#8217;re on the right track.</li>
<li><strong>Be Positive</strong>: While misery loves company, peopleÂ like and follow positive people. In talking &amp; delegating all of your goals, plans, do so positively. You&#8217;re not &#8220;fixing a pile of rubbish&#8221;, you&#8217;re &#8220;building an awesome application&#8221; or &#8220;improving an important machine&#8221; or whatever you can say and actually believe when you say it. Eat right,Â exercise, and/or surround yourself with positive influences. Make this the year you <a href="http://www.menshealth.com/best-life/make-life-worth-living">commit suicide</a>, reorganize &amp; clean your working environment/home office, or just accomplish a small goal that&#8217;s not work related that you use asÂ positivityÂ fuel. Mentor &amp; encourage your team but don&#8217;t come off as a know-it-all/holier-than-thou. Play to win.</li>
</ol>
<p><strong>Successful Exit</strong></p>
<p>If you know what you/your team needs to be working on today, next month, you&#8217;ve approved the hiring you need, and the team is all tasked up, then it&#8217;s time to move on.</p>
<p><strong>Notes on Tier #5 &#8211; 8</strong></p>
<p>The latter teirs are development specific, but rely on a strong firm foundation from the first 4. Remember, the human component is your weakest link, not your Factories. Strengthen them; do not enter these 4 latter tiers of first 4 are weak.</p>
<h2><strong>Tier #5: Build</strong></h2>
<p>You need to easily build the software. This is the most common, and frequent, option you&#8217;ll do many times a day, every day. The longer this takes, the longer it takes you to develop. This can also kill your team&#8217;s momentum. If something goes wrong, such as someone checking in a bug that breaks the build into source control, or a feature needing be implemented for a presentation by some date, a slow buildÂ exacerbatesÂ time to resolution.</p>
<p>Worse, some developers will start making their own build setup, leading to code that works on some developers machines and not on others. Validation of working code suddenly becomes meaningless which can adversely affect project schedule metrics. Even worse, you can think your code works, but it doesn&#8217;t for others. Who&#8217;s right?</p>
<p><strong>Milestones</strong></p>
<ol>
<li><strong>Quick</strong>: The build needs to run quickly. This obviously anÂ arbitraryÂ metric based on code size, libraries,Â continuousÂ integration setup, etc. If developers say &#8220;the build is slow&#8221;, then it&#8217;s slow. Utilize libraries so the entire thing doesn&#8217;t have to compile, inject dependencies at runtime, utilize modules&#8230; whatever it takes.</li>
<li><strong>Easy</strong>: If the build is complicated to do, you&#8217;ll get developers making a lot of mistakes during code validation time before they check in. They&#8217;ll either check in bad code, or make their own setup that allows the code to work on only their machine. They should be able to just click 1 button, run an Ant/Maven script, or do a 1 line command line execution.</li>
<li><strong>Duplicated</strong>: The build should be able to be duplicated on a new developers machine. It&#8217;s completely fine to have company standards, such as only Windows 7 PC w/admin rights, Flex SDK 4.6, running Rake 0.8.2. It&#8217;s also ok if that takes some time with another developer to setup. What&#8217;s not ok is once they do that, it doesn&#8217;t work. If there are 3rd party dependencies that cannot effectively be deployed x-machine, find a way to remove them. Solutions include, again, using libraries, modules, development servers vs. local server setup, etc.</li>
</ol>
<p><strong>Successful Exit</strong></p>
<p>If you can run the build multiple times a day without pulling your hair out, it can be run multiple times on the same code base and not break, and anyone on the team can explain to a new developer 90% of the setup, you&#8217;re good to go. Another validation includes Developer A checking in code, then Developer B updating to latest and running the build and it works on their machine as well.</p>
<h2><strong>Tier #6: Explosions</strong></h2>
<p>When things go awry, you need to immediately know where and why. More than aÂ euphemismÂ for errors/exceptions, explosions also include errors in the application that constantly cause fire drills in the company.</p>
<p><strong>Milestones</strong></p>
<ol>
<li><strong>Exceptions Handled</strong>: Handle all errors save null pointers. If you have global exception handling capabilities, implement it/them. This doesn&#8217;t mean just wrapping something in a try/catch; it means not only logging the catch, but putting something meaningful in the catch so you&#8217;ll understand what it means when it happens.</li>
<li><strong>Logging</strong>: You need to centralize all long into a single library. It&#8217;s ok if this library is your own that builds on top of the built-in provided one, such as Flex&#8217; ILogger. As long as anyone, anywhere on the team wants to log something, they use that vs. print/trace.</li>
<li><strong>Visual Log</strong>: Optional: A visual window, built into the application itself (SWF/JS, etc), that prints out the log levels. This is done to allow logs to be seen by developers, not users. It also allows non-developers,Â especiallyÂ QA, to proactively find problems and talk directly with thoseÂ responsibleÂ vs. the 1st developer they can find. The value this provides inÂ empowermentÂ and time saved should not be underestimated.</li>
<li><strong>No More Fire Drills</strong>: Wrangling in challenging errors to help prevent fire drills can do 3 things. First, you score a lot of trust in &#8220;knowing&#8221; why something is wrong vs. 10Â peopleÂ running around aimlessly trying to figure out why. Second, you can clearly cite accountability; is it the server-side team, your team, or the database team? Instead of yelling &#8220;I think your stuff broke&#8221; you can confidently say it did with helpful data for them to test against. That kind of attitude is much easier to solve problems with. Third, fire drills no longer sabotage your productivity.</li>
</ol>
<p><strong>Successful Exit</strong></p>
<p>If an error occurs and you know where it happened, a general reason of why, and who&#8217;s potentially accountable, you&#8217;re in insanely good shape. Users don&#8217;t see these errors, just null pointers, or those you&#8217;ve built a GUI for (ie Alert error dialogue). Bonus points if fire drills happen on other teams that aren&#8217;t related to yours&#8230; but you have a way of helping through logging to make testing easier.</p>
<h2><strong>Tier #7: Diagnostics</strong></h2>
<p>Diagnostics form a range of tools, not just code. They are anything that helps provide insight into code issues or runtime errors without costing more overhead inÂ maintenanceÂ than the value they provide. The reason diagnostics is before architecture is that in larger applications,Â especiallyÂ in a consulting context, adding simple diagnostics has a ton of value with little effort whereas architecture takes a ton of effort but tends to have low perceived value (yes, it&#8217;s valuable, just harder to sell).</p>
<p><strong>Milestones</strong></p>
<ol>
<li><strong>Unit Test Coverage</strong>: Even if you&#8217;re not doing TDD, unit tests along help find &amp; prevent bugs as well as improve API&#8217;s. Unlike code reviews, they don&#8217;t get tired, benefit the entire team, and if written well only slightly add to codeÂ maintenance. Finally, they can be automated. These are also great things to work on in down times such as when JIRA is cleared, you&#8217;ve hit a brick wall with another bug, or are waiting on dependencies for a feature.</li>
<li><strong>Integration Tests</strong>: These are my favorite on service layers, more so than unit tests. The reason being is most of the Flex projects that I&#8217;ve worked on in a consulting context had some form of service layerÂ problem; ie how they talk to the back-end. Both refactoring the service code and writing unit tests that allowed me to automate the testing. It&#8217;s also nice to quickly know what part broke with confidence; client, server, or database. Automating these also makes you feel better when the server guys test new code, you can quickly help them test. There are more to integration tests, but these are the low-hanging fruit of &#8217;em.</li>
<li><strong>Automated Builds</strong>: Expanding upon Tier #5,Â streamliningÂ your build process to be more inline withÂ continuousÂ integration practices. This means designating a resource to setup, and maintain, aÂ continuosÂ build tool like CruiseControl/Hudson/TeamCity, etc. You should know who checked in bad code and when.</li>
<li><strong>Custom Diagnostics</strong>: Some applications have challenging domains of complexity. For example, video; there are TON of things that can go wrong at runtime even if the code compiles just fine. There are also a sequence of events that can cause video to fail, and knowing this sequence is paramount in debugging it, or shrugging it off since there&#8217;s nothing you can do (i.e. CDN is down). More importantly, though, sometimes you need a way to glimpse this in a more visual way than a logging window can provide. Conversely, sometimes you need to see environment variables in real-time. This little window can verify your application is running in the mode you think it is for a developer in another country. Simply making a box with a text field in it that showed Flash Player&#8217;s sandbox security type saved me 3 days (I lost 3 figuring this out, heh). Additionally, they can help empower others to do testing &amp; diagnostics on their own. Just be careful these are not a security risk for code and/or company information if deployed in production.</li>
</ol>
<p><strong>Successful Exit</strong></p>
<p>If you have good unit test coverage, can automate their running, your build is automated in some fashion (even if just client side only), and you have gui or command lines way to gain insight to your running application to find out more about errors, you&#8217;re in awesome shape.</p>
<h2><strong>Tier #8: Architecture</strong></h2>
<p>While good architecture requires a book full of information + years ofÂ experimentationÂ to get right, what we&#8217;re concerned with here is IMPROVING existing architecture. If you are starting a project from scratch and own the architecture, great, use this phase forÂ maintenance. Otherwise, we&#8217;re looking for that sweet spot of a 1 day change for a more decoupled, easier to use &amp; test in code system. If something takes longer than 3 days, you&#8217;ll be hard pressed to merge it back in and notÂ inconvenienceÂ other developers&#8230; unless it&#8217;s very little code.</p>
<p><strong>Milestones</strong></p>
<ol>
<li><strong>Tight Factories</strong>: Any part of your application which takes outside data into it&#8217;s system, such as external JSON/XML as well as user input, needs to be furtherÂ hardened. DRY the code, layer with <a href="http://jessewarden.com/archives/pix/moar-unit-tests-jxl.jpg">#moarUnitTests</a>. Form a convention on what happens when parsing/decoding fails; do you throw errors orÂ returnÂ null and log them, thus passing the burden of handling null to your system? Decide as a team.</li>
<li><strong>Fault Tolerant Services</strong>: Whether to a back-end, an external call to JavaScript in a host page, or an ad library&#8230; if it&#8217;s not your code, it&#8217;s a service. Make sure you wrap that with a Proxy that can NOT explode, and logs everything that went wrong. That extra 20 minutes pays off mad dividends.</li>
<li><strong>MVC/MVP/MVVM/YourMom/SC/PV/PM</strong>: As a team, pick one an over arching architecture pattern and stick with it for new code. I like <a href="http://martinfowler.com/eaaDev/SupervisingPresenter.html">Supervising Controller</a>, while others of my front-end Â ilk like <a href="http://martinfowler.com/eaaDev/PresentationModel.html">Presentation Model</a>. A lot of JavaScript web frameworks follow more of a <a href="http://martinfowler.com/eaaDev/PassiveScreen.html">Passive View</a>. The only right choice is team consensus &amp; comfortability. Then endeavor as a team to get certain parts moving in that direction. If there is old code, and you&#8217;re currently working on it, see if I can convert in less than a day to make more congruent with the rest of the architecture.</li>
<li><strong>DRY</strong>: If none of the above can be improved, simply making code more DRY is a good fall back task to more unit test coverage.</li>
<li><strong>TODO/FIXME/KLUDGE/HACK</strong>: Do a find all in the code. If you see those, fix them. #<a href="http://pragprog.com/the-pragmatic-programmer/extracts/software-entropy">fixBrokenWindows</a></li>
</ol>
<p><strong>Successful Exit</strong></p>
<p>You never really exit Tier #8; in fact you tend to loop back to either 7 or 6 and 7 and then back to 8. However, if you find yourself working on new features, or fixing bugs with no other drama and the rest of your team is doing the same&#8230; then you&#8217;re in epic shape.</p>
<p><strong>Conclusions</strong></p>
<p>As you can hopefully see, my priority list helps keep you focused on delivering value to those that matter quickly. Good software development is iterative. Earning trust is also iterative; you don&#8217;t take people&#8217;s money and disappear for 6 months (that&#8217;s called good Capitalism via Waterfall). This whole list, while referring to software development, is all about relationships with people. Excluding code review, your challenge as a leader is delegating the tasks in each tier to divide &amp; conquer, mitigating conflicts, and solving hard software problems in addition the rest of yourÂ responsibilities.</p>
<p>Each tier builds upon the former all the way down the line. While deep in the bowels of fixing explosions in Tier #6, I&#8217;m still continuing to build meaningful relationships in Tier #3.</p>
<p>Remember:</p>
<ol>
<li><strong>Report</strong>: Know your true boss and what will make her happy.</li>
<li><strong>Understanding</strong>: Listen, learn about the company, the people, and dive into reading the code.</li>
<li><strong>Trust</strong>: Earn trust by providing immediate value.</li>
<li><strong>Lead</strong>: Take the initiative and move the team forward. Delegate, divide, conquer.</li>
<li><strong>Build</strong>: Make the build fast, easy, and capable of being duplicated if need be.</li>
<li><strong>Explosions</strong>:Â When things go awry, you need to immediately know where and why. Prevent fire drills.</li>
<li><strong>Diagnostics</strong>: Get good unit test coverage, integration tests, automate your builds, and build any customÂ diagnosticÂ tools needed.</li>
<li><strong>Architecture</strong>: Decide on a direction/framework, and continue to nurture the code, and developers, in that direction. Loop back to 6 &amp; 7 if need be.</li>
</ol>
<h6><a href="http://www.flickr.com/photos/55935853@N00/2401448261/">Title photo by Ewan Monro</a>Â is under aÂ <a href="http://creativecommons.org/licenses/by-sa/2.0/">Creative Commons &#8211; ShareAlike Attribution license</a>.</h6>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Why Robotlegs For Games?</title>
		<link>https://jessewarden.com/2011/08/why-robotlegs-for-games.html</link>
					<comments>https://jessewarden.com/2011/08/why-robotlegs-for-games.html#comments</comments>
		
		<dc:creator><![CDATA[JesterXL]]></dc:creator>
		<pubDate>Sun, 07 Aug 2011 18:10:54 +0000</pubDate>
				<category><![CDATA[Flex]]></category>
		<category><![CDATA[ActionScript]]></category>
		<category><![CDATA[architecture]]></category>
		<category><![CDATA[corona]]></category>
		<category><![CDATA[designpatterns]]></category>
		<category><![CDATA[Flash]]></category>
		<category><![CDATA[lua]]></category>
		<category><![CDATA[mvc]]></category>
		<guid isPermaLink="false">http://jessewarden.com/?p=2777</guid>

					<description><![CDATA[Why Robotlegs for Games? The following covers why you would utilize the Robotlegs MVC architecture in a lightweight, Lua game for Corona. I&#8217;ll discuss the refactoring reasoning, the common problems you run across in game architecture, and their solutions with their pro&#8217;s and con&#8217;s discussed. Finally, I conclude on how Robotlegs helps solve these common [&#8230;]]]></description>
										<content:encoded><![CDATA[<p><img decoding="async" style="padding-right: 8px;" src="http://jessewarden.com/archives/blogentryimages/corona-robotlegs-games.jpg" alt="" width="300" height="232" align="left" /><strong>Why Robotlegs for Games?</strong></p>
<p>The following covers why you would utilize the <a href="http://robotlegs.org">Robotlegs</a> MVC architecture in a lightweight, <a href="http://lua.org">Lua</a> game for <a href="http://www.anscamobile.com/corona/">Corona</a>. I&#8217;ll discuss the refactoring reasoning, the common problems you run across in game architecture, and their solutions with their pro&#8217;s and con&#8217;s discussed. Finally, I conclude on how Robotlegs helps solve these common issues, specifically in a Lua &amp; Corona context.</p>
<p>I&#8217;ve started the port of Robotlegs to Lua to work in Corona if you&#8217;re interested in <a href="http://jessewarden.com/2011/08/robotlegs-for-corona.html">learning more</a>.</p>
<p><strong><span id="more-2777"></span>Refactor First</strong></p>
<p>In learning Lua &amp; Corona, I quickly ran into 2 problems with the game I&#8217;m working on. The main code controller became way too large to manage. It wasn&#8217;t quite a God object (yes, the anti-pattern) because a lot of the View&#8217;s themselves handled some of the necessary messaging &amp; logic. Regardless, time to refactor.</p>
<p>The first thing was to start using classes. Lua doesn&#8217;t have classes. There are a bunch of resources out there that explain how to do them in various incarnations. I went with a version that Darren Osadchuk, creator of the <a href="http://www.ludicroussoftware.com/corona/simple-oop-with-inheritance-in-corona/">Corona bundle</a> for TextMate.</p>
<p>The second thing was to start using packages. Lua doesn&#8217;t have packages. There are various ways of implementing them which are all confusing as hell. The easiest way is to just put your code in a folder and use that path in the require function, but you can&#8217;t utilize folders for Android in the latest build of Corona at the time of this writing.</p>
<p>These are the low hanging fruit of re-factoring, and has made a huge difference in code readability &amp; maintainability.</p>
<p><strong>Burdens of Encapsulation</strong></p>
<p>The downside of OOP is that it&#8217;s encapsulated. While making something a black box with internally managed state &amp; implied reusability is good on the surface, it pushes the burden of managing communication between those encapsulated objects to someone ones.</p>
<p>You have 3 options: globals, messaging dependencies, or mediation.</p>
<p><strong>Global Variables: The Good</strong></p>
<p>Most people agree global variables are badâ€¦ in larger software development. In smaller scoped software gaming, not so much. Let&#8217;s explore their benefits.</p>
<p>In a lot of languages, globals are part of the language design, irrespective of how the runtime and tools/IDE&#8217;s handle them. Some languages make them first class citizens with mechanisms and rules around how they&#8217;re often used. This makes them formalized, accepted, AND useful. This is important to understand.</p>
<p>If it&#8217;s formalized, it means the language designers deem their usage acceptable, AND expected.</p>
<p>If it&#8217;s accepted, it means others will use them, incorporate them into their projects, libraries, and training &amp; writing materials. This also means it&#8217;s then promoted amongst the community, solutions and coding strategies/solutions are built around it. This doesn&#8217;t make it inherently &#8220;good&#8221;, just accepted in that particular community.</p>
<p>If it&#8217;s useful, the majority of people will use it if their job is using that language as opposed to hobbyists, or those who continue to explore the language and try different ways to solve similar problems with it off of their employer&#8217;s clock.</p>
<p>In Lua, globals are all 3. Formalized via _G, very similar to ActionScript 1&#8217;s _global, accepted in that people do in fact use them (unknowingly a lot I&#8217;d wager), and useful since the syntax to utilize globals is terse; a Lua hallmark. Notice both have the preceding underscore to ensure they don&#8217;t interfere with the developer&#8217;s potential to create a variable called G or global. While ActionScript 1 has some security implementations to prevent certain loaded SWF&#8217;s from writing/modifying existing definitions, they had the same mechinism with strorage, first via _level&#8217;s on a per SWF basis, and later a formalized _global. Lua takes it a step farther with a series of facilities to change &#8220;which&#8221; globals your using, etc. It&#8217;s also used in package naming strategies, OOP, etc.</p>
<p>As a globally accessible table, access to _G is fast. Fast is good in game development. You want to be part of the solution, not part of the problem.</p>
<p><strong>Global Variables: The Bad</strong></p>
<p>This differs from traditional software development. If you come from any formal software development, globals are considered extremely bad practice. There is a common strategy to use the Singleton design pattern to &#8220;get away with it&#8221;. Even those are considered bad practice when over used. In fact, Singletons are often created merely because the language doesn&#8217;t offer a formalized way of doing global variables (like ActionScript 3 vs. ActionScript 1).</p>
<p>Why? The 3 main reasons are application state coupling, access control, and preventing testability.</p>
<p><strong>Application State Coupling</strong></p>
<p>Application State Coupling refers to the state of your application being dependent on usually a series of global variables. I won&#8217;t get into the why&#8217;s, but <a href="http://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller">MVC</a> and it&#8217;s <a href="http://martinfowler.com/eaaDev/ModelViewPresenter.html">MVP</a> derivatives (<a href="http://martinfowler.com/eaaDev/PassiveScreen.html">Passive View</a>, <a href="http://martinfowler.com/eaaDev/SupervisingPresenter.html">Supervising Controller</a>, <a href="http://martinfowler.com/eaaDev/PresentationModel.html">Presentation Model</a>) have solved most of the state problems. They keep visual state in the View&#8217;s (or anything that&#8217;s a GUI that you can see), and application logic &amp; state in the Model layer somewhere. Your application is no longer coupled to a single variable being a specific value for your application to run, to exhibit a certain bug, etc. Each piece can (usually, hehe) be run independently, and if there is a problem, you know where to look, or at least where NOT to look.</p>
<p>An example is if your player is dying too quickly, you know the problem isn&#8217;t in the player code, or the controller code, but rather somewhere in the model where his life state is being access/set/updated. If you used a global, it&#8217;d probably be set in player itself, or perhaps by an enemy bullet that hit him, etc. No clue where to look.</p>
<p>Another side effect is adding new global variables. This leads to certain parts of your application expecting the globals to be a certain value at certain times. If they aren&#8217;t, things don&#8217;t work. Because they are many different places, it becomes extremely time consuming for you to debug and track down because you don&#8217;t necessarily know who is expecting what to be set to what, and why. This is more caused by access control, howeverâ€¦</p>
<p><strong>Access Control</strong></p>
<p>Access Control refers to who can access your data, and how. In Flash &amp; Flex apps that are smaller, we&#8217;ll usually use the server as access control. Meaning, while we provide a GUI to allow people to create, edit, and delete users from a database for example, the actual PHP/Ruby/Python/Java on the server is the access control. No matter what we do in the <a href="http://adobe.com/products/flex">Flex</a>/<a href="http://adobe.com/products/flash">Flash</a>, we can be assured the server (usuallyâ€¦ *sigh*) will ensure we don&#8217;t delete people we&#8217;re not allowed to, delete users en-masse, put illegal characters into their name, etc. Basically anything that would corrupt the data and screw the up the GUI.</p>
<p>In Flex/Flash apps, and nowadays in larger JavaScript web applications, you have a notion of &#8220;application logic&#8221; or &#8220;application state&#8221;. This is because this state is no longer on the server. It used to be with some web applications, usually in the session. When you go add something to your cart on Amazon.com, it&#8217;s not stored on the page that much beyond to show you a slight graphical change. Once you change pages, that JavaScript &amp; HTML page state is now gone and replaced with a new oneâ€¦ but it remembers what you added. It does this because the state is saved on the server since the client needs to be stateless if the user refreshes the page to go to another one.</p>
<p>We don&#8217;t have that problem as much in Flash/Flex apps. We don&#8217;t go to pages insomuch as new &#8220;Views&#8221;. These views, or graphical representations of a GUI that have internal state, are still in the same SWF embedded in the same page in a browser that doesn&#8217;t go anywhere (same thing for an <a href="http://adobe.com/products/air">AIR</a> app on the desktop or on a mobile device). Therefore, someone has to be responsible for holding the data in a variable or series of variables, and updating it when the server gives you new data.</p>
<p>These are usually classes called &#8220;Models&#8221;, and they&#8217;ll usually mirror their server-side equivalents in terms of CRUD operations: create, read, update, and delete. Where they differ is how much of the server-side provided data is parsed, error handling, data access control, and how that server-side data is set internally.</p>
<p>Suffice to say, good Model classes are encapsulated, ensure application logic is accessed by a public API that ensures security, doesn&#8217;t allow the internal data to be corrupted, and does all this within reason. An example is our Player&#8217;s health. If every enemy collision and bullet out there has access to the player&#8217;s health, we have no easy way to track down who may be potentially doing the math wrong on calculating the new hit-points and setting them to invalid values, or thinking the player is dead when she&#8217;s not, etc. If you have a PlayerModel, you can ensure your problem&#8217;s regarding hit-points and letting the world know about player death is in one place, and problems with said state (how much health does the player currently have) starts in that class and those who access him. Access control in this case refers to ensuring the PlayerModel only exposes methods to increment/decrement the Player&#8217;s hit-points vs. allowing them to be set to -16, or NaN/Nil, etc. You don&#8217;t even have to worry about this; you just don&#8217;t allow it to happen.</p>
<p>Thus, the burden on accessing and setting hit-points correctly is pushed to someone else; those who access PlayerModel. THIS is where you look for bugs, but again, you need to ensure only a set few have access to the data access layer (PlayerModel).</p>
<p>In short, Models centralize data access, ensure it&#8217;s correct, testable, and <a href="http://en.wikipedia.org/wiki/Don't_repeat_yourself">DRY</a> and prevent incorrect access errors, (i.e. global.playerHitPoints = &#8220;dude, pimp!&#8221;).</p>
<p><strong>Preventing Testability</strong></p>
<p>This third problem isn&#8217;t necessarily around unit-testing and <a href="http://en.wikipedia.org/wiki/Test-driven_development">TDD</a> (Test Driven Development), but more around just ripping the class out, putting in a simple main.lua, and seeing if it works. If it has dependencies, they get dragged with itâ€¦ and you have to instantiate and setup those guys. Suddenly quickly confirming some class or method works or not becomes a time consuming process that&#8217;s painful. If you can&#8217;t test something in isolation, you&#8217;ll have huge problems down the road isolating problems in a timely fashion.</p>
<p>Globals by their very nature are&#8217;t testable because they&#8217;re variables, not encapsulated classes. While Lua has some neat mechanisms to encapsulate globals in certain contexts, somewhere, someone is setting a global to some value in their own way. If a class depends on this global, that global must be set the same way before you test the class that relies on the global. Since you may not know who set the global a certain way, that global may not be the same in your test environment vs. in the game proper.</p>
<p><strong>Global Conclusions</strong></p>
<p>While globals in Lua are fast, formalized, and accepted, you must be aware of the rules so you can break them with confidence. First, keep in mind if you want to get something done, premature optimization is the root of all evil. With that in mind, ask yourself the quick question: Does creating a data access control class/layer around your globals to ensure it&#8217;s DRY and secure add so much overhead that the speed makes your game un-playable?</p>
<p>I&#8217;ve found this not to be the case in my implementations in Lua and ActionScript. They run fine, are encapsulated, and succeed in good access control. Thus, while globals are accepted in Lua, implementing a good coding practice via a data access layer does not adversely affect my performance while increasing my productivity in DRY&#8217;er code that&#8217;s easier to test with good encapsulation.</p>
<p><strong>Messaging Dependencies</strong></p>
<p>We&#8217;ve seen how globals can work to allow multiple View&#8217;s to talk to each other directly or indirectly via variables they all reference, or even methods/tables. We&#8217;ve also see how this leads to bad things like harder to find bugs and spaghetti code (you change 1 thing that adversely affects something else seemingly unrelated) as well as making refactoring more challenging than it needs to be.</p>
<p>One way to allow encapsulated objects to communicate is through messaging systems, also know as notifications or events (we&#8217;ll just call them events because that&#8217;s what ActionScript and Corona use). When something happens inside the object, such as a user clicking something, or some internal property changes, it&#8217;ll emit an event. There are 3 types of events we&#8217;re concerned with: local, global, and event context.</p>
<p>A local event is an event issued from an object/table. In ActionScript, anything that extends EventDispatcher, including DisplayObjects (things you can see), can emit events. In Lua, only DisplayObjects can; you have to build your own for regular tables as Lua doesn&#8217;t have an event system. So, if I create a wrapper table in Lua, I can then register for events from that table, and later when it emits them, I&#8217;ll hear them. Those are local events; events dispatched from an object/table directly. Although event objects/tables have the target property on them so I know where they come from, USUALLY event responders are not that encapsulated, and make the assumption that the event is coming from a specific object/table.</p>
<p>A global event is one that&#8217;s received, but we have no clue where it came from. At this point, we&#8217;re inspecting the event object itself to find context. If it&#8217;s a collision, then who collided with who? If it&#8217;s a touch event, then what was touched, and how? Global messaging systems are used for higher-level events and concerns. While you usually won&#8217;t have global events for touches because your mainly concerned with handling the touch event locally, a pause event for example could of been issued from anywhere, and while you don&#8217;t care who issued it, you&#8217;re more than capable of handling it (stopping your game loop, pausing your player&#8217;s movement, etc).</p>
<p>To properly handle an event, we need context. Context is basically the data the event, or message, has stored internally so when the handler gets it, he knows how to handle it. If the event is a touch event, cool, start moving. If it&#8217;s a touch release event, cool, stop moving. If it&#8217;s a collision, is it a bullet? If so, take less damage than say a missile hitting. Is the bullet&#8217;s velocity higher? If so, take more damage than usual. This context is what allows the encapsulation to happen. You issue a message, provide context, and whoever gets it doesn&#8217;t necessarily HAVE to know where it came from; they&#8217;ll have enough information to know how to handle it.</p>
<p>For Corona DisplayObjects, this is easy. You just use dispatch an event. But for Model/data access objects, not so much. You don&#8217;t want the overhead of a DisplayObject to just to send messages, so you build your own. This implies another class/table with the capability of sending/receiving messages. This means your classes will have a dependency on this object. For example, if I want to test my Model class in a brand new main.lua, it&#8217;ll bring along/require the messaging class. This is a dependency. One of the threads (just like OOP, encapsulation, keeping things DRY, don&#8217;t optimize too early, etc) you want to keep in the back of your head is to keep the dependencies low. You don&#8217;t want a class to have too many dependencies. Like globals, dependencies can cause spaghetti code, hard to test &amp; debug situations, and overall just hard to manage code.</p>
<p>Corona makes the event dispatching dependency invisible with DisplayObjects because it&#8217;s built in. Not so for regular tables. Somehow, you have to put this dependency in every class. You can either create a public setter for it, and pass in an instance, or just reference a class globally in a base class. Both are a dependency, the latter just requires a lot less work and code.</p>
<p>Downside? It&#8217;s a dependency. You also force this implementation on everyone who wishes to utilize your class. If you make the messaging system events, 2 things happen. First, people using Corona get it because it&#8217;s the exact same API and functionality (excluding bubbling) that developers are used to. Secondly, it&#8217;s interchangeable and works with Corona DisplayObjects. The best solution would be to do Dependency Injection/Inversion of Controlâ€¦ but I haven&#8217;t figured out how to do this in Lua yet, and I&#8217;m not sure Lua supports metadata annotations. Considering it&#8217;s dynamic, you CAN inject things like this at runtime, but someone, somewhere has to do so. Why do so when every object requiring messaging needs the same mechanism? Thus, the pragmatic thing is to build it in.</p>
<p>Also, more importantly, DOES this messaging system add more performance overhead than using simple globals? To make the question harder to answer, can you make tighter coupling of your code and still get things done?</p>
<p>It&#8217;s been my experience, if you make things easier to use with less coupling, you&#8217;re more productive in the last 10% of your project. While coupling makes things easy in the beginning, it&#8217;s a farce; it has more than an exponential cost at the end.</p>
<p>Besides, you can always increase coupling easily; it&#8217;s removing coupling later that&#8217;s hard. If you need to optimize, great, you can. If not, great, no more work to do; you can instead focus on features. Usually, though, you&#8217;ll know pretty quick if you do iterative builds if a messaging system is making a huge performance impact on your game on not. The only surprises you&#8217;ll get is you spend days on something without a build. Do a small test, see if there is a noticeable difference. Sometimes you&#8217;ll have n-problems you won&#8217;t find till your game gets to a specific size which are unfortunate. An example is a charting component that works great building up to 5000 data points, but suddenly DRASTICALLY slows down beyond that.</p>
<p>These problems aren&#8217;t the fault of the API. If you take a step back, the &#8220;30,000ft view&#8221;, usually it&#8217;s the implementation that&#8217;s at fault, not the code itself.</p>
<p>For example, a little history lesson. Back when ActionScript 1 development was increasing in scope, we went through 4 different messaging systems. The first was the built-in one for Mouse and Keyboard, etc. It was only partially available; there wasn&#8217;t a MovieClip one. So, we used ASBroadcaster; an undocumented one inside of Flash Player. It had a known bug with removing a listener during a dispatch, and other things. Then Bokel released a version on top of that fixed it. Then Adobe created EventDispatcher, mirroring the ECMA one. They then built this into the Flash Player for Flash Player 9&#8217;s new virtual machine.</p>
<p>There were others that came out after ActionScript 3 was born. <a href="http://puremvc.org">PureMVC</a> had notifications in it for an easier port to other platforms &amp; languages. Robert Penner created <a href="http://flashblog.robertpenner.com/2009/09/my-new-as3-event-system-signals.html">Signals</a> for a light-weight, object poolable, quick to develop in C#-esque messaging system.</p>
<p>As you can see, why the bottleneck for most larger Flash &amp; Flex 1.x applications at the time was EventDispatcher, even when they built it into the runtime in C, developers opt-ed for a slower system built by themselves to solve different problems.</p>
<p>So why the continuous talk about performance questions in this section when I rail against premature optimization? Because messaging is the core of any app, or game. The choice you make is the largest impact on what you&#8217;re building, both from performance and from a development perspective. Yes, you can just use direct access to objects, or callbacks, but that&#8217;s not very encapsulated, nor DRY, and is a pain to re-factor later if you need. Messages via Events are more encapsulated, and less coupled, but have a performance impact. Additionally, only DisplayObjects use the internal C implementation; your own uses interpreted Lua with whatever JIT&#8217;ing/machine/voodoo conversion Corona does.</p>
<p>Traditionally, it&#8217;s easy to switch to events from callbacks, but not the other way around. While the performance impact isn&#8217;t that large to utilize a DisplayObject and use the built-in event messaging, based on some benchmarks, this isn&#8217;t a good idea to build upon.</p>
<p><strong>Mediation</strong></p>
<p>The third option is using the <a href="http://flexblog.faratasystems.com/2007/09/26/applying-the-mediator-design-pattern-in-flex">Mediator pattern</a>. Once you have 2 encapsulated objects that need to talk to each other, you utilize a class that handles the communication. It takes the message from ViewA and sends that to ViewB. When ViewB wishes to talk to ViewA, it sends the message and the Mediator relays it.</p>
<p>All the MVC/MVP articles go over A LOT about the different things a View should/should not do,Â particularlyÂ with it&#8217;s needs for data and how to show it. Regardless of the implementation, it&#8217;s generally understood that someone such as a Mediator or a Presenter handels the responses from a View. If it&#8217;s a Presenter, it&#8217;s a dependency in the View, and the View calls methods on it. This allows the actual logic behind both responding to View user gestures (like when I touch a button on the phone) to not muddy up the View (muddy up means TONS of code that has nothing to do with displaying graphics, putting into groups, setting up Sprite Sheets, etc), and allows you to test the behavior in isolation.</p>
<p>Mediator&#8217;s areÂ similar, although, the View has no idea he/she has a Mediator, and the Mediator has the View reference passed into it by someone else. Again, more encapsulation, yet SOMEONE has to have the burden of setting up this relationship. In ActionScript this is easy; Robotlegs just listens for the Event.ADDED_TO_STAGE/REMOVED_FROM_STAGE events and creates/destroys based on an internal hash/table. In Lua, you don&#8217;t have any DisplayObjects events, so you have to manually do it.</p>
<p>Either way, if you DON&#8217;T Mediate your View&#8217;s, you&#8217;ll eventually have a lot of code in there that has to &#8220;know&#8221; about other objects. This&#8217;ll be either a global reference, or a dependency&#8230; and we&#8217;ve already talked about why those things are bad to do. Additionally, tons of code in general is bad; having a View just focus on graphical things and emitting events people outside would care about while the logic can be put elsewhere makes it easier to manage. When you open a View class; you know pretty quickly what you&#8217;re looking at is just GUI specific code.</p>
<p>There&#8217;s another more important aspect of Mediation that isÂ similarÂ to messaging and that is system events that affect Application Logic.</p>
<p>For example, many things in a game care about a Player&#8217;s health.</p>
<ul>
<li>the Sprite that represents the player; it needs to show different graphics for how much health it has</li>
<li>a health bar at the top right of the screen that fills up with green the more health the player has</li>
<li>sounds that play when the player loses and gains health</li>
</ul>
<p>If you use globals, you&#8217;d have all 3 handled by the actual Player sprite class. It&#8217;d update it&#8217;s internal health and update the global variables. Those who have references to the globals would be informed when that value changes. Additionally, you&#8217;ve now wired them together if you do this. If you change one, you&#8217;ll break the other.</p>
<p>Using a Mediator allows:</p>
<ul>
<li>the player and the health bar both the capability to react to the change in the hit points in an encapsulated way. If you change how the Player and HealthBar look/work, the actual logic on how yo do that is centralized to either them, or their Mediators&#8230; and usually Mediators are like 1 line of actual code to change.</li>
<li>The application logic of how hit points are updated and changed to be done in 1 place. As your game grows and different enemies need to do different types of damage to your player, and sometimes react differently depending on how much health the player has, this is all done and updated in 1 place. It&#8217;s DRY, and easy to find where the logic bugs are.</li>
<li>A side effect of this is&#8230; the Mediator pattern (lolz). You can have View&#8217;s the capability of talking to each other without having tight coupling.</li>
</ul>
<p>The most important feature is solving the classic race condition of is the data ready for a View when he&#8217;s created, or is it null and he has to wait. Using Medaitors, you don&#8217;t have this problem. In the onRegister, you just set it if you have it on whatever Model(s) you need, else just wait for the Model(s) to be updated and inform the view.</p>
<p>&#8230;I wouldn&#8217;t say totally solved; handling &#8220;null&#8221; or &#8220;nil&#8221; is still a challenge for developers even in simple View&#8217;s. Those are good problems to have, though vs. race conditions.</p>
<p>If you enter the optimization phase of your game and want to remove events, use callbacks, and have hard-wired references, that&#8217;s fine if benchmarks truly identify that you need theÂ performanceÂ gains. Usually, though, Mediator communication isn&#8217;t your bottle neck, it&#8217;s collisions, lack of object-pooling, and how messages are handled.</p>
<p><strong>Quickie on Commands</strong></p>
<p>Commands are just formalized Controller logic. In fact, in other frameworks, they&#8217;re simply Controller classes with methods. They&#8217;re called &#8220;Commands&#8221; because they do 1 thing&#8230; and can potentially undo it. If you&#8217;ve ever used an Adobe Product, a few of them like Dreamweaver, Fireworks, Flash, and Photoshop will have a Command list, also called &#8220;History Panel&#8221;. In Flash and Fireworks, you can even get the code for these Commands. The line blurs here once you lump them all together, but in my experience, good Controllers have 2 things in common:</p>
<ol>
<li>They contain the only code in the application that updates the Models (update/delete in CRUD for internal data)</li>
<li>They contain all application logic&#8230; or at least share the burden with the Models.</li>
</ol>
<p>For #1, this is important in tracking down bugs and keeping your code DRY. You always know who&#8217;s changing your Player&#8217;s hit points, who&#8217;s actually applying your level up rewards, etc. If you can test your Models in isolation, and they&#8217;re good&#8230; then you know who to blame. This is good because again, they tend to often start by being 1 line functions with the potential to grow to 30 to 60&#8230; not a bad way to start life, nor grow. Small, readable code.</p>
<p>For #2, whether you have a Controller class function, or a Command, SOMEONE in your application needs to &#8220;load the level data&#8221; from your level editor. SOMEONE needs to handle the fact that your player just drank a health potion, but he&#8217;s also wearing a Ring of Health Boost + 2, and this positively affects the effects of the health potions she drinks. SOMEONE needs to handle calling the loadSaveGame service, ensuring it worked, and updating all the Models with theirÂ relevantÂ Memento data.</p>
<p>This orchestrator of pulling everyone together, to read multiple Models and &#8220;make decisions&#8221;, they&#8217;re the brains of your application. For performance reasons, a lot of Controller logic is often done directly in game views, even if it just references a Controller class for ensuring logic is somewhat DRY.</p>
<p>There&#8217;s a lot of loathing in the community by those with a moreÂ pragmaticÂ bent, or just on smaller code bases with shorter deadlines. The overhead associated with them completely negates their perceived value when you can just call a centralized Controller logic function via&#8230; a function call vs. some event that magically spawns some other class that has 1 function with a bunch of injected dependencies. Just depends in you read that last sentence and go &#8220;Makes sense to me, don&#8217;t see what the issue with it is&#8230; &#8221; or &#8220;w&#8230;t&#8230;f&#8230; why!?&#8221;.</p>
<p><strong>Conclusions</strong></p>
<p>Remember, the above is all complete bs. If you or your team have a way of building games that works for you, great. This is just helpful tool I&#8217;ve found in Flash &amp; Flex application development, and it seems to help me in Corona games, specifically around the GUI/HUD portions. I still have globals in my collision routines for speed purposes, hehe.</p>
<p>Additionally, it&#8217;s a great teaching tool, too. <a href="http://joelhooks.com">Joel Hooks</a> got someÂ similarÂ schlack like I did in using <a href="http://puremvc.org">PureMVC</a> when he was first starting out in Objective C for iPhone. Providing a comfortable &amp; familiar framework of development really helped him learn and have context how the new language &amp; platform work with certain concerns; it&#8217;s how he shipped his first app on the app store. Same with me in Corona&#8230; and game development.</p>
<p>Finally, this isn&#8217;t an all or nothing approach. You can just use it on the parts you need, or perhaps just to learn. I find its helped me learn a lot about Lua and Corona, as well as having theÂ flexiblyÂ to change the API of my Player and Enemies without affecting how the GUI itself around the game works. In true spirit of total disclosure, I&#8217;ll report on any adverse overhead if I find it.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://jessewarden.com/2011/08/why-robotlegs-for-games.html/feed</wfw:commentRss>
			<slash:comments>7</slash:comments>
		
		
			</item>
		<item>
		<title>Adding Dependency Injection to Cairngorm 2.x via SwiftSuspenders (or Robotlegs) for Middle Tier Mocking</title>
		<link>https://jessewarden.com/2011/05/adding-dependency-injection-to-cairngorm-2-x-via-swiftsuspenders-or-robotlegs-for-middle-tier-mocking.html</link>
					<comments>https://jessewarden.com/2011/05/adding-dependency-injection-to-cairngorm-2-x-via-swiftsuspenders-or-robotlegs-for-middle-tier-mocking.html#comments</comments>
		
		<dc:creator><![CDATA[JesterXL]]></dc:creator>
		<pubDate>Mon, 23 May 2011 13:27:41 +0000</pubDate>
				<category><![CDATA[Flex]]></category>
		<category><![CDATA[ActionScript]]></category>
		<category><![CDATA[architecture]]></category>
		<category><![CDATA[cairngorm]]></category>
		<category><![CDATA[dependency]]></category>
		<category><![CDATA[Flash]]></category>
		<category><![CDATA[injection]]></category>
		<category><![CDATA[robotlegs]]></category>
		<category><![CDATA[swiftsuspenders]]></category>
		<guid isPermaLink="false">http://jessewarden.com/?p=2699</guid>

					<description><![CDATA[Introduction The following discusses how to utilize Dependency Injection in the Cairngorm 2.x framework, explains why you&#8217;d want to do this, and shows the code you need. Included is a brief explanation of how you Mock or &#8220;fake&#8221; a backend until it&#8217;s ready so you can build your Flex app without waiting for the web [&#8230;]]]></description>
										<content:encoded><![CDATA[<p><span style="color: #000000;"><strong>Introduction</strong></span></p>
<p>The following discusses how to utilize Dependency Injection in the Cairngorm 2.x framework, explains why you&#8217;d want to do this, and shows the code you need. Included is a brief explanation of how you Mock or &#8220;fake&#8221; a backend until it&#8217;s ready so you can build your Flex app without waiting for the web services to be ready.</p>
<p><span id="more-2699"></span><strong>NOTE</strong>: I do not professionally recommend you do the following integration outlined in this article. Instead, I suggest you utilize <a href="http://robotlegs.org">Robotlegs</a> orÂ <a href="http://www.spicefactory.org/parsley/">Parsley</a> at the start of any Flex application of large size. They, and other frameworks of their ilk (<a href="http://swizframework.org/">Swiz</a>, <a href="http://puremvc.org/">PureMVC</a>, etc), have solved many glaring architecture problems Cairngorm has over the past 7 years. There is a reason <a href="http://opensource.adobe.com/wiki/display/cairngorm/Cairngorm+3">Cairngorm 3</a> is a bunch of good ideas, and not a framework. Adobe recommends you use Cairngorm 3 with one of the aforementioned frameworks.</p>
<p><strong>Context</strong></p>
<p>Your project uses Cairngorm 2.x. Your back-end services aren&#8217;t done yet. Your team has a lot of GUI code to write. Ya&#8217;ll cannot wait for the middle tier to be done to actually move forward. The way to solve this is to use Mocks; classes that fake your middle tier. They&#8217;ll take a few seconds to respond, use the same methods, dispatch the same events, and return real ValueObjects. This allows you to write real GUI and Application logic code without having to wait on your server to work. If you&#8217;re server works, and then it turns out to be premature (i.e. &#8220;That isn&#8217;t supposed to happen&#8230; worked for me&#8230;&#8221;), you can go back to your Mocks until it&#8217;s &#8220;really&#8221; ready.</p>
<p><strong>Mocking a Middle Tier</strong></p>
<p>The easiest way to do this strategy is via coding by contract and Dependency Injection. You code to interfaces instead of concrete implementations (you use ILoginService vs LoginService). Your injection rules then have a switch: &#8220;real&#8221; and &#8220;fake&#8221;. If real is turned on, you hit a real server. If fake is turned on instead, you don&#8217;t hit anything. Both take a few seconds (read, more than 1 frame), and both return real ValueObjects. The fake ones do this by hardcoding the return values to something that would commonly be returned.</p>
<p>Examples include faking a login. The MockLoginService will take a hardcoded username and password and return a hardcoded UserVO. The real LoginService will take any username and password, and return a UserVO if successfully logged in that the server gave it.</p>
<p>Both use the same API. Both dispatch the exact same Event(s). Both expose the same return values. The key is the both implement the same ILoginService interface. This allows your DI framework to create the service for you vs. using Boolean or Conditional Compilation flags everywhere.</p>
<p><strong>Example Login Service</strong></p>
<p>Here&#8217;s an example of a real Login Service, specifically a Cairngorm Business Delegate that is assumed to have a predefined remoting-config.xml that defines your BlazeDS/Java services, and you access via a ServicesLocator/Services Singleton.</p>
<pre lang="actionscript">package com.jxl.services
{
   import mx.rpc.IResponder;
   import mx.rpc.AsyncToken;
   import mx.rpc.Responder;
   import mx.rpc.events.FaultEvent;
   import mx.rpc.events.ResultEvent;
   import mx.rpc.remoting.Operation;
   import mx.rpc.remoting.RemoteObject;

   public class LoginService implements ILoginService
   {

      private var responder:IResponder;
      private var service:RemoteObject;

      public function LoginService(responder:IResponder):void
      {
         this.responder    = responder;
         this.service      = ServiceLocator.instance.getRemoteObject( "LoginService" );
      }

      public function login(username:String, password:String):void
      {
         var operation:Operation    = service.getOperation("login") as Operation;
         var responder:Responder    = new Responder(onResult, onFault);
         var token:AsyncToken       = operation.send(username, password);
         token.addResponder(responder);
      }

      private function onResult(event:ResultEvent):void
      {
         responder.result(event);
      }

      private function onFault(event:FaultEvent):void
      {
         responder.fault(event);
      }
   }
}</pre>
<p>Notice it takes your username and password, passes to the predefined service, and awaits a response from the passed in Responder.</p>
<p>Now here&#8217;s the fake one:</p>
<pre lang="actionscript">package com.jxl.services.mocks
{

   import flash.utils.setTimeout;

   import mx.rpc.IResponder;
   import mx.rpc.Responder;
   import mx.rpc.events.ResultEvent;

   public class MockLoginService implements ILoginService
   {

      private var responder:IResponder;

      public function MockLoginService(responder:IResponder):void
      {
         this.responder = responder;
      }

      public function login(username:String, password:String):void
      {
         setTimeout(onResult, 2 * 1000);
      }

      private function onResult():void
      {
         var fakeUser:UserVO    = new UserVO();
         fakeUser.firstName     = "Jesse";
         fakeUser.lastName      = "Warden";
         responder.result(new ResultEvent(ResultEvent.RESULT, false, true, fakeUser));
      }
   }
}</pre>
<p>It, too, implements the ILoginService, as well as dispatching the ResultEvent to the passed in Responder. Notice it creates a fake user, doesn&#8217;t care what you pass in, and uses a 2 second timer to emulate a server call. This seems trivial, but a lot of people coming to ActionScript for the first time from other blocking languages such as C++ or Java assume the server will respond in the same block/stack of code vs. waiting for an event. Using this timer helps surface such workflow issues early.</p>
<p>And the ILoginService interface both of the above implement:</p>
<pre>package com.jxl.services
{
   public interface ILoginService
   {
      function login(username:String, password:String):void;
   }
}</pre>
<p><strong>Using Boolean Constants</strong></p>
<p>Before Dependency Injection frameworks, you&#8217;d use Boolean config variables in some Constants file:</p>
<pre lang="actionscript">package
{
   public class Constants
   {
      public static const USE_MOCKS:Boolean = true;
   }
}</pre>
<p>And then implemented in your Cairngorm Command like so:</p>
<pre lang="actionscript">package com.jxl.commands
{
   import com.jxl.services.LoginService;
   import com.jxl.services.mocks.MockLoginService;
   import com.jxl.services.ILoginService;
   import com.jxl.models.LoginModel;
   import com.jxl.events.controller.LoginEvent;

   import com.adobe.cairngorm.commands.Command;
   import com.adobe.cairngorm.control.CairngormEvent;

   import mx.rpc.Responder;

   public class LoginCommand implements Command
   {
      private var responder:Responder;
      private var delegate:ILoginService;

      public function execute(event:CairngormEvent):void
      {
         responder                 = new Responder(onLoginSuccess, onLoginError);
         var loginEvent:LoginEvent = event as LoginEvent;

         if(Constants.USE_MOCKS == false)
         {
            delegate               = new LoginService(responder);
         }
         else
         {
            delegate               = new MockLoginService(responder);
         }

         delegate.login(loginEvent.username, loginEvent.password);
      }

      private function onLoginSuccess(event:ResultEvent):void
      {
         LoginModel.instance.loggedInUser = event.result as UserVO;
      }

      private function onLoginError(event:FaultEvent):void
      {
         trace("LoginCommand::onLoginError");
      }
   }
}</pre>
<p>There are 3 problems with the above approach.</p>
<ol>
<li>It&#8217;s all or nothing. Once you set the Constants&#8217; file USE_MOCKS variable to false, EVERYTHING is in production mode. A lot of times a critical service will go out of commission, or be updated. You don&#8217;t have the ability using the above to target specific Services/BusinessDelegates to be mocked, while the rest are still production.</li>
<li>QA will often request certain services fail intentionally while others succeed; using the above prevents you from giving QA that ability.</li>
<li>You have if/then&#8217;s everywhere. This can lead to code bloat, specifically in Commands that actually <a href="http://jessewarden.com/2007/08/10-tips-for-working-with-cairngorm.html">handle multiple events vs. single event types</a> (see Point #6)&#8230; or Commands that handle the service call chaining themselves (similarÂ to <a href="http://knowledge.robotlegs.org/discussions/questions/115-using-the-asynccommand-with-services-callbacks">Robotlegs AsyncCommand&#8217;s</a> that choose not to fork, but instead handle everything internally (+ rollback if needed).</li>
</ol>
<p><strong>Using Conditional Compilation</strong></p>
<p>Same as the above, but uses constants defined by the compiler to determine whether to even compile in certain code. Wherever you configure mxmlc, it&#8217;d look something like this:</p>
<pre lang="actionscript">-define=SERVICES::usemocks,true</pre>
<p>And then in your Cairngorm Command:</p>
<pre lang="actionscript">if(SERVICES::usemocks == false)
   delegate = new LoginService(responder);

if(SERVICES::usemocks == true)
   delegate = new MockLoginService(responder);</pre>
<p>Just as ghetto; you still have C-like #ifdef&#8217;s everywhere. Gross. Manual. Prone to error. Still globally set on or off; all or nothing. Additionally, requires you to configure the compiler vs. &#8220;just code&#8221;. More crud to setup, maintain, and ensure goes into your automated build configuration.</p>
<p><strong>Using Dependency Injection via SwiftSuspenders</strong></p>
<p>NOTE: You don&#8217;tÂ necessarilyÂ have to use <a href="https://github.com/tschneidereit/SwiftSuspenders/">SwiftSuspenders</a>, or even Robotlegs. I&#8217;m just using them in this example because I know them.</p>
<p>Dependency Injection, also know as Inversion of Control, or IoC is a way to have your dependencies injected into your class for you. It&#8217;s the &#8220;new &#8216;new'&#8221;. Instead of you going:</p>
<pre lang="actionscript">delegate = new LoginService(responder);</pre>
<p>This is done for you; you never write new Something again for your dependencies. Now generally, it&#8217;s fine to code to Concrete implementations. But hopefully, you can see how coding by contract (ie using ILoginService) above allows you to configure WHICH Login Service to use; the real one or the fake one.</p>
<p>This is where DI comes in. You configure that stuff in one place; globally, or on a case by case basis, usually using ActionScript. An example, this time using the same Constants variable and an already made SwiftSuspenders injector:</p>
<pre lang="actionscript">if(Constants.USE_MOCKS == false)
{
   injector.mapClass(ILoginService, LoginService);
}
else
{
   injector.mapClass(ILoginService, MockLoginService);
}</pre>
<p>As you can see, this accomplishes a few things.</p>
<p>First, it makes your configuration rules DRY. Instead of having if/then&#8217;s or SERVICES::usemocks everywhere, you do it all in one place/class. Second, you can choose to turn it off for specific services. Third, anywhere you utilize ILoginService, this injection rule will run, allowing you to use the same rules in unit tests (although you shouldn&#8217;t, hehe), and any other place you&#8217;re coding by contract. It also keeps your code concise; it&#8217;s just coding to the interface; it has no clue what real type it actually is (LoginService or MockLoginService).</p>
<p>For our purposes, this is perfect for setting up and configuring mocks. We can configure our entire application to use real services once they come online&#8230; or just 1 at a time, all in one place.</p>
<p><strong>DI in Cairngorm</strong></p>
<p>Cairngorm has aÂ prescribedÂ way of writing yourÂ serviceÂ layer (sort of&#8230; ok not really). Thus it&#8217;s implied you&#8217;ll be using BusinessDelegates to connect to your back end and get your data. Additionally, Cairngorm prescribes you utilize Commands to their interface to instantiate and utilize those Services/BusinessDelegates.</p>
<p>Cairngorm 2.x does not have a documented way of doing Dependency Injection. There is a <a href="http://www.springsource.org/extensions/se-springactionscript-as">SpringAS</a> adapter for CairngormÂ <a href="http://davidbuhler.org/">David Buhler</a> told me about on Facebook, but I haven&#8217;t investigated it myself.</p>
<p>There are 3 challenges you need to be aware of:</p>
<ol>
<li>Cairngorm is typically deployed as a SWC; a library. Thus, you don&#8217;t have access to the source to modify. You could, but this makes people nervous.</li>
<li>Cairngorm creates Commands internally in it&#8217;s FrontController.</li>
<li>BusinessDelegates utilize an IResponder for their constructors (by convention), which would require you to utilize constructor injection. While it&#8217;s supported, it&#8217;s confusing for people who haven&#8217;t done it before. Even so, mx.rpc.Responders in turn have a specific constructor only approach to creation. In short, it&#8217;s &#8220;just easier&#8221; to modify the convention of setting responders on BusinessDelegates after they are created via getter/setters vs. using <a href="https://gist.github.com/418821">Alan Shaw&#8217;s Factory injection rule modification</a>&#8230; and even that doesn&#8217;t work at the instance level where it&#8217;s most often inside of Commands anyway. More on this in a bit.</li>
</ol>
<p>So we can&#8217;t modify Cairngorm&#8217;s source code, we need to inject our dependencies manually into Cairngorm Commands, and we need to slightly modify the Cairngorm BusinessDelegate convention to use a public setter vs. a constructor parameter.</p>
<p>No problem. Here&#8217;s the 3 steps you need to follow.</p>
<p><strong>Step 1: Setup Your Injection Rules</strong></p>
<p>You need to setup your injection rules. Since I&#8217;m comfortable using SwiftSuspenders, and Robotlegs already does most of the hard work inside it&#8217;s Context class, I&#8217;ll just use that; I create a MainContext.as class that sets up my rules and instantiate it in my main Flex Application class.</p>
<p>Here&#8217;s the class (again, you&#8217;re welcome to use your own ActionScript DI library like Swiz/Parsely or any Guice/SpringÂ derivatives):</p>
<pre lang="actionscript">package
{
   import com.jxl.events.controller.AppEvent

   import flash.display.DisplayObjectContainer;

   import org.robotlegs.mvcs.Context;

   [Event(name="applicationReady", type="com.jxl.events.controller.AppEvent")]
   public class MainContext extends Context
   {
      public function MainContext(contextView:DisplayObjectContainer=null, autoStartup:Boolean=true)
      {
         super(contextView, autoStartup);
      }

      public override function startup():void
      {
         if(Constants.USE_MOCKS == false)
         {
            injector.mapClass(ILoginService, LoginService);
         }
         else
         {
            injector.mapClass(ILoginService, MockLoginService);
         }
         var appEvent:AppEvent = new AppEvent(AppEvent.APP_READY);
         appEvent.injector     = injector;
         dispatchEvent(appEvent);
      }
   }
}</pre>
<p><strong>Step 2: Give Cairngorm Injection Powers</strong></p>
<p>Most of the work in a Cairngorm application is done in Commands. This is where we&#8217;ll need to inject the majority of our dependencies.Â In Cairngorm, you extend its FrontController class to basically wire up CairngormEvents that are dispatched to run certain Commands. Internally, it&#8217;ll create &amp; execute these command classes for you. We need to override this behavior so we can inject our dependencies before the Command&#8217;s execute method is called. This implies the class that extends FrontController even has an injector, which it doesn&#8217;t.</p>
<p>So how do we go about it?</p>
<ol>
<li>Give your FrontController.as sub-class an injector public property.</li>
<li>give your FrontController an injector instance</li>
<li>override executeCommand to inject into the Command class</li>
</ol>
<p>You&#8217;ll notice in Step 1 I dispatch an &#8220;AppEvent&#8221; and attach the MainContext&#8217;s injector property. This is because the Cairngorm FrontController needs it, and MainContext makes that a protected property. Putting it on an event class allows us to know when it&#8217;s ready to use, and to smuggle it out of the class so others can use it.</p>
<p>First, make your public property addition to your FrontController sub-class:</p>
<pre lang="actionscript">public var injector:Injector;</pre>
<p>Second, set it. I do this in the Flex 4 Application class, like so:</p>
<pre lang="mxml">&lt;fx:Declarations&gt;
   &lt;jxl:MainContext contextView="{this}" applicationReady="onInjectionsReady(event)" /&gt;
   &lt;cairngorm:MainController /&gt;
&lt;/fx:Declarations&gt;

&lt;fx:Script&gt;&lt;![CDATA[
   private function onAppReady(event:AppReady):void
   {
      mainController.injector = event.injector;
   }
]]&gt;&lt;/fx:Script&gt;</pre>
<p>Third, override executeCommand in your FrontController sub-class. It looks like this:</p>
<pre lang="actionscript">protected function executeCommand( event : CairngormEvent ) : void
{
   var commandToInitialise : Class = getCommand( event.type );
   var commandToExecute : ICommand = new commandToInitialise();

   commandToExecute.execute( event );
}</pre>
<p>Make it look like this:</p>
<pre lang="actionscript">protected override function executeCommand( event : CairngormEvent ) : void
{
   var commandToInitialise : Class = getCommand( event.type );
   var commandToExecute : ICommand = new commandToInitialise();
   injector.injectInto(commandToExecute);
   commandToExecute.execute( event );
}</pre>
<p>&nbsp;</p>
<p><strong>Step 3: Implement Your Commands &amp; BusinessDelegates</strong></p>
<p>First, here&#8217;s our modified LoginCommand. Notice 3 things. First, the delegate is now a public variable that has the [Inject] tag on top; it must be public otherwise the [Inject] tag won&#8217;t work. Second, notice we don&#8217;t instantiate delegate; we just assume (rightly so) it&#8217;s already instantiated. Third, and most important; we&#8217;re setting the responder directly on the Delegate vs. putting it in the constructor like a lot of Cairngorm examples do.</p>
<p>Remember, whether we&#8217;re using Mocks or a real server, the Command will stay the exact same.</p>
<pre lang="actionscript">package com.jxl.commands
{
   import com.jxl.services.LoginService;
   import com.jxl.services.mocks.MockLoginService;
   import com.jxl.services.ILoginService;
   import com.jxl.models.LoginModel;
   import com.jxl.events.controller.LoginEvent;

    import com.adobe.cairngorm.commands.Command;
    import com.adobe.cairngorm.control.CairngormEvent;

    import mx.rpc.Responder;

    public class LoginCommand implements Command
    {
      [Inject]
      public var delegate:ILoginService;

      public function execute(event:CairngormEvent):void
        {
         var loginEvent:LoginEvent = event as LoginEvent;

         delegate.responder = new Responder(onLoginSuccess, onLoginError);
         delegate.login(loginEvent.username, loginEvent.password);
        }

      private function onLoginSuccess(event:ResultEvent):void
      {
         LoginModel.instance.loggedInUser = event.result as UserVO;
      }

      private function onLoginError(event:FaultEvent):void
      {
         trace("LoginCommand::onLoginError");
      }
    }
}</pre>
<p>Second, just modify your BusinessDelegates on how they get IResponders. So, instead of this:</p>
<pre lang="actionscript">private var responder:IResponder;
private var service:RemoteObject;

public function LoginService(responder:IResponder):void
{
   this.responder = responder;
   this.service = ServiceLocator.instance.getRemoteObject( "LoginService" );
}</pre>
<p>&#8230;do this:</p>
<pre lang="actionscript">public var responder:IResponder;
private var service:RemoteObject;

public function LoginService():void
{
   this.service = ServiceLocator.instance.getRemoteObject( "LoginService" );
}</pre>
<p>Now, I&#8217;m one of those people who hates useless getter/setters to that don&#8217;t actually DO anything. That said, you can put getter/setters in interfaces to ensure your BusinessDelegates follow the contract. Up to you; find a convention you like.</p>
<p>&#8230;or just do constructor injection.</p>
<p><strong>Conclusions</strong></p>
<p>I&#8217;ve used Mocks on 3 projects now, 1 small, and 2 large and it has significantly improved my teams velocity in all 3 instances. Usually the person setting up the Mocks tends to be a bottleneck for a day or so, but once in place (and assuming you have some idea of the ValueObjects you need), your team can start moving immediately regardless of the state of your server.</p>
<p>This is helpful in Design Agency work where deadlines are non-negotiable, and the server team is just as stressed as you are. It&#8217;s useful in Enterprise situationsÂ especiallyÂ where you might not have a working server + services + production-like testing environment for 5 Sprints. That&#8217;s at least 3 months with NO dependable services. I&#8217;ve seen it take way longer than that, as well.</p>
<p>Keep in mind too that if there are no injection rules defined, noting will happen. This is important if you&#8217;re converting an existing code base and want to help remove some of the dependencies from it. You can lay your DI framework on top, and Cairngorm wil still work the same. This is nice in that some Cairngorm code bases are some of the largest Flex code bases known to man (IÂ guaranteeÂ you right now someÂ CorvetteÂ drivingÂ ParsleyÂ proponent is claiming his is bigger).</p>
<p>Remember, you just: Setup your injection rules, give the FrontController an injector, and override executeCommand to use that injector to inject into the Command classes for their dependencies. The rest is convention.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://jessewarden.com/2011/05/adding-dependency-injection-to-cairngorm-2-x-via-swiftsuspenders-or-robotlegs-for-middle-tier-mocking.html/feed</wfw:commentRss>
			<slash:comments>8</slash:comments>
		
		
			</item>
	</channel>
</rss>
