<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" media="screen" href="/~d/styles/rss2full.xsl"?><?xml-stylesheet type="text/css" media="screen" href="http://feeds.feedburner.com/~d/styles/itemcontent.css"?><rss xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:sy="http://purl.org/rss/1.0/modules/syndication/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/" xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" version="2.0">

<channel>
	<title>Ext JS, Flex, and Flash Consultant - Jesse Warden</title>
	
	<link>http://jessewarden.com</link>
	<description>A blog on consulting, software development, and gaming.</description>
	<lastBuildDate>Wed, 04 Apr 2012 14:09:37 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" type="application/rss+xml" href="http://feeds.feedburner.com/jessewarden" /><feedburner:info uri="jessewarden" /><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="hub" href="http://pubsubhubbub.appspot.com/" /><item>
		<title>Consulting Chronicles #7: The Priority Pyramid</title>
		<link>http://feedproxy.google.com/~r/jessewarden/~3/PBsAU2FxqFY/consulting-chronicles-7-the-priority-pyramid.html</link>
		<comments>http://jessewarden.com/2012/04/consulting-chronicles-7-the-priority-pyramid.html#comments</comments>
		<pubDate>Wed, 04 Apr 2012 14:09:37 +0000</pubDate>
		<dc:creator>JesterXL</dc:creator>
				<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, &#8230; <a href="http://jessewarden.com/2012/04/consulting-chronicles-7-the-priority-pyramid.html">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p><img 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&#8242;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 &#8216;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>
<img src="http://feeds.feedburner.com/~r/jessewarden/~4/PBsAU2FxqFY" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://jessewarden.com/2012/04/consulting-chronicles-7-the-priority-pyramid.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://jessewarden.com/2012/04/consulting-chronicles-7-the-priority-pyramid.html?utm_source=rss&amp;utm_medium=rss&amp;utm_campaign=consulting-chronicles-7-the-priority-pyramid</feedburner:origLink></item>
		<item>
		<title>Consulting Chronicles #6: Refactoring</title>
		<link>http://feedproxy.google.com/~r/jessewarden/~3/m8ONvxMgRcg/consulting-chronicles-6-refactoring.html</link>
		<comments>http://jessewarden.com/2012/04/consulting-chronicles-6-refactoring.html#comments</comments>
		<pubDate>Tue, 03 Apr 2012 14:50:09 +0000</pubDate>
		<dc:creator>JesterXL</dc:creator>
				<category><![CDATA[Flex]]></category>
		<category><![CDATA[chronicles]]></category>
		<category><![CDATA[consulting]]></category>
		<category><![CDATA[consultingchronicles]]></category>
		<category><![CDATA[refactoring]]></category>

		<guid isPermaLink="false">http://jessewarden.com/?p=3080</guid>
		<description><![CDATA[Introduction Refactoring is the discipline of applying a multitude of small, low-risk techniques to a code base in order fix and improve it. While corroborated by the software community, employing such techniques in a consulting context can be challenging because &#8230; <a href="http://jessewarden.com/2012/04/consulting-chronicles-6-refactoring.html">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p><img style="padding-right: 8px;" src="http://jessewarden.com/archives/blogentryimages/refactoring-4.3.2012.jpg" alt="Refactoring" width="320" height="240" align="left" /><strong>Introduction</strong></p>
<p>Refactoring is the discipline of applying a multitude of small, low-risk techniques to a code base in order fix and improve it. While corroborated by the software community, employing such techniques in a consulting context can be challenging because people are involved, often in a negative situation.</p>
<p>You need 2 weapons to win the refactoring battle. First, you need to understand what refactoring techniques are at your disposal and how to implement them. Below, I&#8217;ve listed the core ones I see needed time and time again. Second, you need to have a plan on how you engage the client company and their employees to allow you to do the first. That&#8217;s covered in the next article.</p>
<p><span id="more-3080"></span>I&#8217;ve talked about how you do various parts of these initiatives in previous articles. What I want to talk about today is 1 of the 2 things: The core things you need to be concerned about in refactoring. In the next article we&#8217;ll talk about a prioritized plan you should follow when engaging a client where refactoring is needed. These are aimed at being used in the worst situations, but can provide positive benefits in benign or benevolent situations as well.</p>
<p>You should be able to take this blog post and the next, and from them both progressively improve a poor quality code base as well as engage a challenging client amongst challenging circumstances.</p>
<p><strong>Note On Languages</strong></p>
<p>I&#8217;ve intermingled JavaScript, ActionScript, and Lua to help provide a variety of examples, show this list is technology agnostic, and provide corroboration of techniques across technologies. That and I miss coding Lua since I&#8217;ve been so busy and needed an excuse. This does have a strong focus with front-end languages, namely those which run in a browser.</p>
<p><strong>Nomenclature</strong></p>
<p><strong>Factory/Decoder/Parsing</strong>: Taking any kind of data, such as JSON or XML, and converting  into something you need it for. This could be as simple as accessing properties on it to converting it to a completely different type of object, or even creating new objects from it.</p>
<p><strong>Coding Conventions</strong></p>
<ul>
<li><strong>Factory Errors vs. Null</strong>: Below, I&#8217;m using both error and null. Error means if a Factory/function/decoder fails in anyway to understand its data, you throw an error. This helps in unit testing, and expose errors early in the weakest part of a front end application; those that utilize non-strongly typed data. Optionally, when you find a parsing error, you return null instead. Consumers of the Factory must test for null, but you mitigate runtime exceptions and expose faulty consumers. I like using both, but it&#8217;s a lot of work to be sure.</li>
<li><strong>Don&#8217;t Create Grenades</strong>: Regardless of language, <a href="http://jessewarden.com/2009/06/error-handling-in-actionscript-3-dont-make-grenades-or-how-to-not-crash-safari.html">you shouldn&#8217;t create grenades</a>. This means don&#8217;t use throw/error. Instead, dispatch a custom error event that is opt-in. Consumers shouldn&#8217;t have to worry about the code they&#8217;re using bubbling up problems to their area of worry unless they&#8217;ve opted into those concerns. ActionScript, JavaScript, and Lua also don&#8217;t have a strongly typed ways to verify with the compiler that these contracts have been met, unlike Java&#8217;s throwable. Thus, don&#8217;t throw, inform to those who wish to know. Log regardless.</li>
<li><strong>Factory vs. VO Self Parsing</strong>: Some like Factory&#8217;s to parse external data (JSON/XML, etc.) into ValueObjects for an increased likehood of DRY code (shared parsing code that&#8217;s easier to unit test). Others like ValueObjects to serialize/deserialize themselves to reduce coding overhead as well as make the API easier to use. I&#8217;ve used both below, but I&#8217;ve found this is usually a team decision and also depends on how complex your VO&#8217;s are.</li>
<li><strong>Model vs. Command vs. Remote Proxy</strong>: From architecture perspective, some people prefer to have a Model handle Application Data, and a Command/Controller/Presenter handle remote Service calls to update that data. Some prefer wrapping both inside of a Remote Proxy (basically a Model that has serivce(s) inside it), and allowing Controllers/Mediators/Presenters/ViewControllers to make calls on those Remote Proxies. I use both Model &amp; Commands below, but no Remote Proxies. It&#8217;s up to you and your team which you think is best. If you&#8217;ve gotten this far in the discussion, you&#8217;re clearly better off than most. The point here is solve for Model and/or Application logic encapsulation.</li>
<li><strong>try/catch</strong>: I use try/catch liberally. Developers concerned about performance, such as game developers or those using complicated parsing algorithms should take note the significant performance cost of try/catch as well as liberal use of <a href="http://martinfowler.com/refactoring/catalog/extractMethod.html">ExtractMethod</a>. This article assumes the code is in bad shape and you/your team needs to refactor it over many months to ensure your team can prevent fire drills, meet milestones, and start to build a firm foundation. If the code base has the following problems outlined in this article, your first order of business should be fixing them first before you start optimizing. If you really need performance, just use unit tests instead and pray.</li>
<li><strong>Singletons</strong>: While not a replacement for global variables, and generally frowned upon, well written ones are a good first step if they have access control and utilize strong-typing. (ex Model).</li>
</ul>
<p><strong>Refactoring Basics</strong></p>
<p>Improving existing code can be done in 3 ways: handling exceptions, using a good architecture, using strong-typing if available, and following refactoring paths. The reason you use refactoring, especially in a consulting/contracting context with existing code bases is that you&#8217;re not allowed to rewrite them from scratch. Thus an unwritten bequeathment of responsibility occurs between the code base and you: it now becomes your problem. Its failings become your failings. The insecurity it gives your client now has them project that insecurity, and responsibility to remedy it, onto you.</p>
<p>I&#8217;m assuming you&#8217;ve already done a code review by this point to ensure you, or your firm, want to even get involved. If you don&#8217;t but are still here, it&#8217;s probably because they&#8217;re paying you a lot of money to wallow in their mess. In that case, welcome to the suck.</p>
<p>The original <a href="http://martinfowler.com/refactoring/">definition of refactoring</a>, referring to Martin Fowlers here, is making a small, positive change that has low inherent risk. This is done to ensure you don&#8217;t break anything. The theory is, over time if you make enough positive changes, you&#8217;ll make the whole code base positive.</p>
<p>Life is more complex than that, but the point here is that you use refactoring to affect positive change without breaking the code and looking like an idiot in front of your client and ticking off their customers. You <strong>do not</strong> make large, sweeping changes to the code base, even if they are needed. Take it slow and steady, 1 little change at a time. Some of the examples below are small (such as using strong-typing in place of Object and *), and some are larger (such as modifying your Model layer) are larger. Sometimes such changes you need help in tackling because it&#8217;s sphaghetti code; team refactoring can be invigorating and you get a lot more done, so don&#8217;t think you have to do this on your own.</p>
<p>When in doubt, make a small, positive change. If you take more than 3 days to make a change, abort.</p>
<p><strong>Exceptions</strong></p>
<p>Your first priority in refactoring should be handling exceptions or errors. It&#8217;s ok if you see how sausage is made in the meat factory, but it&#8217;s <a href="http://www.msnbc.msn.com/id/46926159/ns/business-us_business/#.T3pMl6sS3vI">not ok</a> if your client does. You can turn explosive bedlam into a controlled spectacle. That&#8217;s right, things breaking can be made into looking like your in total control. Magic isn&#8217;t magic; it&#8217;s sleight of hand through distraction.</p>
<blockquote><p>&#8220;Look at this pretty logging window created by our company to handle such situations. All errors are now known to us, when and where they happen. This awesome ability to report said errors amongst your staff, not just QA, but you, your customers&#8230; everyone, even while in production! No surprises or fire drills here&#8230; ALL at no extra charge.&#8221;</p></blockquote>
<p>But how do we get there? Let&#8217;s start at bottom.</p>
<p>A lot of programming languages execute functions or methods in 2 modes: protected or omg-it-might-blow-up-we&#8217;re-hardcore mode. JavaScript/CoffeeScript, ActionScript, and Java for example use try/catch. Ruby uses begin &amp; rescue. Python uses try/except. Lua uses pcall. Most languages have various ways to ensure that if code explodes, it&#8217;s done so in a controlled fashion. Additionally, some have global exception handling as well.</p>
<p>Exceptions are the first area of uncontrolled chaos that must be contained. No controlled refactoring can take place without tackling these areas first.</p>
<p><strong>Architecture</strong></p>
<p>Architecture comes into play for large code bases, although, using it for small code bases can help you learn (albeit hard to appreciate as it&#8217;ll often get in your way of getting r done).</p>
<p>Architecture refers to how an application is built. It&#8217;s usually an amalgamation of design patterns used in a common way. For the sake of this article, we&#8217;re using architecture in a small sense of the word in helping move parts of the code to be more encapsulated, make things that break easier to identify, test in isolation, that sort of thing. While references to MVC/MVP/MVVM can get really esoteric and subjective, we&#8217;re not concerned with that.</p>
<p>What you need to verify with defining &#8220;good architecture&#8221; for you and your team is how it works, agree on approach, and ensure it helps you test things in isolation. If y&#8217;all agree, can be independently productive, and if something breaks you know where&#8230; that&#8217;s good architecture. Don&#8217;t get hung up on the definitions, get hung up on the contract on how things talk to each other, and that your team all agrees on that contract. This&#8217;ll come into play later in the next article regarding team synergy.</p>
<p><strong>Strong Typing</strong></p>
<p>Not much to say here. Don&#8217;t use Object/*/Dictionary. If you do, wrap it with a strongly typed API or unit tests. Putting the burden on the consumer of those objects leads to lots of code. Lots of code == bad.</p>
<p>Don&#8217;t do this:</p>

<div class="wp_syntax"><div class="code"><pre class="actionscript" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">var</span> person:<span style="color: #0066CC;">Object</span> = <span style="color: #66cc66;">&#123;</span><span style="color: #66cc66;">&#125;</span>;
person.<span style="color: #006600;">firstName</span> = <span style="color: #ff0000;">&quot;Jesse&quot;</span>;
person.<span style="color: #006600;">lastName</span> = <span style="color: #ff0000;">&quot;Warden&quot;</span>;</pre></div></div>

<p>Do this:</p>

<div class="wp_syntax"><div class="code"><pre class="actionscript" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">class</span> PersonVO
<span style="color: #66cc66;">&#123;</span>
   <span style="color: #0066CC;">public</span> <span style="color: #000000; font-weight: bold;">var</span> firstName:<span style="color: #0066CC;">String</span>;
   <span style="color: #0066CC;">public</span> <span style="color: #000000; font-weight: bold;">var</span> lastName:<span style="color: #0066CC;">String</span>;
<span style="color: #66cc66;">&#125;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">var</span> person:PersonVO = <span style="color: #000000; font-weight: bold;">new</span> PersonVO<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
person.<span style="color: #006600;">firstName</span> = <span style="color: #ff0000;">&quot;Jesse&quot;</span>;
person.<span style="color: #006600;">lastName</span> = <span style="color: #ff0000;">&quot;Warden&quot;</span>;</pre></div></div>

<p>When you don&#8217;t have strong-typing (JavaScript/CoffeeScript/Lua), <a href="http://jessewarden.com/archives/pix/moar-unit-tests-jxl.jpg">#moarUnitTests</a>. For JavaScript use <a href="http://jshint.com">jshint</a>, <a href="http://jslint.com">jslint</a>, and annotations that various frameworks use to infer type like Google&#8217;s Closure compiler for great justice.</p>
<p><strong>Refactoring Paths</strong></p>
<p>Beyond the suggestions below + mentioned resources, you have to use your own intuition. Refactorings on their own are good but when done as a team effort in strategic areas, you can make greater headway, earn more trust from your client, and do more &#8220;relevant&#8221; refactoring.</p>
<p>There are some things you&#8217;ll know are right such as investing in a good GUI logger, making friends with IT, etc. Others, on what to fix first, how to support dual architectures in some areas, and how to portray transparency to your client&#8230; some of those are just experience. When in doubt, go with your gut. The less code of the choices, the better.</p>
<p>A good refactoring path allows you the ability to code right now, satisfy non-programmers for trust earning, with assurance you haven’t coded yourself into a corner. It&#8217;s like a good marriage: compromise.</p>
<p>You&#8217;ll lose some battles. The goal is to win the war.</p>
<p>You&#8217;ll have detractors such as who don&#8217;t have their Code License; knowing the rules before breaking them&#8230; or some who are just afraid. Some are ivory tower zealots who aren&#8217;t punished for getting nothing done (some are rewarded). Some have emotional scars from attempting to fix things, and are hesitant to do what&#8217;s right. This is usually when they know the value but cannot effectively articulate it to stakeholders (this is called a &#8220;software developer&#8221;). Some are just insecure and don&#8217;t believe in their own refactoring ability and thus hold you back as well (<a href="http://en.wikipedia.org/wiki/DISC_assessment">low D on DISC</a>). Some think you&#8217;re full of it.</p>
<p>Refactoring is temporal. You are creating a positive change to last for awhile&#8230; but not forever. It&#8217;s ok to refactor something, then refactor it again later as long as you&#8217;re actually making an improvement upon a problem. If a ship is taking on water, the first thing you do is plug the holes with wooden spikes. Later, when the French stop firing at you and your hangover is gone from drinking all the wine you found on their now apprehended ship, you can plug the holes proper with a leather &amp; tar mixture. Then once in dry dock, replace the planks.</p>
<p>Architecture is not temporal&#8230; but can be as well. You&#8217;re supposed to establish rules and guidelines on how you approach a code base. Sometimes, however, you can jury-rig a solution to hit some deadline, or get a build out the door for some managerial milestone. Later, you can re-assess. Sometimes, you&#8217;re initial hack is controlled; meaning you are writing throwaway code on purpose. In doing so, you can make it easier to fix later.</p>
<p>Architecture is generally decided upon by the team, and you move forward for the length of the project on it.</p>
<p>Refactoring is a strategy that can change daily.</p>
<p><strong>Step #1: Exceptions</strong></p>
<p><strong>Case</strong>: Service layer has 3 failure points: entry, error, and exit parsing.<br />
<strong>Solution</strong>: Validate post data, log error, wrap parsing/factory/decoding.<br />
<strong>Language</strong>: JavaScript using <a href="http://amplifyjs.com">AmplifyJS</a></p>
<p><strong>Bad Code</strong>:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;">amplify.<span style="color: #660066;">request</span>.<span style="color: #660066;">decoders</span>.<span style="color: #660066;">appEnvelope</span> <span style="color: #339933;">=</span>
    <span style="color: #003366; font-weight: bold;">function</span> <span style="color: #009900;">&#40;</span> data<span style="color: #339933;">,</span> <span style="color: #000066;">status</span><span style="color: #339933;">,</span> xhr<span style="color: #339933;">,</span> success<span style="color: #339933;">,</span> error <span style="color: #009900;">&#41;</span>
    <span style="color: #009900;">&#123;</span>
        <span style="color: #000066; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span> data.<span style="color: #000066;">status</span> <span style="color: #339933;">===</span> <span style="color: #3366CC;">&quot;success&quot;</span> <span style="color: #009900;">&#41;</span>
        <span style="color: #009900;">&#123;</span>
            success<span style="color: #009900;">&#40;</span> data.<span style="color: #660066;">data</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #009900;">&#125;</span> <span style="color: #000066; font-weight: bold;">else</span> <span style="color: #000066; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span> data.<span style="color: #000066;">status</span> <span style="color: #339933;">===</span> <span style="color: #3366CC;">&quot;fail&quot;</span> <span style="color: #339933;">||</span> data.<span style="color: #000066;">status</span> <span style="color: #339933;">===</span> <span style="color: #3366CC;">&quot;error&quot;</span> <span style="color: #009900;">&#41;</span>
        <span style="color: #009900;">&#123;</span>
            error<span style="color: #009900;">&#40;</span> data.<span style="color: #660066;">message</span><span style="color: #339933;">,</span> data.<span style="color: #000066;">status</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #009900;">&#125;</span> <span style="color: #000066; font-weight: bold;">else</span> <span style="color: #009900;">&#123;</span>
            error<span style="color: #009900;">&#40;</span> data.<span style="color: #660066;">message</span> <span style="color: #339933;">,</span> <span style="color: #3366CC;">&quot;fatal&quot;</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #009900;">&#125;</span>
    <span style="color: #009900;">&#125;</span><span style="color: #339933;">;</span>
&nbsp;
amplify.<span style="color: #660066;">request</span>.<span style="color: #660066;">define</span><span style="color: #009900;">&#40;</span> <span style="color: #3366CC;">&quot;decoderExample&quot;</span><span style="color: #339933;">,</span> <span style="color: #3366CC;">&quot;ajax&quot;</span><span style="color: #339933;">,</span> <span style="color: #009900;">&#123;</span>
    url<span style="color: #339933;">:</span> <span style="color: #3366CC;">&quot;http://server.com/service/doSomething/&quot;</span><span style="color: #339933;">,</span>
    type<span style="color: #339933;">:</span> <span style="color: #3366CC;">&quot;POST&quot;</span><span style="color: #339933;">,</span>
    decoder<span style="color: #339933;">:</span> <span style="color: #3366CC;">&quot;appEnvelope&quot;</span>
<span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
amplify.<span style="color: #660066;">request</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#123;</span>
    resourceId<span style="color: #339933;">:</span> <span style="color: #3366CC;">&quot;decoderExample&quot;</span><span style="color: #339933;">,</span>
    success<span style="color: #339933;">:</span> <span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span> data <span style="color: #009900;">&#41;</span>
    <span style="color: #009900;">&#123;</span>
        data.<span style="color: #660066;">foo</span><span style="color: #339933;">;</span> <span style="color: #006600; font-style: italic;">// bar</span>
    <span style="color: #009900;">&#125;</span><span style="color: #339933;">,</span>
    error<span style="color: #339933;">:</span> <span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span> message<span style="color: #339933;">,</span> level <span style="color: #009900;">&#41;</span>
    <span style="color: #009900;">&#123;</span>
        <span style="color: #000066;">alert</span><span style="color: #009900;">&#40;</span> <span style="color: #3366CC;">&quot;always handle errors with alerts.&quot;</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p><strong>Refactored Code</strong>:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #006600; font-style: italic;">/*
Our decoder function is now:
1. shielded from bad data
2. assumes the response not well formed from the get go
3. logs each parsing error separately for easier diagnosis
*/</span>
&nbsp;
<span style="color: #006600; font-style: italic;">// modified appEnvelope decoder function</span>
<span style="color: #003366; font-weight: bold;">function</span> <span style="color: #009900;">&#40;</span> data<span style="color: #339933;">,</span> <span style="color: #000066;">status</span><span style="color: #339933;">,</span> xhr<span style="color: #339933;">,</span> success<span style="color: #339933;">,</span> error <span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
    <span style="color: #000066; font-weight: bold;">try</span>
    <span style="color: #009900;">&#123;</span>
        <span style="color: #000066; font-weight: bold;">if</span><span style="color: #009900;">&#40;</span>data <span style="color: #339933;">==</span> <span style="color: #003366; font-weight: bold;">null</span> <span style="color: #339933;">||</span> data <span style="color: #339933;">==</span> <span style="color: #3366CC;">&quot;&quot;</span><span style="color: #009900;">&#41;</span>
        <span style="color: #009900;">&#123;</span>
            error<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;Decoding error in parsing data.&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #009900;">&#125;</span>
        <span style="color: #000066; font-weight: bold;">else</span> <span style="color: #000066; font-weight: bold;">if</span><span style="color: #009900;">&#40;</span>data.<span style="color: #000066;">status</span> <span style="color: #339933;">==</span> <span style="color: #003366; font-weight: bold;">null</span> <span style="color: #339933;">||</span> data.<span style="color: #000066;">status</span> <span style="color: #339933;">!=</span> <span style="color: #3366CC;">&quot;&quot;</span><span style="color: #009900;">&#41;</span>
        <span style="color: #009900;">&#123;</span>
            error<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;Unknown status.&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #009900;">&#125;</span>
        <span style="color: #000066; font-weight: bold;">else</span> <span style="color: #000066; font-weight: bold;">if</span><span style="color: #009900;">&#40;</span>data.<span style="color: #660066;">message</span> <span style="color: #339933;">==</span> <span style="color: #003366; font-weight: bold;">null</span> <span style="color: #339933;">||</span> data.<span style="color: #660066;">message</span> <span style="color: #339933;">!=</span> <span style="color: #3366CC;">&quot;&quot;</span><span style="color: #009900;">&#41;</span>
        <span style="color: #009900;">&#123;</span>
            error<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;Uknown message.&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #009900;">&#125;</span>
        <span style="color: #000066; font-weight: bold;">else</span> <span style="color: #000066; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span> data.<span style="color: #000066;">status</span> <span style="color: #339933;">===</span> <span style="color: #3366CC;">&quot;success&quot;</span> <span style="color: #009900;">&#41;</span>
        <span style="color: #009900;">&#123;</span>
            success<span style="color: #009900;">&#40;</span> data.<span style="color: #660066;">data</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #009900;">&#125;</span>
        <span style="color: #000066; font-weight: bold;">else</span> <span style="color: #000066; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span> data.<span style="color: #000066;">status</span> <span style="color: #339933;">===</span> <span style="color: #3366CC;">&quot;fail&quot;</span> <span style="color: #339933;">||</span> data.<span style="color: #000066;">status</span> <span style="color: #339933;">===</span> <span style="color: #3366CC;">&quot;error&quot;</span> <span style="color: #009900;">&#41;</span>
        <span style="color: #009900;">&#123;</span>
            error<span style="color: #009900;">&#40;</span> data.<span style="color: #660066;">message</span><span style="color: #339933;">,</span> data.<span style="color: #000066;">status</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #009900;">&#125;</span>
        <span style="color: #000066; font-weight: bold;">else</span>
        <span style="color: #009900;">&#123;</span>
            error<span style="color: #009900;">&#40;</span> data.<span style="color: #660066;">message</span> <span style="color: #339933;">,</span> <span style="color: #3366CC;">&quot;fatal&quot;</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #009900;">&#125;</span>
    <span style="color: #009900;">&#125;</span>
    <span style="color: #000066; font-weight: bold;">catch</span><span style="color: #009900;">&#40;</span>e<span style="color: #009900;">&#41;</span>
    <span style="color: #009900;">&#123;</span>
       error<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;Decoding error.&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #006600; font-style: italic;">/*
Notice we:
1. Validate our requestData (you could do more than a null check) before making an actual service call.
2. Additionally, we log the failed request with the Service name and reason for easier diagnosis in a larger application.
*/</span>
&nbsp;
<span style="color: #000066; font-weight: bold;">if</span><span style="color: #009900;">&#40;</span>requestData <span style="color: #339933;">!=</span> <span style="color: #003366; font-weight: bold;">null</span><span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
    amplify.<span style="color: #660066;">request</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#123;</span>
        resourceId<span style="color: #339933;">:</span> <span style="color: #3366CC;">&quot;decoderExample&quot;</span><span style="color: #339933;">,,</span>
        data<span style="color: #339933;">:</span> requestData<span style="color: #339933;">,</span>
        success<span style="color: #339933;">:</span> <span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span> data <span style="color: #009900;">&#41;</span>
        <span style="color: #009900;">&#123;</span>
            data.<span style="color: #660066;">foo</span><span style="color: #339933;">;</span> <span style="color: #006600; font-style: italic;">// bar</span>
        <span style="color: #009900;">&#125;</span><span style="color: #339933;">,</span>
        <span style="color: #006600; font-style: italic;">/*
        Our request error handling now has:
        1. a log, vs. an alert, for logging our error
        2. a common logging signature for easier diagnosis in a larger application
        */</span>
        error<span style="color: #339933;">:</span> <span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span> message<span style="color: #339933;">,</span> level <span style="color: #009900;">&#41;</span>
        <span style="color: #009900;">&#123;</span>
            console.<span style="color: #660066;">error</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;MyService::error, message: &quot;</span> <span style="color: #339933;">+</span> message <span style="color: #339933;">+</span> <span style="color: #3366CC;">&quot;, level: &quot;</span> <span style="color: #339933;">+</span> level<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #009900;">&#125;</span>
    <span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
<span style="color: #000066; font-weight: bold;">else</span>
<span style="color: #009900;">&#123;</span>
    console.<span style="color: #660066;">error</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;MyService::error, requestData is null.&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p><strong>Case</strong>: Null values in GUI. View/GUI must assume data is not always good; must handle null without exploding.<br />
<strong>Solution</strong>: Check for null using if/then.<br />
<strong>Language</strong>: ActionScript 3</p>
<p><strong>Bad Code</strong>:</p>

<div class="wp_syntax"><div class="code"><pre class="actionscript" style="font-family:monospace;">myTextField.<span style="color: #0066CC;">text</span> = person.<span style="color: #0066CC;">name</span>;</pre></div></div>

<p><strong>Refactored Code</strong>:</p>

<div class="wp_syntax"><div class="code"><pre class="actionscript" style="font-family:monospace;"><span style="color: #808080; font-style: italic;">/*
We now:
1. check for a null VO first
2. if it is in fact null, we have a visual, conventional way of displaying null values w/o exploding.
3. if a property of the VO is null, that'll display as normal (in this case as an empty String)
*/</span>
&nbsp;
<span style="color: #b1b100;">if</span><span style="color: #66cc66;">&#40;</span>person<span style="color: #66cc66;">&#41;</span>
<span style="color: #66cc66;">&#123;</span>
   myTextField.<span style="color: #0066CC;">text</span> = person.<span style="color: #0066CC;">name</span>;
<span style="color: #66cc66;">&#125;</span>
<span style="color: #b1b100;">else</span>
<span style="color: #66cc66;">&#123;</span>
   myTextField.<span style="color: #0066CC;">text</span> = <span style="color: #ff0000;">&quot;???&quot;</span>;
<span style="color: #66cc66;">&#125;</span></pre></div></div>

<p><strong>Case</strong>: Global Exception Handling<br />
<strong>Solution</strong>: Add global handler that logs errors away from users to see.<br />
<strong>Language</strong>: ActionScript and JavaScript</p>
<p><strong>Refactored ActionScript Code</strong>:</p>

<div class="wp_syntax"><div class="code"><pre class="actionscript" style="font-family:monospace;">package
<span style="color: #66cc66;">&#123;</span>
   <span style="color: #0066CC;">import</span> flash.<span style="color: #006600;">display</span>.<span style="color: #006600;">Sprite</span>;
   <span style="color: #0066CC;">import</span> flash.<span style="color: #006600;">events</span>.<span style="color: #006600;">Event</span>;
   <span style="color: #0066CC;">import</span> flash.<span style="color: #006600;">events</span>.<span style="color: #006600;">UncaughtErrorEvent</span>;
&nbsp;
   <span style="color: #0066CC;">public</span> <span style="color: #000000; font-weight: bold;">class</span> ErrorHandling <span style="color: #0066CC;">extends</span> Sprite
   <span style="color: #66cc66;">&#123;</span>
      <span style="color: #0066CC;">public</span> <span style="color: #000000; font-weight: bold;">function</span> ErrorHandling<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>
      <span style="color: #66cc66;">&#123;</span>
         <span style="color: #0066CC;">super</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
         addEventListener<span style="color: #66cc66;">&#40;</span>Event.<span style="color: #006600;">ADDED_TO_STAGE</span>, onAdded<span style="color: #66cc66;">&#41;</span>;
      <span style="color: #66cc66;">&#125;</span>
&nbsp;
      <span style="color: #0066CC;">private</span> <span style="color: #000000; font-weight: bold;">function</span> onAdded<span style="color: #66cc66;">&#40;</span>event:Event<span style="color: #66cc66;">&#41;</span>:<span style="color: #0066CC;">void</span>
      <span style="color: #66cc66;">&#123;</span>
         loaderInfo.<span style="color: #006600;">uncaughtErrorEvents</span>.<span style="color: #006600;">addEventListener</span><span style="color: #66cc66;">&#40;</span>UncaughtErrorEvent.<span style="color: #006600;">UNCAUGHT_ERROR</span>, onUncaughtError<span style="color: #66cc66;">&#41;</span>;
      <span style="color: #66cc66;">&#125;</span>
&nbsp;
      <span style="color: #0066CC;">private</span> <span style="color: #000000; font-weight: bold;">function</span> onUncaughtError<span style="color: #66cc66;">&#40;</span>event:UncaughtErrorEvent<span style="color: #66cc66;">&#41;</span>:<span style="color: #0066CC;">void</span>
      <span style="color: #66cc66;">&#123;</span>
         <span style="color: #0066CC;">trace</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;Uncaught Error: &quot;</span> + event<span style="color: #66cc66;">&#41;</span>;
         <span style="color: #0066CC;">try</span>
         <span style="color: #66cc66;">&#123;</span>
            <span style="color: #808080; font-style: italic;">// note, fails in Asyncronous errors</span>
            <span style="color: #0066CC;">throw</span> <span style="color: #000000; font-weight: bold;">new</span> <span style="color: #0066CC;">Error</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;stack trace creator&quot;</span><span style="color: #66cc66;">&#41;</span>;
         <span style="color: #66cc66;">&#125;</span>
         <span style="color: #0066CC;">catch</span><span style="color: #66cc66;">&#40;</span><span style="color: #0066CC;">error</span>:<span style="color: #0066CC;">Error</span><span style="color: #66cc66;">&#41;</span>
         <span style="color: #66cc66;">&#123;</span>
            <span style="color: #0066CC;">trace</span><span style="color: #66cc66;">&#40;</span><span style="color: #0066CC;">error</span>.<span style="color: #006600;">getStackTrace</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>;
         <span style="color: #66cc66;">&#125;</span>
      <span style="color: #66cc66;">&#125;</span>
   <span style="color: #66cc66;">&#125;</span>
<span style="color: #66cc66;">&#125;</span></pre></div></div>

<p><strong>Refactored JavaScript Code</strong>:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #006600; font-style: italic;">// via http://stackoverflow.com/questions/951791/javascript-global-error-handling</span>
<span style="color: #006600; font-style: italic;">//</span>
<span style="color: #006600; font-style: italic;">// more techniques here for Opera/Safari older versions</span>
<span style="color: #006600; font-style: italic;">// http://stackoverflow.com/questions/645840/mimic-window-onerror-in-opera-using-javascript</span>
<span style="color: #006600; font-style: italic;">//</span>
<span style="color: #006600; font-style: italic;">// also note various browsers pass different arguments, and some suggest</span>
<span style="color: #006600; font-style: italic;">// handling existing handlers if they exist</span>
<span style="color: #006600; font-style: italic;">// https://developer.mozilla.org/en/DOM/window.onerror</span>
<span style="color: #006600; font-style: italic;">//</span>
<span style="color: #006600; font-style: italic;">// also note that the error in some browsers will still occur unless you handle it</span>
<span style="color: #006600; font-style: italic;">// a certain way; here we're returning true from the error handler to do so.</span>
&nbsp;
window.<span style="color: #000066;">onerror</span> <span style="color: #339933;">=</span> <span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
    <span style="color: #000066; font-weight: bold;">if</span><span style="color: #009900;">&#40;</span>arguments <span style="color: #339933;">&amp;</span>amp<span style="color: #339933;">;&amp;</span>amp<span style="color: #339933;">;</span> arguments.<span style="color: #660066;">length</span> <span style="color: #339933;">&amp;</span>amp<span style="color: #339933;">;&amp;</span>amp<span style="color: #339933;">;</span> arguments.<span style="color: #660066;">length</span> <span style="color: #339933;">&amp;</span>gt<span style="color: #339933;">;</span> <span style="color: #CC0000;">0</span><span style="color: #009900;">&#41;</span>
    <span style="color: #009900;">&#123;</span>
        <span style="color: #003366; font-weight: bold;">var</span> logStr <span style="color: #339933;">=</span> <span style="color: #3366CC;">&quot;&quot;</span><span style="color: #339933;">;</span>
        <span style="color: #003366; font-weight: bold;">var</span> len <span style="color: #339933;">=</span> arguments.<span style="color: #660066;">length</span><span style="color: #339933;">;</span>
        <span style="color: #000066; font-weight: bold;">for</span><span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">var</span> index <span style="color: #339933;">=</span> <span style="color: #CC0000;">0</span><span style="color: #339933;">;</span> index <span style="color: #339933;">&amp;</span>lt<span style="color: #339933;">;</span> len<span style="color: #339933;">;</span> index<span style="color: #339933;">++</span><span style="color: #009900;">&#41;</span>
        <span style="color: #009900;">&#123;</span>
            logStr <span style="color: #339933;">+=</span> <span style="color: #3366CC;">&quot;<span style="color: #000099; font-weight: bold;">\t</span>&quot;</span> <span style="color: #339933;">+</span> arguments<span style="color: #009900;">&#91;</span>index<span style="color: #009900;">&#93;</span> <span style="color: #339933;">+</span> <span style="color: #3366CC;">&quot;<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #339933;">;</span>
        <span style="color: #009900;">&#125;</span>
        console.<span style="color: #660066;">error</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;Global Error:<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span> <span style="color: #339933;">+</span> logStr<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
    <span style="color: #000066; font-weight: bold;">else</span>
    <span style="color: #009900;">&#123;</span>
        console.<span style="color: #660066;">log</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;Global Error&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
    <span style="color: #000066; font-weight: bold;">return</span> <span style="color: #003366; font-weight: bold;">true</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span><span style="color: #339933;">;</span></pre></div></div>

<p><strong>Step #2: Architecture</strong></p>
<p><strong>Case</strong>: Encapsulation of statefull, Model data.<br />
<strong>Solution</strong>: Encapsulate Setting of Model Data to single place (DRY)<br />
<strong>Language</strong>: Lua in Corona SDK</p>
<p><strong>Bad Code</strong>:</p>

<div class="wp_syntax"><div class="code"><pre class="lua" style="font-family:monospace;"><span style="color: #b1b100;">_G</span>.score <span style="color: #66cc66;">=</span> <span style="color: #cc66cc;">0</span>
&nbsp;
<span style="color: #b1b100;">local</span> scoreText <span style="color: #66cc66;">=</span> display.newText<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>
<span style="color: #b1b100;">function</span> updateScoreText<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>
   scoreText.text <span style="color: #66cc66;">=</span> <span style="color: #b1b100;">_G</span>.score
<span style="color: #b1b100;">end</span>
updateScoreText<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>
&nbsp;
<span style="color: #b1b100;">local</span> powerUp <span style="color: #66cc66;">=</span> display.newImage<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;powerup.png&quot;</span><span style="color: #66cc66;">&#41;</span>
powerUp.name <span style="color: #66cc66;">=</span> <span style="color: #ff0000;">&quot;powerUp&quot;</span>
&nbsp;
<span style="color: #b1b100;">local</span> enemy <span style="color: #66cc66;">=</span> display.newImage<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;enemy.png&quot;</span><span style="color: #66cc66;">&#41;</span>
enemy.name <span style="color: #66cc66;">=</span> <span style="color: #ff0000;">&quot;enemy&quot;</span>
<span style="color: #b1b100;">function</span> enemy:collision<span style="color: #66cc66;">&#40;</span>event<span style="color: #66cc66;">&#41;</span>
   <span style="color: #b1b100;">if</span> event.phase <span style="color: #66cc66;">==</span> <span style="color: #ff0000;">&quot;began&quot;</span> <span style="color: #b1b100;">then</span>
      <span style="color: #b1b100;">if</span> event.target.name <span style="color: #66cc66;">==</span> <span style="color: #ff0000;">&quot;bullet&quot;</span> <span style="color: #b1b100;">then</span>
         <span style="color: #b1b100;">_G</span>.score <span style="color: #66cc66;">=</span> <span style="color: #b1b100;">_G</span>.score + <span style="color: #cc66cc;">1</span>
      <span style="color: #b1b100;">end</span>
   <span style="color: #b1b100;">end</span>
<span style="color: #b1b100;">end</span>
enemy:addEventListener<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;collision&quot;</span>, enemy<span style="color: #66cc66;">&#41;</span>
&nbsp;
<span style="color: #b1b100;">local</span> ship <span style="color: #66cc66;">=</span> display.newImage<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;ship.png&quot;</span><span style="color: #66cc66;">&#41;</span>
<span style="color: #b1b100;">function</span> ship:collision<span style="color: #66cc66;">&#40;</span>event<span style="color: #66cc66;">&#41;</span>
   <span style="color: #b1b100;">if</span> event.phase <span style="color: #66cc66;">==</span> <span style="color: #ff0000;">&quot;began&quot;</span> <span style="color: #b1b100;">then</span>
      <span style="color: #b1b100;">if</span> event.target.name <span style="color: #66cc66;">==</span> <span style="color: #ff0000;">&quot;powerUp&quot;</span> <span style="color: #b1b100;">then</span>
         <span style="color: #b1b100;">_G</span>.score <span style="color: #66cc66;">=</span> <span style="color: #b1b100;">_G</span>.score + <span style="color: #cc66cc;">1</span>
         updateScoreText<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>
         <span style="color: #b1b100;">return</span> <span style="color: #b1b100;">true</span>
      <span style="color: #b1b100;">end</span>
   <span style="color: #b1b100;">end</span>
<span style="color: #b1b100;">end</span>
ship:addEventListener<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;collision&quot;</span>, ship<span style="color: #66cc66;">&#41;</span>
&nbsp;
<span style="color: #b1b100;">function</span> onTouch<span style="color: #66cc66;">&#40;</span>event<span style="color: #66cc66;">&#41;</span>
   <span style="color: #b1b100;">if</span> event.phase <span style="color: #66cc66;">==</span> <span style="color: #ff0000;">&quot;began&quot;</span> <span style="color: #b1b100;">then</span>
      <span style="color: #b1b100;">local</span> bullet <span style="color: #66cc66;">=</span> display.newImage<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;bullet.png&quot;</span><span style="color: #66cc66;">&#41;</span>
      bullet.name <span style="color: #66cc66;">=</span> <span style="color: #ff0000;">&quot;bullet&quot;</span>
      <span style="color: #b1b100;">return</span> <span style="color: #b1b100;">true</span>
   <span style="color: #b1b100;">end</span>
<span style="color: #b1b100;">end</span>
&nbsp;
Runtime:addEventListener<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;touch&quot;</span>, onTouch<span style="color: #66cc66;">&#41;</span></pre></div></div>

<p><strong>Refactored Code Round 1</strong>:</p>

<div class="wp_syntax"><div class="code"><pre class="lua" style="font-family:monospace;"><span style="color: #808080; font-style: italic;">--[[
Notice we've added an addScore method to:
1. have a central place everyone can update the model data
2. make it easier to identify WHO is calling this add function
3. ensure we never forget to update our Text Field with the latest value like in the original code
]]</span><span style="color: #808080; font-style: italic;">--</span>
&nbsp;
<span style="color: #b1b100;">function</span> addScore<span style="color: #66cc66;">&#40;</span>amount<span style="color: #66cc66;">&#41;</span>
   <span style="color: #b1b100;">_G</span>.score <span style="color: #66cc66;">=</span> <span style="color: #b1b100;">_G</span>.score + amount
   updateScoreText<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>
<span style="color: #b1b100;">end</span>
&nbsp;
<span style="color: #808080; font-style: italic;">-- Fixing our enemy collision handler to now call our encapsulated method</span>
<span style="color: #b1b100;">function</span> enemy:collision<span style="color: #66cc66;">&#40;</span>event<span style="color: #66cc66;">&#41;</span>
   <span style="color: #b1b100;">if</span> event.phase <span style="color: #66cc66;">==</span> <span style="color: #ff0000;">&quot;began&quot;</span> <span style="color: #b1b100;">then</span>
      <span style="color: #b1b100;">if</span> event.target.name <span style="color: #66cc66;">==</span> <span style="color: #ff0000;">&quot;bullet&quot;</span> <span style="color: #b1b100;">then</span>
         addScore<span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">1</span><span style="color: #66cc66;">&#41;</span>
      <span style="color: #b1b100;">end</span>
   <span style="color: #b1b100;">end</span>
<span style="color: #b1b100;">end</span></pre></div></div>

<p><strong>Refactored Code Round 2</strong>:</p>

<div class="wp_syntax"><div class="code"><pre class="lua" style="font-family:monospace;"><span style="color: #808080; font-style: italic;">--[[
Now we use a more generalized Observer pattern, and dispatch an event
when the value changes. The system is free to listen to this event
and react however it needs to. This allows the GUI to change w/o worrying
updating the model changing behavior to compensate for a changing GUI API.
]]</span><span style="color: #808080; font-style: italic;">--</span>
&nbsp;
<span style="color: #b1b100;">function</span> addScore<span style="color: #66cc66;">&#40;</span>amount<span style="color: #66cc66;">&#41;</span>
   <span style="color: #b1b100;">_G</span>.score <span style="color: #66cc66;">=</span> <span style="color: #b1b100;">_G</span>.score + amount
   Runtime:dispatchEvent<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#123;</span>name<span style="color: #66cc66;">=</span><span style="color: #ff0000;">&quot;onScoreChanged&quot;</span>, newScore<span style="color: #66cc66;">=</span><span style="color: #b1b100;">_G</span>.score<span style="color: #66cc66;">&#125;</span><span style="color: #66cc66;">&#41;</span>
<span style="color: #b1b100;">end</span>
&nbsp;
<span style="color: #808080; font-style: italic;">-- we now can update more GUI parts as they become needed</span>
<span style="color: #b1b100;">function</span> onScoreUpdated<span style="color: #66cc66;">&#40;</span>event<span style="color: #66cc66;">&#41;</span>
   updateScoreText<span style="color: #66cc66;">&#40;</span>event.newScore<span style="color: #66cc66;">&#41;</span>
<span style="color: #b1b100;">end</span>
Runtime:addEventListener<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;onScoreChanged&quot;</span>, onScoreUpdated<span style="color: #66cc66;">&#41;</span>
&nbsp;
<span style="color: #808080; font-style: italic;">-- notice this includes encapsulated GUI controls as well;</span>
<span style="color: #808080; font-style: italic;">-- they can just listen in on the Event Bus.</span>
<span style="color: #808080; font-style: italic;">-- Here, we have a Level Progress bar that listens to the score change</span>
<span style="color: #808080; font-style: italic;">-- to visually indicate how far along the user is until they level up.</span>
<span style="color: #b1b100;">require</span> <span style="color: #ff0000;">&quot;com.company.project.controls.ProgressBar&quot;</span>
&nbsp;
LevelUpProgressBar <span style="color: #66cc66;">=</span> <span style="color: #66cc66;">&#123;</span><span style="color: #66cc66;">&#125;</span>
&nbsp;
<span style="color: #b1b100;">function</span> LevelUpProgressBar:new<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>
&nbsp;
   <span style="color: #b1b100;">local</span> bar <span style="color: #66cc66;">=</span> ProgressBar:new<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#123;</span>width <span style="color: #66cc66;">=</span> <span style="color: #cc66cc;">100</span>, height <span style="color: #66cc66;">=</span> <span style="color: #cc66cc;">60</span><span style="color: #66cc66;">&#125;</span><span style="color: #66cc66;">&#41;</span>
   bar.levelMax <span style="color: #66cc66;">=</span> <span style="color: #cc66cc;">1</span>
&nbsp;
   <span style="color: #b1b100;">function</span> bar:onScoreChanged<span style="color: #66cc66;">&#40;</span>event<span style="color: #66cc66;">&#41;</span>
      self:setProgress<span style="color: #66cc66;">&#40;</span>event.newScore, self.levelMax<span style="color: #66cc66;">&#41;</span>
   <span style="color: #b1b100;">end</span>
&nbsp;
   <span style="color: #b1b100;">function</span> bar:onLevelMaxChanged<span style="color: #66cc66;">&#40;</span>event<span style="color: #66cc66;">&#41;</span>
      self.levelMax <span style="color: #66cc66;">=</span> event.newLevelMax
   <span style="color: #b1b100;">end</span>
&nbsp;
   Runtime:addEventListener<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;onLevelMaxChanged&quot;</span>, bar<span style="color: #66cc66;">&#41;</span>
   Runtime:addEventListener<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;onScoreChanged&quot;</span>, bar<span style="color: #66cc66;">&#41;</span>
&nbsp;
<span style="color: #b1b100;">end</span>
&nbsp;
<span style="color: #b1b100;">return</span> LevelUpProgressBar</pre></div></div>

<p><strong>Case</strong>: Access Control for Statefull Model Data Using Application Logic (English: you need to update some model data, and multiple parts in your application need to do this). aka, removing global variables.<br />
<strong>Solution</strong>: Utilize Proxy Pattern or Command Pattern for single access (DRY), this ensures there is only 1 way to update your model data, inputs are validated. This makes it easier to debug who is calling/invoking it, and what data they are passing, as well as ensuring those who need to know about the change are informed.<br />
<strong>Language</strong>: ActionScript</p>
<p><strong>Bad Code</strong>:</p>

<div class="wp_syntax"><div class="code"><pre class="actionscript" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">var</span> firstName:<span style="color: #0066CC;">String</span>             = firstNameTextInput.<span style="color: #0066CC;">text</span>;
<span style="color: #000000; font-weight: bold;">var</span> lastName:<span style="color: #0066CC;">String</span>              = lastNameTextInput.<span style="color: #0066CC;">text</span>;
<span style="color: #000000; font-weight: bold;">var</span> birthdate:<span style="color: #0066CC;">Date</span>               = birthdateControl.<span style="color: #006600;">value</span>;
<span style="color: #000000; font-weight: bold;">var</span> myPersonVO:PersonVO          = <span style="color: #000000; font-weight: bold;">new</span> PersonVO<span style="color: #66cc66;">&#40;</span>firstName, lastName, birthdate<span style="color: #66cc66;">&#41;</span>;
MyStaticModel.<span style="color: #006600;">person</span>             = myPersonVO;
MyStaticModel.<span style="color: #006600;">person</span>.<span style="color: #006600;">lastName</span>    = <span style="color: #ff0000;">&quot;McTaggart&quot;</span></pre></div></div>

<p><strong>Refactored Code</strong>:</p>

<div class="wp_syntax"><div class="code"><pre class="actionscript" style="font-family:monospace;"><span style="color: #808080; font-style: italic;">// First we create a factory class to test our creation &amp;amp; validation in isolation.</span>
<span style="color: #808080; font-style: italic;">// This is also easier to write unit tests for. It's also DRY in that all classes</span>
<span style="color: #808080; font-style: italic;">// who need to create PersonVO's and validate them are using the same code to do so.</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">class</span> PersonFactory
<span style="color: #66cc66;">&#123;</span>
   <span style="color: #0066CC;">public</span> <span style="color: #0066CC;">static</span> <span style="color: #000000; font-weight: bold;">function</span> getPerson<span style="color: #66cc66;">&#40;</span>firstName:<span style="color: #0066CC;">String</span>, lastName:<span style="color: #0066CC;">String</span>, birthdate:<span style="color: #0066CC;">Date</span><span style="color: #66cc66;">&#41;</span>:PersonVO
   <span style="color: #66cc66;">&#123;</span>
      <span style="color: #b1b100;">if</span><span style="color: #66cc66;">&#40;</span>firstName == <span style="color: #000000; font-weight: bold;">null</span> <span style="color: #66cc66;">||</span> firstName == <span style="color: #ff0000;">&quot;&quot;</span><span style="color: #66cc66;">&#41;</span>
      <span style="color: #66cc66;">&#123;</span>
         <span style="color: #0066CC;">throw</span> <span style="color: #000000; font-weight: bold;">new</span> <span style="color: #0066CC;">Error</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;firstName cannot be null nor an empty String.&quot;</span><span style="color: #66cc66;">&#41;</span>;
         <span style="color: #b1b100;">return</span>;
      <span style="color: #66cc66;">&#125;</span>
&nbsp;
      <span style="color: #b1b100;">if</span><span style="color: #66cc66;">&#40;</span>lastName == <span style="color: #000000; font-weight: bold;">null</span> <span style="color: #66cc66;">||</span> lastName == <span style="color: #ff0000;">&quot;&quot;</span><span style="color: #66cc66;">&#41;</span>
      <span style="color: #66cc66;">&#123;</span>
         <span style="color: #0066CC;">throw</span> <span style="color: #000000; font-weight: bold;">new</span> <span style="color: #0066CC;">Error</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;lastName cannot be null nor an empty String.&quot;</span><span style="color: #66cc66;">&#41;</span>;
         <span style="color: #b1b100;">return</span>;
      <span style="color: #66cc66;">&#125;</span>
&nbsp;
      <span style="color: #b1b100;">if</span><span style="color: #66cc66;">&#40;</span>birthdate == <span style="color: #000000; font-weight: bold;">null</span><span style="color: #66cc66;">&#41;</span>
      <span style="color: #66cc66;">&#123;</span>
         <span style="color: #0066CC;">throw</span> <span style="color: #000000; font-weight: bold;">new</span> <span style="color: #0066CC;">Date</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;birthdate cannot be null.&quot;</span><span style="color: #66cc66;">&#41;</span>;
      <span style="color: #66cc66;">&#125;</span>
&nbsp;
      <span style="color: #b1b100;">return</span> <span style="color: #000000; font-weight: bold;">new</span> PersonVO<span style="color: #66cc66;">&#40;</span>firstName, lastName, birthdate<span style="color: #66cc66;">&#41;</span>;
   <span style="color: #66cc66;">&#125;</span>
&nbsp;
   <span style="color: #0066CC;">public</span> <span style="color: #0066CC;">static</span> const validateLastName<span style="color: #66cc66;">&#40;</span>lastName:<span style="color: #0066CC;">String</span><span style="color: #66cc66;">&#41;</span>:<span style="color: #0066CC;">Boolean</span>
   <span style="color: #66cc66;">&#123;</span>
      <span style="color: #b1b100;">if</span><span style="color: #66cc66;">&#40;</span>lastName <span style="color: #66cc66;">!</span>= <span style="color: #000000; font-weight: bold;">null</span> <span style="color: #66cc66;">&amp;</span>amp;<span style="color: #66cc66;">&amp;</span>amp; lastName <span style="color: #66cc66;">!</span>= <span style="color: #ff0000;">&quot;&quot;</span><span style="color: #66cc66;">&#41;</span>
      <span style="color: #66cc66;">&#123;</span>
         <span style="color: #b1b100;">return</span> <span style="color: #000000; font-weight: bold;">true</span>;
      <span style="color: #66cc66;">&#125;</span>
      <span style="color: #b1b100;">else</span>
      <span style="color: #66cc66;">&#123;</span>
         <span style="color: #b1b100;">return</span> <span style="color: #000000; font-weight: bold;">false</span>;
      <span style="color: #66cc66;">&#125;</span>
   <span style="color: #66cc66;">&#125;</span>
<span style="color: #66cc66;">&#125;</span>
&nbsp;
<span style="color: #808080; font-style: italic;">// Second step, create a change event that those who need to know about a changing</span>
<span style="color: #808080; font-style: italic;">// personVO in the model can be made aware of.</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">class</span> PersonModelEvent <span style="color: #0066CC;">extends</span> Event
<span style="color: #66cc66;">&#123;</span>
&nbsp;
   <span style="color: #0066CC;">public</span> <span style="color: #0066CC;">static</span> const PERSON_CHANGED:<span style="color: #0066CC;">String</span> = <span style="color: #ff0000;">&quot;personChanged&quot;</span>;
&nbsp;
   <span style="color: #0066CC;">public</span> <span style="color: #000000; font-weight: bold;">function</span> PersonModelEvent<span style="color: #66cc66;">&#40;</span><span style="color: #0066CC;">type</span>:<span style="color: #0066CC;">String</span><span style="color: #66cc66;">&#41;</span>
   <span style="color: #66cc66;">&#123;</span>
      <span style="color: #0066CC;">super</span><span style="color: #66cc66;">&#40;</span><span style="color: #0066CC;">type</span>, <span style="color: #000000; font-weight: bold;">false</span>, <span style="color: #000000; font-weight: bold;">true</span><span style="color: #66cc66;">&#41;</span>;
   <span style="color: #66cc66;">&#125;</span>
&nbsp;
<span style="color: #66cc66;">&#125;</span>
&nbsp;
<span style="color: #808080; font-style: italic;">/*
Third, create a Model class Singleton that:
- dispatches change events when it's internal person variable is changed, or modified
through accessor controls
- validates creation &amp;amp; changes
NOTE: If classes need to operate on PersonVO itself, create additional methods to
operate on the internal PersonVO to ensure proper change events are dispatched.
NOTE: For those who wish to remove Singletons, create as an instance, and inject the dependencies,
whether via a DI framework such as SwiftSuspenders/Guice/Spring, or manually via
getter/setters for those classes who need instance access.
*/</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">class</span> PersonModel <span style="color: #0066CC;">extends</span> EventDispatcher
<span style="color: #66cc66;">&#123;</span>
&nbsp;
   <span style="color: #0066CC;">private</span> <span style="color: #000000; font-weight: bold;">var</span> _person:PersonVO;
&nbsp;
   <span style="color: #0066CC;">public</span> <span style="color: #000000; font-weight: bold;">function</span> <span style="color: #0066CC;">get</span> person<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>:PersonVO <span style="color: #66cc66;">&#123;</span> <span style="color: #b1b100;">return</span> _person; <span style="color: #66cc66;">&#125;</span>
   <span style="color: #0066CC;">public</span> <span style="color: #000000; font-weight: bold;">function</span> <span style="color: #0066CC;">set</span> person<span style="color: #66cc66;">&#40;</span>value:PersonVO<span style="color: #66cc66;">&#41;</span>:<span style="color: #0066CC;">void</span>
   <span style="color: #66cc66;">&#123;</span>
      _person = value;
      dispatchEvent<span style="color: #66cc66;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> PersonModelEvent<span style="color: #66cc66;">&#40;</span>PersonModelEvent.<span style="color: #006600;">PERSON_CHANGED</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>;
   <span style="color: #66cc66;">&#125;</span>
&nbsp;
   <span style="color: #0066CC;">public</span> <span style="color: #000000; font-weight: bold;">function</span> PersonModel<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>
   <span style="color: #66cc66;">&#123;</span>
   <span style="color: #66cc66;">&#125;</span>
&nbsp;
   <span style="color: #0066CC;">public</span> <span style="color: #000000; font-weight: bold;">function</span> setNewPerson<span style="color: #66cc66;">&#40;</span>firstName:<span style="color: #0066CC;">String</span>, lastName:<span style="color: #0066CC;">String</span>, birthdate:<span style="color: #0066CC;">Date</span><span style="color: #66cc66;">&#41;</span>:<span style="color: #0066CC;">void</span>
   <span style="color: #66cc66;">&#123;</span>
      <span style="color: #808080; font-style: italic;">// first, validate data is good, don't want to pollute our model</span>
      <span style="color: #000000; font-weight: bold;">var</span> personVO:PersonVO;
      <span style="color: #0066CC;">try</span>
      <span style="color: #66cc66;">&#123;</span>
         personVO = PersonFactory.<span style="color: #006600;">getPerson</span><span style="color: #66cc66;">&#40;</span>firstName, lastName, birthdate<span style="color: #66cc66;">&#41;</span>;
         person = personVO;
      <span style="color: #66cc66;">&#125;</span>
      <span style="color: #0066CC;">catch</span><span style="color: #66cc66;">&#40;</span><span style="color: #0066CC;">error</span>:<span style="color: #0066CC;">Error</span><span style="color: #66cc66;">&#41;</span>
      <span style="color: #66cc66;">&#123;</span>
         <span style="color: #0066CC;">trace</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;PersonModel::setNewPerson error: &quot;</span> + <span style="color: #0066CC;">error</span><span style="color: #66cc66;">&#41;</span>;
      <span style="color: #66cc66;">&#125;</span>
   <span style="color: #66cc66;">&#125;</span>
&nbsp;
   <span style="color: #0066CC;">public</span> <span style="color: #000000; font-weight: bold;">function</span> updateLastName<span style="color: #66cc66;">&#40;</span>lastName:<span style="color: #0066CC;">String</span><span style="color: #66cc66;">&#41;</span>:<span style="color: #0066CC;">void</span>
   <span style="color: #66cc66;">&#123;</span>
      <span style="color: #b1b100;">if</span><span style="color: #66cc66;">&#40;</span>person<span style="color: #66cc66;">&#41;</span>
      <span style="color: #66cc66;">&#123;</span>
         <span style="color: #b1b100;">if</span><span style="color: #66cc66;">&#40;</span>PersonFactory.<span style="color: #006600;">validateLastName</span><span style="color: #66cc66;">&#40;</span>lastName<span style="color: #66cc66;">&#41;</span> == <span style="color: #000000; font-weight: bold;">true</span><span style="color: #66cc66;">&#41;</span>
         <span style="color: #66cc66;">&#123;</span>
            person.<span style="color: #006600;">lastName</span> = lastName;
            dispatchEvent<span style="color: #66cc66;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> PersonModelEvent<span style="color: #66cc66;">&#40;</span>PersonModelEvent.<span style="color: #006600;">PERSON_CHANGED</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>;
         <span style="color: #66cc66;">&#125;</span>
         <span style="color: #b1b100;">else</span>
         <span style="color: #66cc66;">&#123;</span>
            <span style="color: #0066CC;">trace</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;PersonModel::updateLastName, failed because the lastName '&quot;</span> + lastName + <span style="color: #ff0000;">&quot;' is invalid.&quot;</span><span style="color: #66cc66;">&#41;</span>;
         <span style="color: #66cc66;">&#125;</span>
      <span style="color: #66cc66;">&#125;</span>
      <span style="color: #b1b100;">else</span>
      <span style="color: #66cc66;">&#123;</span>
         <span style="color: #0066CC;">trace</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;PersonModel::updateLastName, failed because the current person is null.&quot;</span><span style="color: #66cc66;">&#41;</span>;
      <span style="color: #66cc66;">&#125;</span>
   <span style="color: #66cc66;">&#125;</span>
&nbsp;
   <span style="color: #0066CC;">private</span> <span style="color: #0066CC;">static</span> <span style="color: #000000; font-weight: bold;">var</span> _inst:PersonModel;
&nbsp;
   <span style="color: #0066CC;">public</span> <span style="color: #0066CC;">static</span> <span style="color: #000000; font-weight: bold;">function</span> <span style="color: #0066CC;">get</span> instance<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>:PersonModel
   <span style="color: #66cc66;">&#123;</span>
      <span style="color: #b1b100;">if</span><span style="color: #66cc66;">&#40;</span>_inst == <span style="color: #000000; font-weight: bold;">null</span><span style="color: #66cc66;">&#41;</span>
         _inst = <span style="color: #000000; font-weight: bold;">new</span> PersonModel<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;
      <span style="color: #b1b100;">return</span> _inst;
   <span style="color: #66cc66;">&#125;</span>
<span style="color: #66cc66;">&#125;</span></pre></div></div>

<p><strong>Refactored Code 2</strong>:</p>

<div class="wp_syntax"><div class="code"><pre class="actionscript" style="font-family:monospace;"><span style="color: #808080; font-style: italic;">/*
In the case of need of many needing to affect the Model, and there is no
desire to all Models/Proxies to have public methods accessible by others,
you can use the Command pattern. Additionally, this solves the use case
where multiple Models are needed to be accessed and/or modified. Finally,
we also handle asynchronous use cases where you need to update a Model(s)
based on a server response. Notice how each step is validated, and a log is
produced if any step fails. You need to know WHERE it failed and WHY.
Also, no rollback support in the following.
*/</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">class</span> CreatePersonEvent <span style="color: #0066CC;">extends</span> Event
<span style="color: #66cc66;">&#123;</span>
   <span style="color: #0066CC;">public</span> <span style="color: #0066CC;">static</span> const CREATE_PERSON:<span style="color: #0066CC;">String</span> = <span style="color: #ff0000;">&quot;createPerson&quot;</span>;
&nbsp;
   <span style="color: #0066CC;">public</span> <span style="color: #000000; font-weight: bold;">var</span> firstName:<span style="color: #0066CC;">String</span>;
   <span style="color: #0066CC;">public</span> <span style="color: #000000; font-weight: bold;">var</span> lastName:<span style="color: #0066CC;">String</span>;
   <span style="color: #0066CC;">public</span> <span style="color: #000000; font-weight: bold;">var</span> birthdate:<span style="color: #0066CC;">Date</span>;
   <span style="color: #0066CC;">public</span> <span style="color: #000000; font-weight: bold;">var</span> personModel:PersonModel;
   <span style="color: #0066CC;">public</span> <span style="color: #000000; font-weight: bold;">var</span> organizationModel:OrganizationModel;
&nbsp;
   <span style="color: #0066CC;">public</span> <span style="color: #000000; font-weight: bold;">function</span> CreatePersonEvent<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>
   <span style="color: #66cc66;">&#123;</span>
      <span style="color: #0066CC;">super</span><span style="color: #66cc66;">&#40;</span>CREATE_PERSON<span style="color: #66cc66;">&#41;</span>;
   <span style="color: #66cc66;">&#125;</span>
<span style="color: #66cc66;">&#125;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">class</span> CreatePersonCommand <span style="color: #0066CC;">extends</span> AsynCommand
<span style="color: #66cc66;">&#123;</span>
&nbsp;
   <span style="color: #808080; font-style: italic;">// injected dependencies; you could use a DI framework,</span>
   <span style="color: #808080; font-style: italic;">// wrap Command class creation with these, or simply pass</span>
   <span style="color: #808080; font-style: italic;">// in through the Event payload like the below shows.</span>
   <span style="color: #0066CC;">private</span> <span style="color: #000000; font-weight: bold;">var</span> personModel:PersonModel;
   <span style="color: #0066CC;">private</span> <span style="color: #000000; font-weight: bold;">var</span> organizationModel:PersonModel;
   <span style="color: #0066CC;">private</span> <span style="color: #000000; font-weight: bold;">var</span> createPersonService:RESTFullCreatePersonService;
   <span style="color: #0066CC;">private</span> <span style="color: #000000; font-weight: bold;">var</span> personVOToCreate:PersonVO;
&nbsp;
   <span style="color: #808080; font-style: italic;">// Create a PersonVO, set on the PersonModel,</span>
   <span style="color: #808080; font-style: italic;">// and ensure the OrganizationModel is updated with the</span>
   <span style="color: #808080; font-style: italic;">// new person once the server has verified it's creation.</span>
   <span style="color: #0066CC;">public</span> <span style="color: #000000; font-weight: bold;">function</span> execute<span style="color: #66cc66;">&#40;</span>event:CreatePersonEvent<span style="color: #66cc66;">&#41;</span>:<span style="color: #0066CC;">void</span>
   <span style="color: #66cc66;">&#123;</span>
      <span style="color: #0066CC;">try</span>
      <span style="color: #66cc66;">&#123;</span>
         personModel = event.<span style="color: #006600;">personModel</span>;
         organizationModel = event.<span style="color: #006600;">organizationModel</span>;
         personVOToCreate = PersonFactory.<span style="color: #006600;">getPerson</span><span style="color: #66cc66;">&#40;</span>firstName, lastName, birthdate<span style="color: #66cc66;">&#41;</span>;
         <span style="color: #b1b100;">if</span><span style="color: #66cc66;">&#40;</span>personVOToCreate <span style="color: #66cc66;">!</span>= <span style="color: #000000; font-weight: bold;">null</span><span style="color: #66cc66;">&#41;</span>
         <span style="color: #66cc66;">&#123;</span>
            createPerson<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>
         <span style="color: #66cc66;">&#125;</span>
         <span style="color: #b1b100;">else</span>
         <span style="color: #66cc66;">&#123;</span>
            <span style="color: #0066CC;">throw</span> <span style="color: #000000; font-weight: bold;">new</span> <span style="color: #0066CC;">Error</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;ERROR: CreatePersonCommand::exeucte, PersonFactory returned null.&quot;</span><span style="color: #66cc66;">&#41;</span>;
         <span style="color: #66cc66;">&#125;</span>
      <span style="color: #66cc66;">&#125;</span>
      <span style="color: #0066CC;">catch</span><span style="color: #66cc66;">&#40;</span><span style="color: #0066CC;">error</span>:<span style="color: #0066CC;">Error</span><span style="color: #66cc66;">&#41;</span>
      <span style="color: #66cc66;">&#123;</span>
         <span style="color: #0066CC;">trace</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;ERROR: CreatePersonCommand::execute, error: &quot;</span> + <span style="color: #0066CC;">error</span><span style="color: #66cc66;">&#41;</span>;
         finish<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
      <span style="color: #66cc66;">&#125;</span>
   <span style="color: #66cc66;">&#125;</span>
&nbsp;
   <span style="color: #0066CC;">private</span> <span style="color: #000000; font-weight: bold;">function</span> createPerson<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>:<span style="color: #0066CC;">void</span>
   <span style="color: #66cc66;">&#123;</span>
      createPersonService = <span style="color: #000000; font-weight: bold;">new</span> RESTFullCreatePersonService<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
      createPersonService.<span style="color: #006600;">addEventListener</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;success&quot;</span>, onCreatePersonSuccess<span style="color: #66cc66;">&#41;</span>;
      createPersonService.<span style="color: #006600;">addEventListener</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;error&quot;</span>, onCreatePersonError<span style="color: #66cc66;">&#41;</span>;
      createPersonService.<span style="color: #006600;">createPerson</span><span style="color: #66cc66;">&#40;</span>personVOToCreate<span style="color: #66cc66;">&#41;</span>;
   <span style="color: #66cc66;">&#125;</span>
&nbsp;
   <span style="color: #0066CC;">private</span> <span style="color: #000000; font-weight: bold;">function</span> onCreatePersonError<span style="color: #66cc66;">&#40;</span>event:Event<span style="color: #66cc66;">&#41;</span>:<span style="color: #0066CC;">void</span>
   <span style="color: #66cc66;">&#123;</span>
      <span style="color: #0066CC;">trace</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;ERROR: CreatePersonCommand::onCreatePersonError, event: &quot;</span> + event<span style="color: #66cc66;">&#41;</span>;
      finish<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
   <span style="color: #66cc66;">&#125;</span>
&nbsp;
   <span style="color: #0066CC;">private</span> <span style="color: #000000; font-weight: bold;">function</span> onCreatePersonSuccess<span style="color: #66cc66;">&#40;</span>event:Event<span style="color: #66cc66;">&#41;</span>:<span style="color: #0066CC;">void</span>
   <span style="color: #66cc66;">&#123;</span>
      <span style="color: #808080; font-style: italic;">// server has successfully created PersonVO, let's update ours with what</span>
      <span style="color: #808080; font-style: italic;">// the server sent back to ensure we now have a proper PersonVO.ID set</span>
      <span style="color: #808080; font-style: italic;">// by the server</span>
      <span style="color: #b1b100;">if</span><span style="color: #66cc66;">&#40;</span>createPersonService.<span style="color: #006600;">savedPersonVO</span> <span style="color: #66cc66;">!</span>= <span style="color: #000000; font-weight: bold;">null</span><span style="color: #66cc66;">&#41;</span>
      <span style="color: #66cc66;">&#123;</span>
         personModel.<span style="color: #006600;">person</span> = createPersonService.<span style="color: #006600;">savedPersonVO</span>;
         organizationModel.<span style="color: #006600;">addNewPerson</span><span style="color: #66cc66;">&#40;</span>personModel.<span style="color: #006600;">person</span><span style="color: #66cc66;">&#41;</span>;
      <span style="color: #66cc66;">&#125;</span>
      <span style="color: #b1b100;">else</span>
      <span style="color: #66cc66;">&#123;</span>
         <span style="color: #0066CC;">trace</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;ERROR: CreatePersonCommand::onCreatePersonSuccess failed, server sent back a null savedPersonVO.&quot;</span><span style="color: #66cc66;">&#41;</span>;
      <span style="color: #66cc66;">&#125;</span>
      finish<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
   <span style="color: #66cc66;">&#125;</span>
&nbsp;
<span style="color: #66cc66;">&#125;</span></pre></div></div>

<p><strong>Step #3: Strong Typing</strong></p>
<p><strong>Case</strong>: Using loose typing/variants/Objects/*, resulting in loss of compiler time checking and thus errors that only appear at runtime.<br />
<strong>Solution</strong>: Use strong-typing.<br />
<strong>Language</strong>: ActionScript</p>
<p><strong>Bad Code</strong>:</p>

<div class="wp_syntax"><div class="code"><pre class="actionscript" style="font-family:monospace;"><span style="color: #808080; font-style: italic;">/*
Notice:
- personVO.lstName is a mispelling, but no error will be raised by the compiler.
- no error will be raised by the updatePerson function as Object is dynamic,
and lastName will be created and set on the personVO Object.
- no error will be raised if you pass something other than a personVO to updatePerson
except for runtime errors
*/</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">var</span> personVO:<span style="color: #0066CC;">Object</span> = <span style="color: #66cc66;">&#123;</span><span style="color: #66cc66;">&#125;</span>;
personVO.<span style="color: #006600;">firstName</span> = <span style="color: #ff0000;">&quot;Jesse&quot;</span>;
personVO.<span style="color: #006600;">lstName</span> = <span style="color: #ff0000;">&quot;Warden&quot;</span>;
&nbsp;
<span style="color: #000000; font-weight: bold;">function</span> updatePerson<span style="color: #66cc66;">&#40;</span>person:<span style="color: #66cc66;">*</span>, newNameFromStringBlock:<span style="color: #0066CC;">String</span><span style="color: #66cc66;">&#41;</span>:<span style="color: #0066CC;">void</span>
<span style="color: #66cc66;">&#123;</span>
   <span style="color: #000000; font-weight: bold;">var</span> nameArray:<span style="color: #0066CC;">Array</span> = newNameFromStringBlock.<span style="color: #0066CC;">split</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot; &quot;</span><span style="color: #66cc66;">&#41;</span>;
   person.<span style="color: #006600;">firstName</span> = nameArray<span style="color: #66cc66;">&#91;</span><span style="color: #cc66cc;">0</span><span style="color: #66cc66;">&#93;</span>;
   person.<span style="color: #006600;">lastName</span> = nameArray<span style="color: #66cc66;">&#91;</span><span style="color: #cc66cc;">1</span><span style="color: #66cc66;">&#93;</span>;
<span style="color: #66cc66;">&#125;</span></pre></div></div>

<p><strong>Refactored Code</strong>:</p>

<div class="wp_syntax"><div class="code"><pre class="actionscript" style="font-family:monospace;"><span style="color: #808080; font-style: italic;">/*
Notice:
- our &quot;lstName&quot; will be caught by the compiler
- our updatePerson function ensures only a PersonVO is accepted to be operated on. If not,
our compiler will let us know.
*/</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">class</span> PersonVO
<span style="color: #66cc66;">&#123;</span>
   <span style="color: #0066CC;">public</span> <span style="color: #000000; font-weight: bold;">var</span> firstName:<span style="color: #0066CC;">String</span>;
   <span style="color: #0066CC;">public</span> <span style="color: #000000; font-weight: bold;">var</span> lastName:<span style="color: #0066CC;">String</span>;
<span style="color: #66cc66;">&#125;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">var</span> personVO:PersonVO = <span style="color: #000000; font-weight: bold;">new</span> PersonVO<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
personVO.<span style="color: #006600;">firstName</span> = <span style="color: #ff0000;">&quot;Jesse&quot;</span>;
personVO.<span style="color: #006600;">lstName</span> = <span style="color: #ff0000;">&quot;Warden&quot;</span>;
&nbsp;
<span style="color: #000000; font-weight: bold;">function</span> updatePerson<span style="color: #66cc66;">&#40;</span>person:PersonVO, newNameFromStringBlock:<span style="color: #0066CC;">String</span><span style="color: #66cc66;">&#41;</span>:<span style="color: #0066CC;">void</span>
<span style="color: #66cc66;">&#123;</span>
   <span style="color: #000000; font-weight: bold;">var</span> nameArray:<span style="color: #0066CC;">Array</span> = newNameFromStringBlock.<span style="color: #0066CC;">split</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot; &quot;</span><span style="color: #66cc66;">&#41;</span>;
   person.<span style="color: #006600;">firstName</span> = nameArray<span style="color: #66cc66;">&#91;</span><span style="color: #cc66cc;">0</span><span style="color: #66cc66;">&#93;</span>;
   person.<span style="color: #006600;">lastName</span> = nameArray<span style="color: #66cc66;">&#91;</span><span style="color: #cc66cc;">1</span><span style="color: #66cc66;">&#93;</span>;
<span style="color: #66cc66;">&#125;</span></pre></div></div>

<p><strong>Case</strong>: Service layer has no input validation, is hard to test, and has no error reporting. Burden is on class user to wrap in try/catch as well as parse server response including knowing business logic. Finally, asynchronous loader is not a class member variable, thus potential memory leak + harder to debug.<br />
<strong>Solution</strong>: Create a Service class that is easy to use, validates inputs, and logs errors. Encapsulates business logic.<br />
<strong>Langauge</strong>: ActionScript</p>
<p><strong>Bad Code</strong>:</p>

<div class="wp_syntax"><div class="code"><pre class="actionscript" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">class</span> CreatePersonService <span style="color: #0066CC;">extends</span> EventDispatcher
<span style="color: #66cc66;">&#123;</span>
&nbsp;
   <span style="color: #0066CC;">public</span> <span style="color: #000000; font-weight: bold;">var</span> loader:URLLoader;
&nbsp;
   <span style="color: #0066CC;">public</span> <span style="color: #000000; font-weight: bold;">function</span> CreatePersonService<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>
   <span style="color: #66cc66;">&#123;</span>
      <span style="color: #0066CC;">super</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
   <span style="color: #66cc66;">&#125;</span>
&nbsp;
   <span style="color: #0066CC;">public</span> <span style="color: #000000; font-weight: bold;">function</span> createPerson<span style="color: #66cc66;">&#40;</span>person:PersonVO<span style="color: #66cc66;">&#41;</span>:<span style="color: #0066CC;">void</span>
   <span style="color: #66cc66;">&#123;</span>
      <span style="color: #000000; font-weight: bold;">var</span> loader = <span style="color: #000000; font-weight: bold;">new</span> URLLoader<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
      loader.<span style="color: #006600;">addEventListener</span><span style="color: #66cc66;">&#40;</span>Event.<span style="color: #006600;">COMPLETE</span>, onComplete<span style="color: #66cc66;">&#41;</span>;
      <span style="color: #000000; font-weight: bold;">var</span> req:URLRequest = <span style="color: #000000; font-weight: bold;">new</span> URLRequest<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;http://someserver.com/restful/api/&quot;</span><span style="color: #66cc66;">&#41;</span>;
      req.<span style="color: #0066CC;">data</span> = person.<span style="color: #006600;">toJSON</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
      loader.<span style="color: #0066CC;">load</span><span style="color: #66cc66;">&#40;</span>req<span style="color: #66cc66;">&#41;</span>;
   <span style="color: #66cc66;">&#125;</span>
&nbsp;
   <span style="color: #0066CC;">private</span> <span style="color: #000000; font-weight: bold;">function</span> onComplete<span style="color: #66cc66;">&#40;</span>event:Event<span style="color: #66cc66;">&#41;</span>:<span style="color: #0066CC;">void</span>
   <span style="color: #66cc66;">&#123;</span>
      dispatchEvent<span style="color: #66cc66;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> Event<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;success&quot;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>;
   <span style="color: #66cc66;">&#125;</span>
<span style="color: #66cc66;">&#125;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">var</span> service:CreatePersonService = <span style="color: #000000; font-weight: bold;">new</span> CreatePersonService<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
service.<span style="color: #006600;">addEventListener</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;success&quot;</span>, onSuccess<span style="color: #66cc66;">&#41;</span>;
&nbsp;
<span style="color: #000000; font-weight: bold;">function</span> onSuccess<span style="color: #66cc66;">&#40;</span>event:Event<span style="color: #66cc66;">&#41;</span>:<span style="color: #0066CC;">void</span>
<span style="color: #66cc66;">&#123;</span>
   <span style="color: #000000; font-weight: bold;">var</span> json:<span style="color: #0066CC;">Object</span> = JSON.<span style="color: #006600;">decode</span><span style="color: #66cc66;">&#40;</span>service.<span style="color: #006600;">loader</span>.<span style="color: #0066CC;">data</span><span style="color: #66cc66;">&#41;</span>;
   <span style="color: #000000; font-weight: bold;">var</span> person:PersonVO = <span style="color: #000000; font-weight: bold;">new</span> PersonVO<span style="color: #66cc66;">&#40;</span>json.<span style="color: #006600;">firstName</span>, json.<span style="color: #006600;">lastName</span>, json.<span style="color: #006600;">birthdate</span><span style="color: #66cc66;">&#41;</span>;
<span style="color: #66cc66;">&#125;</span></pre></div></div>

<p><strong>Refactored Code</strong>:</p>

<div class="wp_syntax"><div class="code"><pre class="actionscript" style="font-family:monospace;"><span style="color: #808080; font-style: italic;">/*
Note:
- createPerson validates you gave it a valid PersonVO.
- all errors within class are opt-in, no throw's. User has to register event listener to hear; #dontCreateGrenades
- class assumes single-concurrency if possible, kills previous load call before proceeding
- listens for all errors, and responds with 1 error with more detail logged if needed; simplifies API
- wraps actual call to verify SecurityError isn't thrown and if it is, it's logged w/ opt-in error
- uses united tested Factory for DRY parsing and assumes
- assumes Factory can fail, and reports it as such
- result in the form of a strongly-typed ValueObject in a read-only property to ensure proper API usage
*/</span>
<span style="color: #000000; font-weight: bold;">class</span> CreatePersonService <span style="color: #0066CC;">extends</span> EventDispatcher
<span style="color: #66cc66;">&#123;</span>
&nbsp;
   <span style="color: #0066CC;">private</span> <span style="color: #000000; font-weight: bold;">var</span> _savedPersonVO:PersonVO;
   <span style="color: #0066CC;">private</span> <span style="color: #000000; font-weight: bold;">var</span> loader:URLLoader;
&nbsp;
   <span style="color: #0066CC;">public</span> <span style="color: #000000; font-weight: bold;">function</span> <span style="color: #0066CC;">get</span> savedPersonVO<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>:PersonVO <span style="color: #66cc66;">&#123;</span> <span style="color: #b1b100;">return</span> _savedPerson; <span style="color: #66cc66;">&#125;</span>
&nbsp;
   <span style="color: #0066CC;">public</span> <span style="color: #000000; font-weight: bold;">function</span> CreatePersonService<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>
   <span style="color: #66cc66;">&#123;</span>
      <span style="color: #0066CC;">super</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
   <span style="color: #66cc66;">&#125;</span>
&nbsp;
   <span style="color: #0066CC;">public</span> <span style="color: #000000; font-weight: bold;">function</span> createPerson<span style="color: #66cc66;">&#40;</span>person:PersonVO<span style="color: #66cc66;">&#41;</span>:<span style="color: #0066CC;">void</span>
   <span style="color: #66cc66;">&#123;</span>
      _savedPersonVO = <span style="color: #000000; font-weight: bold;">null</span>;
&nbsp;
      <span style="color: #b1b100;">if</span><span style="color: #66cc66;">&#40;</span>person == <span style="color: #000000; font-weight: bold;">null</span><span style="color: #66cc66;">&#41;</span>
      <span style="color: #66cc66;">&#123;</span>
         onError<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;You cannot pass in a null person to create.&quot;</span><span style="color: #66cc66;">&#41;</span>;
         <span style="color: #b1b100;">return</span>;
      <span style="color: #66cc66;">&#125;</span>
&nbsp;
      <span style="color: #b1b100;">if</span><span style="color: #66cc66;">&#40;</span>loader == <span style="color: #000000; font-weight: bold;">null</span><span style="color: #66cc66;">&#41;</span>
      <span style="color: #66cc66;">&#123;</span>
         loader = <span style="color: #000000; font-weight: bold;">new</span> URLLoader<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
         loader.<span style="color: #006600;">addEventListener</span><span style="color: #66cc66;">&#40;</span>IOErrorEvent.<span style="color: #006600;">IO_ERROR</span>, onIOError<span style="color: #66cc66;">&#41;</span>;
         loader.<span style="color: #006600;">addEventListener</span><span style="color: #66cc66;">&#40;</span>SecurityErrorEvent.<span style="color: #006600;">SECURITY_ERROR</span>, onSecurityError<span style="color: #66cc66;">&#41;</span>;
         loader.<span style="color: #006600;">addEventListener</span><span style="color: #66cc66;">&#40;</span>Event.<span style="color: #006600;">COMPLETE</span>, onComplete<span style="color: #66cc66;">&#41;</span>;
      <span style="color: #66cc66;">&#125;</span>
      <span style="color: #b1b100;">else</span>
      <span style="color: #66cc66;">&#123;</span>
         <span style="color: #0066CC;">try</span>
         <span style="color: #66cc66;">&#123;</span>
            loader.<span style="color: #0066CC;">close</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
         <span style="color: #66cc66;">&#125;</span>
         <span style="color: #0066CC;">catch</span><span style="color: #66cc66;">&#40;</span><span style="color: #0066CC;">error</span>:<span style="color: #0066CC;">Error</span><span style="color: #66cc66;">&#41;</span>
         <span style="color: #66cc66;">&#123;</span>
            <span style="color: #808080; font-style: italic;">// only exception that is ok to swallow</span>
         <span style="color: #66cc66;">&#125;</span>
      <span style="color: #66cc66;">&#125;</span>
&nbsp;
      <span style="color: #0066CC;">try</span>
      <span style="color: #66cc66;">&#123;</span>
         <span style="color: #000000; font-weight: bold;">var</span> req:URLRequest = <span style="color: #000000; font-weight: bold;">new</span> URLRequest<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;http://someserver.com/restful/api/&quot;</span><span style="color: #66cc66;">&#41;</span>;
         req.<span style="color: #0066CC;">data</span> = person.<span style="color: #006600;">toJSON</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
         loader.<span style="color: #0066CC;">load</span><span style="color: #66cc66;">&#40;</span>req<span style="color: #66cc66;">&#41;</span>;
      <span style="color: #66cc66;">&#125;</span>
      <span style="color: #0066CC;">catch</span><span style="color: #66cc66;">&#40;</span><span style="color: #0066CC;">error</span>:<span style="color: #0066CC;">Error</span><span style="color: #66cc66;">&#41;</span>
      <span style="color: #66cc66;">&#123;</span>
         onError<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;CreatePersonService::createPerson, error: &quot;</span> + <span style="color: #0066CC;">error</span><span style="color: #66cc66;">&#41;</span>;
      <span style="color: #66cc66;">&#125;</span>
   <span style="color: #66cc66;">&#125;</span>
&nbsp;
   <span style="color: #0066CC;">private</span> <span style="color: #000000; font-weight: bold;">function</span> onIOError<span style="color: #66cc66;">&#40;</span>event:IOErrorEvent<span style="color: #66cc66;">&#41;</span>:<span style="color: #0066CC;">void</span>
   <span style="color: #66cc66;">&#123;</span>
      onError<span style="color: #66cc66;">&#40;</span>event.<span style="color: #0066CC;">text</span><span style="color: #66cc66;">&#41;</span>;
   <span style="color: #66cc66;">&#125;</span>
&nbsp;
   <span style="color: #0066CC;">private</span> <span style="color: #000000; font-weight: bold;">function</span> onSecurityError<span style="color: #66cc66;">&#40;</span>event:SecurityErrorEvent<span style="color: #66cc66;">&#41;</span>:<span style="color: #0066CC;">void</span>
   <span style="color: #66cc66;">&#123;</span>
      onError<span style="color: #66cc66;">&#40;</span>event.<span style="color: #0066CC;">text</span><span style="color: #66cc66;">&#41;</span>;
   <span style="color: #66cc66;">&#125;</span>
&nbsp;
   <span style="color: #0066CC;">private</span> <span style="color: #000000; font-weight: bold;">function</span> onComplete<span style="color: #66cc66;">&#40;</span>event:Event<span style="color: #66cc66;">&#41;</span>:<span style="color: #0066CC;">void</span>
   <span style="color: #66cc66;">&#123;</span>
      <span style="color: #0066CC;">try</span>
      <span style="color: #66cc66;">&#123;</span>
         _savedPersonVO = PersonFactory.<span style="color: #006600;">parsePersonFromJSON</span><span style="color: #66cc66;">&#40;</span>loader.<span style="color: #0066CC;">data</span><span style="color: #66cc66;">&#41;</span>;
         <span style="color: #b1b100;">if</span><span style="color: #66cc66;">&#40;</span>_savedPersonVO <span style="color: #66cc66;">!</span>= <span style="color: #000000; font-weight: bold;">null</span><span style="color: #66cc66;">&#41;</span>
         <span style="color: #66cc66;">&#123;</span>
            dispatchEvent<span style="color: #66cc66;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> Event<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;success&quot;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>;
         <span style="color: #66cc66;">&#125;</span>
         <span style="color: #b1b100;">else</span>
         <span style="color: #66cc66;">&#123;</span>
            onError<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;CreatePersonService::onComplete, factory returned a null PersonVO.&quot;</span><span style="color: #66cc66;">&#41;</span>;
         <span style="color: #66cc66;">&#125;</span>
      <span style="color: #66cc66;">&#125;</span>
      <span style="color: #0066CC;">catch</span><span style="color: #66cc66;">&#40;</span><span style="color: #0066CC;">error</span>:<span style="color: #0066CC;">Error</span><span style="color: #66cc66;">&#41;</span>
      <span style="color: #66cc66;">&#123;</span>
         onError<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;CreatePersonService::onComplete, parsing error: &quot;</span> + <span style="color: #0066CC;">error</span><span style="color: #66cc66;">&#41;</span>;
      <span style="color: #66cc66;">&#125;</span>
   <span style="color: #66cc66;">&#125;</span>
&nbsp;
   <span style="color: #0066CC;">private</span> <span style="color: #000000; font-weight: bold;">function</span> onError<span style="color: #66cc66;">&#40;</span>errorString:<span style="color: #0066CC;">String</span><span style="color: #66cc66;">&#41;</span>:<span style="color: #0066CC;">void</span>
   <span style="color: #66cc66;">&#123;</span>
      <span style="color: #0066CC;">trace</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;ERROR: CreatePersonService::onError: &quot;</span> + errorString<span style="color: #66cc66;">&#41;</span>;
      dispatchEvent<span style="color: #66cc66;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> Event<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;error&quot;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>;
   <span style="color: #66cc66;">&#125;</span>
<span style="color: #66cc66;">&#125;</span></pre></div></div>

<p><strong>Step #4: Fine Tuning</strong></p>
<p>If you made it this far, and have managed to continue to maintain the above, congratulations! This stuff is icing on the cake. You can continue onto <a href="http://martinfowler.com/refactoring/catalog/index.html">smaller scope refactorings</a>, as well as continuing to increase your unit test coverage.</p>
<p><strong>Final Tips</strong></p>
<ol>
<li>When casting, ensure result is not null before using. If null, log the casting failure.</li>
<li>For Flash Player, set ExternalInterface.marshallExceptions = true if using ExternalInterface</li>
<li>Log all errors</li>
<li>Code Review. Often. Weekly. Whatever, pick a schedule.</li>
<li>Object / * / Dictionary == if you can&#8217;t avoid, wrap with unit tests</li>
<li>Remember: small, low-risk changes.</li>
<li>TODO was invented for a reason.</li>
<li>If you haven&#8217;t committed to source control for 3 full days of working, abort and just check into a branch for later revisiting/reference.</li>
</ol>
<p><strong>Conclusions</strong></p>
<p>Remember, the most important refactoring you can possibly do is reading the code base for 1 hour a day, no more. Just 1 person. This is has more positive impact than good unit test coverage. Daily code reviews, even in isolation, are extremely important. The earlier in the project life cycle, the better.</p>
<p>From that, you can make small, low risk changes. Keep track with TODO&#8217;s. Breathe, Rome wasn&#8217;t fixed in a day, and a pile of rubbish wasn&#8217;t fixed in one either.</p>
<p>For further, positive refactorings you can check an older <a href="http://martinfowler.com/refactoring/catalog/">list by Martin Fowler</a>, and <a href="http://www.amazon.com/Working-Effectively-Legacy-Michael-Feathers/dp/0131177052/ref=sr_1_1?ie=UTF8&amp;qid=1333060864&amp;sr=8-1">this book</a> has a ton of wonderful ones + tests as well. While a Code Review has decreasing value the more people you add in terms of defects found, the ability to learn &amp; make positive suggestions for architecture are wonderful. If you&#8217;re alone, use <a href="http://codereview.stackexchange.com/">codereview.stackexchange.com</a>.</p>
<p>In the next article I&#8217;ll show you how to get help with the above&#8230; and permission.</p>
<img src="http://feeds.feedburner.com/~r/jessewarden/~4/m8ONvxMgRcg" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://jessewarden.com/2012/04/consulting-chronicles-6-refactoring.html/feed</wfw:commentRss>
		<slash:comments>3</slash:comments>
		<feedburner:origLink>http://jessewarden.com/2012/04/consulting-chronicles-6-refactoring.html?utm_source=rss&amp;utm_medium=rss&amp;utm_campaign=consulting-chronicles-6-refactoring</feedburner:origLink></item>
		<item>
		<title>Positive Notes on Week 3 of P90X</title>
		<link>http://feedproxy.google.com/~r/jessewarden/~3/LMfFYo_GJHE/positive-notes-on-week-3-of-p90x.html</link>
		<comments>http://jessewarden.com/2012/03/positive-notes-on-week-3-of-p90x.html#comments</comments>
		<pubDate>Sat, 24 Mar 2012 22:15:14 +0000</pubDate>
		<dc:creator>JesterXL</dc:creator>
				<category><![CDATA[Flex]]></category>
		<category><![CDATA[beachbody]]></category>
		<category><![CDATA[excercise]]></category>
		<category><![CDATA[p90x]]></category>
		<category><![CDATA[workout]]></category>

		<guid isPermaLink="false">http://jessewarden.com/?p=3071</guid>
		<description><![CDATA[I started P90X 3 weeks ago for the first time with her majesty. I&#8217;m generally a positive person so I thought I&#8217;d write down some of my challenges I had and how things have changed in a short time frame. &#8230; <a href="http://jessewarden.com/2012/03/positive-notes-on-week-3-of-p90x.html">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>I started <a href="http://p90x.com">P90X</a> 3 weeks ago for the first time with her majesty. I&#8217;m generally a positive person so I thought I&#8217;d write down some of my challenges I had and how things have changed in a short time frame.</p>
<p><span id="more-3071"></span><strong>Why P90X?</strong><br />
I&#8217;m a programmer who&#8217;s a work-a-holic so I sit for 12+ hours a day, 7 days a week. Recently, my part of the tech industry has gone into major upheaval (change is a constant, but this was crazy), and the only thing I can control about it is my well being to adapt to the change. I always found exercise to be a positive outlet; strength training for the frustration when code doesn&#8217;t work or a client drives me bonkers, and cardio for keeping my body warm and not achy from sitting so long. My business partner is a meat head and always raves about P90X that he and his wife do together, so I thought I&#8217;d give it a try.</p>
<p><strong>Personal/Life Challenges</strong></p>
<ul>
<li>I hadn&#8217;t worked out in 4 years (used to do strength training + too much cardio 3 times a week). I couldn&#8217;t even pass the test they suggest you pass before you start P90X, but I forged ahead anyway. #growl</li>
<li>I run my own business so even if I only bill for 5 hours in the day, I still work 14. Being in software, you have to constantly research/read/experiment to stay up to date; this isn&#8217;t an option, you just have to do it whether you want to or not (most of us do via our short attention spans). I have to do this in addition to everything else required to run a small business (taxes, paperwork, lead generation, dealing with <strike>insane</strike> clients, etc). As such, time is in short supply, and valuable, for me.</li>
<li>I have 2 young kids who are spaztastic like me.</li>
<li>I&#8217;m a <a href="http://pintley.com/">beer</a> <a href="http://untappd.com/">snob</a>. I like trying new beers every few weeks, from light to dark, foreign and domestic. Water weight.</li>
<li>I&#8217;m not attempting to do the P90X diet. I want to, but not for round 1.</li>
<li>I&#8217;m taking zero supplements, nor shakes. While I&#8217;ve found positive results from protein bars when I was younger, nothing of the sort here.</li>
<li>I&#8217;m &#8220;not 23&#8243;, lulz. I&#8217;m 32. My metabolism is not what it was at 18 &#8211; 24 where I could eat 10 billion things and show nothing.</li>
</ul>
<p><strong>Results</strong></p>
<p>So what&#8217;s positive that&#8217;s happened 3 weeks in?</p>
<ol>
<li>I found some &#8220;brand new&#8221; jeans from 4 years ago that I could fit into (32/32 vs 34/32). I wasn&#8217;t really trying to lose weight, just feel better and bulk up. 3 weeks in, though, clearly my beer stocked stomach is showing results.</li>
<li>The first week I couldn&#8217;t even use weights. Week 3 I&#8217;ve maxed out to the 27lb band (red one) for most work outs, falling back to the black one for some of the harder arm/leg exercises. I&#8217;m already having to order heavier bands and maybe a few free weights for some of the leg exercises I&#8217;d rather use dumbbells for.</li>
<li>Week 1 and 2, I couldn&#8217;t finish Kenpo X. Today, I did and only did 18 of the 20 reps on 2 of the exercises. Next time, I know for a fact I&#8217;ll finish no problem.</li>
<li>First time Yoga, I couldn&#8217;t do half of the poses. Now, I&#8217;m just getting my tail kicked by Warrior 3 and Half-No-One-Is-Supposed-To-Bend-That-Way-Moon. While all my poses aren&#8217;t perfect, it&#8217;s insane how quickly I got better at doing + holding just 3 weeks in. I&#8217;m uber paranoid about hurting myself so am pretty impressed.</li>
<li>Anytime a stretch required me to stand, lean to the floor with my hands and touch it, I&#8217;d get my hands to my knees. Now I can touch the floor. 2 years of working out on my own I never was able to do that; it shows just how much repetition + following P90X&#8217;s lead can really make you more flexible.</li>
<li>I only got <a href="http://www.amazon.com/gp/product/B000UOD5QM/ref=oh_o01_s00_i01_details">a heart rate monitor</a> (+ <a href="http://new.digifit.com/">app</a> + <a href="http://www.amazon.com/gp/product/B004GIKYDK/ref=oh_o01_s00_i00_details">connector</a>) 2nd week in, but already it&#8217;s a lot easier to keep my heart rate in the zone. Yes, I do try to raise it, but I&#8217;m just amazed at how good I feel even in Zone 3 and 4&#8230; (yes, was on the floor week 1 and 2 breathing heavily, not moving).</li>
<li>I could only do 1 pull up the entire workout week 1. Using the <a href="http://www.amazon.com/gp/product/7245456313/ref=oh_o00_s01_i00_details">bands</a> + chair combo sometimes, I can do a lot more, improving week to week. I&#8217;m still not happy with my current state, but looking at the worksheets, I&#8217;ve seriously improved. I thought it&#8217;d take 2 months, but apparently it doesn&#8217;t.</li>
<li>As I slouch a variety of ways, whether at my desk or at <a href="http://starbucks.com">Starbucks</a> (other office), my legs will sometimes fall asleep if I get lost in the code. It used to take 15 minutes for an asleep limb to stop being in pain and wake up. Now it takes 15 seconds. I actually made my leg fall asleep on purpose the other day because I thought it was a fluke. That took me 2 1/2 months to get to back when I was working out 3 days a week even with a personal trainer (who cost bling I might add).</li>
</ol>
<p>&#8230;the other positive thing that&#8217;s happened, and I didn&#8217;t intend for this, is that some of my friends who were doing P90X, unbeknownst to me, have being inspired to bring it more. Others who were on the fence about trying it have said they&#8217;d look into it. Two unrelated people have said the same thing: &#8220;The DVD&#8217;s have been on my shelf, un-opened for awhile&#8230; maybe I&#8217;ll try it next Monday.&#8221;</p>
<p>Remember folks, this scrawny, beer bellied work-a-holic programmer is getting results in 3 weeks in, feels better emotionally, and I&#8217;m only doing 80% of my physical best because of my lack of previous fitness + no good diet + 2 year old hugging me during leg squats + 4 year old falling on me during Yoga + her majesty demanding I do more cardio in addition to my regular P90X schedule. I&#8217;ve even switched to more wine vs. beer just because I don&#8217;t want to ruin this momentum.</p>
<p>Finally, if you&#8217;re still not losing enough fat to visibly see a difference, reading <a href="http://www.weightloss-hq.biz/weight-loss-forum/beginners-corner/what-to-expect-during-p90x.html">this thread</a> on another forum helped a few people I know feel better.</p>
<p>So good luck and continue to bring it!</p>
<img src="http://feeds.feedburner.com/~r/jessewarden/~4/LMfFYo_GJHE" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://jessewarden.com/2012/03/positive-notes-on-week-3-of-p90x.html/feed</wfw:commentRss>
		<slash:comments>11</slash:comments>
		<feedburner:origLink>http://jessewarden.com/2012/03/positive-notes-on-week-3-of-p90x.html?utm_source=rss&amp;utm_medium=rss&amp;utm_campaign=positive-notes-on-week-3-of-p90x</feedburner:origLink></item>
		<item>
		<title>Building An Elevator in Box2D</title>
		<link>http://feedproxy.google.com/~r/jessewarden/~3/8X5yyUGhgPU/building-an-elevator-in-box2d.html</link>
		<comments>http://jessewarden.com/2012/02/building-an-elevator-in-box2d.html#comments</comments>
		<pubDate>Thu, 23 Feb 2012 16:00:16 +0000</pubDate>
		<dc:creator>JesterXL</dc:creator>
				<category><![CDATA[Flex]]></category>
		<category><![CDATA[android]]></category>
		<category><![CDATA[box2d]]></category>
		<category><![CDATA[coronasdk]]></category>
		<category><![CDATA[gaming]]></category>
		<category><![CDATA[lua]]></category>
		<category><![CDATA[mobile]]></category>
		<category><![CDATA[programming]]></category>

		<guid isPermaLink="false">http://jessewarden.com/?p=3048</guid>
		<description><![CDATA[Introduction It took me 4 days to build an Elevator via Box2D in Corona SDK. I wrote the actual code and API for it in about 30 minutes. Getting the physics to work proved way more challenging than I anticipated. &#8230; <a href="http://jessewarden.com/2012/02/building-an-elevator-in-box2d.html">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p><strong>Introduction</strong></p>
<p>It took me 4 days to build an Elevator via <a href="http://box2d.org/">Box2D</a> in <a href="http://anscamobile.com">Corona SDK</a>. I wrote the actual code and API for it in about 30 minutes. Getting the physics to work proved way more challenging than I anticipated. I&#8217;m still learning the ins and outs of Box2D as it relates to game development, so wanted to report on how I went about it and what I learned.</p>
<p><span id="more-3048"></span>The following article talks about how I&#8217;m using Box2D in my game, the 4 approaches I took to building an elevator, and what I eventually decided upon.</p>
<p>Please keep in mind some of the things below are related to Corona SDK&#8217;s implementation of Box2D. Thus, some of the issues and compensation measures I took may not need to be done, nor happen, in other implementations and platforms.</p>
<p><strong>Why An Elevator?</strong></p>
<p>Elevators provide an interesting transition in both games and <a href="http://unrealitymag.com/index.php/2010/03/22/elevator-scenes-in-movies/">movies</a>. They also provide easier ways for game developers to unload and load a level, provide a rest for the player, and/or make it easy to provide cut scene dialogue to prepare for the player for an upcoming part. In a lot of horror movies, they actually are the focal point of a lot of scary scenes such as <a href="http://www.youtube.com/watch?v=wexyYCt_0_c&amp;t=4m53s">Resident Evil</a>, and also provide a perfect setting for <a href="http://tvtropes.org/pmwiki/pmwiki.php/Main/UncomfortableElevatorMoment">comedic relief</a> such as such as Spiderman 2 and <a href="http://www.youtube.com/watch?v=S2ua0UCrzxs&amp;t=4m0s">Deep</a> <a href="http://www.youtube.com/watch?v=n4HAfe14i_M">Rising</a> (good ole <a href="http://tvtropes.org/pmwiki/pmwiki.php/Main/TheElevatorFromIpanema">Ipanema</a>).</p>
<p>One of my favorite easter eggs was from Max Payne was in an elevator. You walk into a shoddy NYC apartment building elevator alone, with the notorious off-kilter 3rd person camera. Combined with the absurd brightness in the elevator&#8217;s interior amongst a very noir game, the tell tale &#8220;elevator muzak&#8221; is playing. If you shoot the overhead speaker, Max utters a smirk filled, 2nd word annunciated &#8220;<a href="http://www.youtube.com/watch?v=Z53X9CxHiOE">Thank you!</a>&#8220;.</p>
<p>Romance, fear, death. In such a confined space clearly only meant for short periods of stay, elevators can force us to view the human condition ever more clearly. Many writers play up the claustrophobia aspect, the lack of control as a metaphor for life taking us where it wills to, or preying on our fear of the unknown when you hear bad things just outside the lift walls.</p>
<p>It also helps players in games get from one floor to another in a controlled manner. Kind of like they do in the real world.</p>
<p><strong>How Does Mine Need to Work?</strong></p>
<p>A game I&#8217;m building requires that a character inside a building go up a floor in the building he is in. It&#8217;s based on a Brooklyn apartment building that has 13 floors with 12 ft ceilings. The character is on the 12th floor and needs to use the standard elevator. It has a call switch on the outside. You press a button and the elevator will arrive at the floor the button was pressed. You can optionally walk into the elevator and press the up or down buttons for the same effect. The elevator does not move on it&#8217;s own, only when a button is pressed. It currently only operates on 2 floors.</p>
<p>Simple, right? Code wise, it was. Here&#8217;s the <a href="https://github.com/JesterXL/ZombieStick/blob/StateMachineBranch/code/com/jxl/zombiestick/gamegui/levelviews/Elevator.lua">Lua class on Github</a>. The only thing to really note is the goUp, goDown, and tick functions. The goUp and goDown simply set flags so the elevator knows where to go. The tick function handles the actual movement via the <a href="https://github.com/JesterXL/ZombieStick/blob/StateMachineBranch/code/com/jxl/zombiestick/core/GameLoop.lua">game loop</a>. Distance joints, which I&#8217;ll cover in a minute, are not powered by motors, so I just increment or decrement the length to move it up or down.</p>
<p><strong>Brief On Box2D</strong></p>
<p>I&#8217;ve fully committed to Box2D. That means that a lot of things are handled for me such as gravity, forces, and collisions&#8230; basically all the physics code. If you&#8217;re not familiar with Box2D, here&#8217;s a brief synopsis.</p>
<p>From the <a href="http://box2d.org/about/">site</a>:</p>
<blockquote><p>Box2D is an open source C++ engine for simulating rigid bodies in 2D. Box2D is developed by Erin Catto&#8230;</p></blockquote>
<p>It&#8217;s basically a physics engine for games, although it can be used for other things as well. It&#8217;s been ported to a lot of other languages and platforms, such as <a href="http://box2dflash.sourceforge.net/">ActionScript</a>, <a href="http://code.google.com/p/dartbox2d/">Dart</a>, and <a href="http://box2d-js.sourceforge.net/">JavaScript</a>.</p>
<p>It&#8217;s recently regained popularity because it can ease the creation of <a href="http://seb.ly/2012/01/live-iphone-coding-video-now-online/">Angry Birds</a> like games.</p>
<p><iframe width="640" height="360" src="http://www.youtube.com/embed/LBnBml2KFFk" frameborder="0" allowfullscreen></iframe></p>
<p><strong>Box2D Constraints</strong></p>
<p>You give up a lot of control when you use Box2D and also have to develop a certain way. For example, all bodies (or things in the world that can bump into each other) default to dynamic. This means they are affected by gravity, which you usually default to <a href="http://en.wikipedia.org/wiki/Terminal_velocity">9.8</a> to simulate the real world.</p>
<p>If you&#8217;ve read the <a href="http://oos.moxiecode.com/blog/tutorials/tilebased-games-in-flash-5-part-12/">Jailbitch</a> tutorials and/or others of it&#8217;s ilk, you basically write code like:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;">thisObject.<span style="color: #660066;">y</span> <span style="color: #339933;">+=</span> speed<span style="color: #339933;">;</span>
<span style="color: #000066; font-weight: bold;">if</span><span style="color: #009900;">&#40;</span>thisObject.<span style="color: #660066;">y</span> <span style="color: #339933;">&gt;=</span> theGround.<span style="color: #660066;">y</span><span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
	stopFalling<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	thisObject.<span style="color: #660066;">y</span> <span style="color: #339933;">=</span> theGround.<span style="color: #660066;">y</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>Notice that gravity is applied, by you, on a per object basis. No code, no gravity. No code, no collisions.</p>
<p>This makes building elevators, or &#8220;platforms that raise up and down&#8221; pretty straightforward. You just increase or decrease the y value of an object. You can detect to see if the character is touching the elevator, and make sure she rises and falls with the platform.</p>
<p><strong>Using Y</strong></p>
<p>In Box2D, all dynamic objects have gravity by default and all the collisions are handled for you. Additionally, how the collisions happen can be tweaked on a per object basis if you like. Things like how heavy something is hitting something soft, the friction, and the bounce. You do not have to write any code for this; it&#8217;s just how the world works.</p>
<p>However, making a dynamic object in Box2D rise and fall isn&#8217;t as straightforward as you would think. Box2D has a neat feature which allows developers to set a body&#8217;s x and y value, and it&#8217;ll apply the necessary gravity, forces, and collisions at the next redraw/tick. However, if you want something to move up, you have to treat it JUST like you would in the real world: through <a href="http://www.youtube.com/watch?v=YI-JC6w_Eqc">force</a> (NSFW).</p>
<p>If I immediately set an apple above my head at a y of 0, it&#8217;ll eventually fall on my head. If I want to stay there, I have to keep setting it to 0 using an enter frame/interval/timer&#8230; like a juggler. That&#8217;s redonk.</p>
<p><strong>Using Forces</strong></p>
<p>Box2D provides, at least in Corona SDK, a variety ways of applying force; as an impulse/jolt as well as force over time. The 2 in particular are <a href="http://developer.anscamobile.com/reference/index/bodyapplyforce">body:applyForce</a> and <a href="http://developer.anscamobile.com/reference/index/bodyapplylinearimpulse">body:applyLinearImpulse</a>.</p>
<p>The applyLinearImpulse is momentary jolt or shove.</p>
<p><iframe width="640" height="360" src="http://www.youtube.com/embed/cluijVRD6WQ" frameborder="0" allowfullscreen></iframe></p>
<p>The applyForce is like a jet pack; you have to continually apply it via a timer/tick/enter frame to move something.</p>
<p><iframe width="640" height="360" src="http://www.youtube.com/embed/VThnqp3ALkM" frameborder="0" allowfullscreen></iframe></p>
<p>As you can see, this makes things more complicated. Instead of simply &#8220;moving an object by changing it&#8217;s y position&#8221; you&#8217;re now having to compensate for the gravity of t3h erf.</p>
<p><strong>Using Kinematic Bodies</strong></p>
<p>The other simpler option is to utilize kinematic bodies. Instead of dynamic, kinematic allows a body to be affected by forces, like things bumping into it, the functions above, but NOT gravity. Ideal for an elevator, right? In theory yes. I&#8217;ll explain why I didn&#8217;t end up going this route in a bit. The only drawback here is that kinematic objects don&#8217;t &#8220;look&#8221; like real world objects. They don&#8217;t &#8220;sway&#8221; in the wind, or of something pushes it it just slightly moves. It doesn&#8217;t look &#8220;real&#8221; and defeats the purpose of using Box2D. While following <a href="http://en.wikipedia.org/wiki/Newton's_laws_of_motion">Newton&#8217;s Laws of Motion</a>, it looks like an elevator in space vs. on Earth with gravity.</p>
<p>The whole point of kinematic is for the user to drag them via touch or mouse, for cut scene animations where a character can still affect the physical world but you need to move elsewhere&#8230; or for things you specifically don&#8217;t want to be affected by gravity.</p>
<p><strong>Using Joints</strong></p>
<p>The 3rd option is constructing a realistic elevator so that Box2D can do it&#8217;s job: simulate rigid bodies in a 2D space. The mantra I&#8217;ve heard repeated by those more experienced in Box2D is keep it simple (or just abandon Box2D and write it yourself&#8230; but um&#8230; no). Instead of building a real car in Box2D, just build simple geometry (bodies and joints), and let the image of the car itself make the player think it&#8217;s real.</p>
<p>An elevator in Box2D terms is basically a box you can walk in and has a cable that attaches the box to a firm ceiling. This means, you create 2 boxes and a joint.</p>
<p>&#8230;but what TYPE of joint? And how do you apply it? THAT is what took 4 days.</p>
<p><strong>Version 1: Distance Joint</strong></p>
<p>A distance joint is a line that connects 2 things. You can shorten the line, and like a fishing pole, will reel in the body it&#8217;s attached to while it&#8217;s dangling below. Perfect for an elevator right?</p>
<p><iframe width="640" height="360" src="http://www.youtube.com/embed/elfceCfHX4c" frameborder="0" allowfullscreen></iframe></p>
<p>Bleh.</p>
<p>My first problem was the box was off-kilter. I made it in a C shape so the player could walk in with a wall to the right, and a ceiling to connect the joint too. Being a non-square, however, this made the elevator&#8217;s weight distribution un even. It would immediately rotate even if nothing was on it because the weight of the right wall was heavier then the left side with none.</p>
<p>While increasing the friction the elevator had the consistency of velcro, thus ensuring our character wouldn&#8217;t fall out, if the player DID walk left, they&#8217;d plummet to their death in the elevator shaft, even if you made the shaft just wide enough to fix the box. While you could shrink the shaft and increase <a href="http://developer.anscamobile.com/reference/index/physicssetpositioniterations">Box2D&#8217;s sensitivity</a>, it&#8217;d sometimes get stuck.</p>
<p><iframe width="640" height="360" src="http://www.youtube.com/embed/YD6rdYuEK-I" frameborder="0" allowfullscreen></iframe></p>
<p>While I could set <a href="http://developer.anscamobile.com/reference/index/bodyisfixedrotation">isFixedRotation</a> to ensure the elevator no longer rotated, and make the distance joint a little more like a rubber band via its frequency and dampingRatio properties, it still didn&#8217;t look as cool.</p>
<p><strong>Version 2: Multiple Distance Joints</strong></p>
<p>Most modern elevators nowadays have a variety of attachments beyond a single cable. Magnetic locks with tracks&#8230; and usually more than 1 cable. So, I did the same thing and added 2 more cables to compensate.</p>
<p><iframe width="640" height="360" src="http://www.youtube.com/embed/phnU11TTXNc" frameborder="0" allowfullscreen></iframe></p>
<p>At first, I was like eureka. But then I hit problems, and was like, no wai!</p>
<p>For some reason, if I changed the length of the first joint to reel in the elevator, AND set the other 2 joints to have the same length&#8230; sometimes it didn&#8217;t work. Yes, the values would change, but the elevator would just remain stuck. !? I don&#8217;t know if this was my code, the Corona simulator, or&#8230; Box2D.</p>
<p>At any rate, our intrepid heros can&#8217;t run from zombies if an elevator &#8220;sometimes works&#8221;. While a great plot device, it&#8217;s only good if I can control said plot device.</p>
<p><strong>Version 3: Piston Joint</strong></p>
<p>Piston joints are just that: a piston. You can control and constrain their linear movement so moves just like a normal hydraulic piston on carnival rides, etc. Fine, I&#8217;ll lose the elevator swaying/dangling behavior, but with piston constraints, it should make the coding easier, right?</p>
<p><iframe width="640" height="480" src="http://www.youtube.com/embed/rzNjNBKYuGI" frameborder="0" allowfullscreen></iframe></p>
<p>Wrong.</p>
<p>Piston constraints, and Box2D in general in Corona totally breaks down when you introduce groups. In HTML, this is div&#8217;s within div&#8217;s. In Flash, this is Sprites within Sprites. In Corona, Groups are basically the same thing. When creating a game level, you can put the whole thing in a group, and just move the group to move your level.</p>
<p>Box2D, however, doesn&#8217;t like this at all. It assumes all bodies are in a same group. While you CAN put things in different groups, things get visually very strange.</p>
<p>Here is some boxes on top of each other.</p>
<p><iframe width="640" height="480" src="http://www.youtube.com/embed/aXQM2feMlSQ" frameborder="0" allowfullscreen></iframe></p>
<p>Now, here&#8217;s where I move the group the 2nd box is in. You&#8217;ll see boxes pile on top of one another even though visually they are floating in space.</p>
<p><iframe width="640" height="480" src="http://www.youtube.com/embed/DGR-F9M8TXw" frameborder="0" allowfullscreen></iframe></p>
<p>This change of global space also affects calls to the pistons setLimit function. Given <a href="http://lua.org">Lua</a> in Corona doesn&#8217;t have a lot of built in methods to affect coordinate space on the fly, you&#8217;re pretty much forced to keep things in a single group to keep it simple. While fine, you still have to CONTINUALLY update the coordinate space&#8230; and that doesn&#8217;t work if you a lot of classes affecting this as well as the fact that joints can move.</p>
<p><strong>Version 4: Kinematic Floor</strong></p>
<p>I knew I could knock this out in 20 minutes in Flash. So&#8230; I coded it like I could code it in Flash: Make a box, decrease its y to move it up, increase its y to move it down. In simple tests, this worked great. Again, I lost the realism factor (the whole point of using Box2D beyond saving a lot of code writing for collisions), but whatever, you MUST git-r-done and move on. Analysis paralysis == bad news bears. Kill t3h scope creep, man.</p>
<p>&#8230;however, once I applied <a href="http://developer.anscamobile.com/forum/2010/10/25/collision-filters-helper-chart">collision filters</a>, this fell on it&#8217;s face. The same exact code works just fine using a dynamic body, but kinematic? <a href="http://darthno.ytmnd.com/">NOoooooOOOOOooo</a>&#8230;.</p>
<p><iframe width="640" height="360" src="http://www.youtube.com/embed/cwARXbQHnKg" frameborder="0" allowfullscreen></iframe></p>
<p>Debugging collision filters are impossible; they either work, or they don&#8217;t, and your only 2 options are to check your math again or give up. The most frustrating part is that collision filters are the main reason I like using Box2D vs. my own code. When they break (or appear to&#8230; no way my math is wrong&#8230; ever&#8230; specially when I&#8217;m changing the body type&#8230; right?), they erode to whole purpose of using Box2D in the first place.</p>
<p>I have a rule: if you can&#8217;t solve something in an hour, it&#8217;s time to move on. Whether that&#8217;s another problem/bug/feature, or solution in this case, so be it. So that&#8217;s what I did. My #&#8217;s checked out, but even in the isolation tests I did, the kinematic box would NOT collide with my character and no collision events were dispatched.</p>
<p>Things got REALLY weird when I created complex bodies using filters for each part; you can see the kruft multiple body code in the elevator class on github. Totally unrelated geometry would act very strange. I&#8217;m pretty positive it&#8217;s a bug in Ansca&#8217;s implementation as I suspect most are merely creating a single polygonal body for complex shapes vs. multiple (like I was for my floor, wall, and elevator ceiling).</p>
<p>Maybe if I spent another hour with a lot of sleep and no kids around I could figure it out, but the rule is there for a reason.</p>
<p><strong>Solution</strong></p>
<p>So I went back to Version 1 and just turned isFixedRotation to true. I also found that sometimes the elevator&#8217;s distance joint would get stuck at the top or bottom and even with a high maxMotorForce, the joint was simply incapable of dislodging the elevator. Worse, the values WOULD continue to change and I&#8217;d receive no code errors, and visually nothing would change. Simply applying some light applyLinearImpulse (a quick jolt) up or down fixed it every time.</p>
<p>Now, when my character passes by an elevator switch or touches the elevator, the GUI appears for him to go up or down. He&#8217;d sometimes fall through the 20 pixel floor, so I increased the Box2D <a href="http://developer.anscamobile.com/reference/index/physicssetpositioniterations">position sensitivity</a> from 8 to 10, slowed down the elevator a tad, and this seemed to fix it. Increasing the Elevator floor&#8217;s height + density seemed to help as well.</p>
<p><strong>Conclusions</strong></p>
<p>As you can see, what I thought would be simple was made harder by my not knowing the quirks of Box2D, nor having built an Elevator with floor collisions before. That said, Box2D is really fun, and I can see how the more I learn about it, the more time it saves me for certain types of things&#8230; like my <a href="http://www.youtube.com/watch?v=BjGIhff0QDU">Die Hard</a> fire hose.</p>
<p><iframe width="640" height="360" src="http://www.youtube.com/embed/-8o_vaTCaJo" frameborder="0" allowfullscreen></iframe></p>
<p>Basically, the things I need to keep in mind and learned:</p>
<ol>
<li>Keep all Box2D objects in Corona in a single Display Object; inject child dependencies if a class needs to create composited objects</li>
<li>If a joint has a length &amp; motor, but things get stuck, try increasing the body&#8217;s density, reduce nearby body&#8217;s friction, and applying a tincy bit of impulse to &#8220;git er unstuck&#8221;&#8221;.</li>
<li>Create visual test harnesses; a place where you can test your components in isolation. It&#8217;s amazing how frustrating debugging reference points are in Corona SDK as a Flash Developer. In Flash, everything is aligned top left unless you move stuff manually. You can&#8217;t even edit the registration point. In Corona, my convention is to default everything to <a href="http://developer.anscamobile.com/reference/index/objectsetreferencepoint">top left</a> to emulate how Flash works, and thus make my visual alignment coding appear cleaner&#8230; except for groups. Being able to test the elevator alone, and then in game, allowed me to quickly diagnose problems.</li>
<li>To heck with you piston joint. You&#8217;re awesome, but until Corona makes it easier for you to adjust being in a different global coordinate space, I&#8217;m sticking with <a href="http://developer.anscamobile.com/content/game-edition-physics-joints">distance and touch joints</a>.</li>
<li>I really wish I knew why my kinematic bodies aren&#8217;t working with my collision filters. In isolated tests, it works just fine.</li>
</ol>
<p>I hope this helps you in your Box2D adventures.</p>
<img src="http://feeds.feedburner.com/~r/jessewarden/~4/8X5yyUGhgPU" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://jessewarden.com/2012/02/building-an-elevator-in-box2d.html/feed</wfw:commentRss>
		<slash:comments>1</slash:comments>
		<feedburner:origLink>http://jessewarden.com/2012/02/building-an-elevator-in-box2d.html?utm_source=rss&amp;utm_medium=rss&amp;utm_campaign=building-an-elevator-in-box2d</feedburner:origLink></item>
		<item>
		<title>Sencha Ext JS is Viable Technology Choice for Flex Developers</title>
		<link>http://feedproxy.google.com/~r/jessewarden/~3/ycRuRkY9eK4/sencha-ext-js-is-viable-technology-choice-for-flex-developers.html</link>
		<comments>http://jessewarden.com/2012/02/sencha-ext-js-is-viable-technology-choice-for-flex-developers.html#comments</comments>
		<pubDate>Tue, 14 Feb 2012 15:10:01 +0000</pubDate>
		<dc:creator>JesterXL</dc:creator>
				<category><![CDATA[Flex]]></category>
		<category><![CDATA[ActionScript]]></category>
		<category><![CDATA[adobe]]></category>
		<category><![CDATA[coffeescript]]></category>
		<category><![CDATA[enterprise]]></category>
		<category><![CDATA[extjs]]></category>
		<category><![CDATA[Flash]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[mvc]]></category>
		<category><![CDATA[sencha]]></category>
		<category><![CDATA[touch]]></category>

		<guid isPermaLink="false">http://jessewarden.com/?p=3015</guid>
		<description><![CDATA[Below, I describe my experiences with Ext JS after the Sencha Fast Track training, my challenges with doing browser based work in a consulting context, and my thoughts on why it matters to Flex Developers. I&#8217;m in a hurry. I &#8230; <a href="http://jessewarden.com/2012/02/sencha-ext-js-is-viable-technology-choice-for-flex-developers.html">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>Below, I describe my experiences with Ext JS after the Sencha Fast Track training, my challenges with doing browser based work in a consulting context, and my thoughts on why it matters to Flex Developers.<br />
<span id="more-3015"></span></p>
<p><a href="#conclusions">I&#8217;m in a hurry</a>.</p>
<p><a href="#introduction">I don&#8217;t want a history lesson.</a></p>
<p>Get comfortable, this is long.</p>
<p><strong>Preface</strong></p>
<p>I had the pleasure of attending a 5 day fast track for <a href="http://sencha.com">Sencha&#8217;s</a> <a href="http://www.sencha.com/products/extjs/">Ext JS 4</a> in New York last week with my partners from <a href="http://webappsolution.com">Web App Solution</a>. Of the 13 people that attended, 7 were <a href="http://incubator.apache.org/flex/">Flex</a> Developers working on Enterprise Applications. Yakov and Victor from <a href="http://faratasystems.com/">Farata Systems</a> were there and <a href="http://universalmind.com">Universal Mind</a> had <a href="http://twitter.com/johnyanarella">John Yanarella</a> representing.</p>
<p>While the technical future of Flex is extremely bright and exciting, the business and marketing future of it is over. Adobe, with the community&#8217;s help, has ensured that it is in the best hands with the <a href="http://apache.org">Apache foundation</a>. With a multitude of capable, brilliant, and diverse contributors to the open source project, there are definitely a lot of great things on the horizon for the next <a href="http://incubator.apache.org/flex/">Flex SDK</a>.</p>
<p>Adobe has also ensured, intentionally and unintentionally, it has a limited future which will ensure Flex is no longer invested in any technical capacity from small, medium, and large businesses unless absolutely essential, or under the radar. The mobile revolution has happened, and while Flash had the opportunity to play a pivotal role, Macromedia, and later Adobe have failed to take the initiative and successfully execute on it.</p>
<p>While there is still a significant business &amp; technical advantage from a design, development, and workflow perspective in the <a href="http://adobe.com/products/air/">Adobe AIR</a> stack for developing &amp; deploying on <a href="http://android.com">Android</a> and <a href="http://apple.com/ios/">iOS</a>, Adobe has made it a clear that they perceive it is an opportunity they are not interested in pursuing on the developer front. This is a huge topic mostly discussed from a technical perspective in the community, and only a select few blog articles got it right from a business one&#8230; and even then, those missed it from a technical perspective.</p>
<p>Bottom line, Flex Developers are between a rock and a hard place in the industry right now.</p>
<p>The type of work they do for desktop web applications is different from what Flash Developers do, mainly in team size, project scope, and client base. It&#8217;s not as simple as &#8220;just use <a href="http://jquery.com">jQuery</a>, and move on&#8221;. While the tools &amp; runtime we use are technically sound, even clients who have a technical understanding of the marketplace &amp; toolset will not invest in a perceived abandoned platform. Server-side offerings do not offer the rich client experiences we&#8217;re used to creating. The plethora of frameworks in the web market, both open source and proprietary, do not offer the same tooling, performance, and expedient workflow we have on the Flash Platform.</p>
<p>&#8230; except <a href="http://www.sencha.com/products/extjs/">Ext JS</a>. Sort of.</p>
<p>As stated by John Yanarella at the training last week:</p>
<blockquote><p>&#8220;Out of all of the web based frameworks out there, Sencha&#8217;s Ext JS is the best safety net there is for Flex Developers.&#8221;</p></blockquote>
<p>It has the necessary component framework, a growing company with enough resources &amp; funding at a specific size behind it, with a competent web &amp; mobile technical story that has the potential for critical mass within an Enterprise context.</p>
<p>Thus, given my company&#8217;s need to offer my clients an HTML5 alternative to Flex, Ext JS seems to fit the bill. Considering time is at a premium nowadays, the fast track <a href="http://www.sencha.com/training/">training</a> Sencha offers seemed like a great opportunity. And I love New York so any excuse to go there is great.</p>
<p>Given the whirlwind that was the past 3 months, as well as reflecting upon what I learned from the training, I thought it prudent to write down my thoughts here. There are a lot of Flex Developers who are looking for direction, so I&#8217;m hoping this is one for them to follow.</p>
<p><strong>Background</strong></p>
<p>As a Flex Developer faced with a forced career change driven by forces beyond my control based on the infamous events of November 9th, 2011, I had 2 choices. Do what I always did back in my 20&#8242;s and dive headlong into the unknown, or let the pioneers get the arrows in their backs as it were. Now that I run a business and am a father of 2 children, I don&#8217;t have the free time I used to back being single and W2. Flash &amp; Flex, even on death march projects, allowed me to get up in the morning fueled by the passion of using my favorite technology, and attack problems full bore.</p>
<p>Surveying the landscape, things were pretty grim&#8230; even for someone positive like me.</p>
<p>While the iOS stack had a clear advantage with both a growing developer base, mature tooling &amp; framework, and customers who actually paid for content, none of my large clients actually had initiatives around iOS work. Enterprise applications, known for their copious amounts of input needs from the user, do not translate well to the small screen size and lack of keyboards on smart phones and tablets.</p>
<p>As such, while the uptick in service based software shops servicing the needs of clients who need iOS applications has increased, the scope of said projects is not as large and often is more consumer based. The latter is troubling as it&#8217;s hard enough utilizing ActionScript 1 in a deadline driven environment that Design Agencies employ; dodging technical debt for as long as possible in Objective C, even with superior tooling is not appealing when longer and more profitable projects exist with the opportunity to have competent peers beside me vs. being a lone wolf. Learning a lower-level toolset for shorter engagements that pay less makes it a non-starter.</p>
<p>Android, while being easier to deploy to as well as more easily iterating with your customer base, is notorious for it&#8217;s fragmentation, both programming and design. It&#8217;s hard enough for designers to lessen the overall experience via <a href="http://www.zeldman.com/2011/12/29/state-of-the-web-of-apps-devices-and-breakpoints/">responsive web design</a> to compensate for a variety of screen sizes. You now have developers who cannot turn as fast as designers can and thus have to spend more time on a platform that doesn&#8217;t generate nearly as much, if any, revenue from consumers compared to iOS. This doesn&#8217;t even broach the business topic of how do you lessen the maintenance cost on your customer when they have to hire both an iOS and Android developer, or some awesomely expensive hybrid who can do both, to handle both platforms. The other bizarre thing about Android is that it is taking the PC approach to competing on price with iOS and continually increasing market share, yet doesn&#8217;t seem to be generating the service revenue compared to iOS (ie people who own Androids don&#8217;t buy apps as much as those on iOS). Same problem as iOS: Invest in a lower-level technology with massive fragmentation for shorter projects that pay less money&#8230; again, non-starter.</p>
<p>The multi-development &amp; deployment problem was what the web was supposed to solve. While native development does give you significant user experience &amp; tooling advantages,   it seems wrong to invest my career for applications that my current client base do not target. Every single large client I&#8217;ve had treats mobile as either a fun skunkworks project, experiment with no perceived ROI, or as a necessity with the minimal amount of money devoted to it, sometimes taken from another project&#8217;s budget ad hominem.</p>
<p>Both don&#8217;t bode well for a future career from a consulting perspective in mobile.</p>
<p>While consumers bringing their smartphones, tablets, and technology of choice to work has had a huge impact on large companies, most Enterprise customers still target the desktop web as the main avenue of both B2C &amp; B2B based revenue. While many have made huge and wonderful strides in providing value for their mobile websites, it&#8217;s clear many either provide a lot less functionality than their desktop counterparts, or strain at even that.</p>
<p>With large media companies it&#8217;s a little different. Studies have shown that tablets are better at allowing consumers to consume content whereas desktops/laptops are better for producing content. While &#8220;duh&#8221;, having studies like this made and corroborating themselves verifies what we already know. They have a vested interest in increasing consumers ability to purchase and access that content in a controlled manner.</p>
<p>The problem here is that the budgets for those projects doesn&#8217;t increase with the needed targets.</p>
<p>For example, while working on <a href="http://hbogo.com">HBOGO.com</a>, the initial release of the iPhone app did not allow you to watch videos. The Flex app we did at the time was the only way to view videos. Overtime, it was prudent to support both iPhone and iPad versions. A lot of companies, however, don&#8217;t magically get 2 budgets, 1 for the web and 1 for the iPad just because the iPad is so cool. While the GUI&#8217;s needed for iPhone and iPad are simpler, you still want to create the same user experience for the customer, especially if they are using all 3 to access their content. The <a href="http://en.wikipedia.org/wiki/Project_triangle">Iron Triangle</a> verifies that something must give, and thus, the scope/functionality/user experience often does.</p>
<p>Investing in a mobile technology where consumers pay less, and larger businesses devote less capital to the same projects doesn&#8217;t bode well for investing the smaller portion. If I were back in 2002 still doing design agency work, I&#8217;d totally be an iOS developer right now. As a consultant who does more than build software, and who doesn&#8217;t see his clients changing their plans, I see no prudent reason to go the iOS/Android device route. &#8230;&#8230; beyond them being really fun (another story).</p>
<p><a href="http://www.appcelerator.com/">Appcelerator</a>, <a href="http://www.anscamobile.com/">Corona SDK</a>, <a href="http://www.sencha.com/products/touch/">Sencha Touch</a>, and <a href="http://phonegap.com/">PhoneGap</a>, technologies which allow you to deploy to multiple mobile platforms with mostly the same code base and skillset, can be lumped in the same bag as native with the above perspective.</p>
<p>Why invest in technologies that offer less money and my clientelle isn&#8217;t using?</p>
<p>On the flip side, the HTML5 moniker has taken on a life of it&#8217;s own. While not necessarily  representing the full JavaScript, HTML, CSS, and associated libraries &amp; frameworks stack, a lot of clients big and small have been sold the bill of goods that it solves the same multi-platform, multi-device problem that the Flex/Appcelerator/Corona/Touch/PhoneGap attempt to solve: single code base, single developer toolset, and multiple targets within their same organization.</p>
<p>I won&#8217;t get into the phenomenon that is HTML5. All you need to know of the context of this post is that a lot clients either suddenly think HTML, CSS, and JavaScript can provide the same experiences we can do in Flex for the same price using the same teams&#8230; or they know it&#8217;s false, but either their Board of Directors or Business Customers force them to use the tech anyway for political reasons that have nothing to do with engineering ones.</p>
<p><strong>The Challenges of the New Platform</strong></p>
<p>The issue, however, is that it&#8217;s not that straightforward. There are 5 main issues that the HTML/JS/CSS stack (which I&#8217;ll here after refer to as the HTML stack), have when coming from the Flex platform in a consulting context (there are more, but these are the ones that matter with regards to the context of this post). They are:</p>
<ol>
<li>DOM as a dynamic display technology</li>
<li>JavaScript lacking mature language constructs</li>
<li>There are larger problems for multiple Browser Vendors to solve</li>
<li>the industry&#8217;s libraries &amp; frameworks are young from an Enterprise context (yet not!?)</li>
<li>The Video Codec Issues</li>
<li>Tooling</li>
</ol>
<p><strong>The Document Object Model</strong></p>
<p>The HTML DOM wasn&#8217;t made to do the type of applications we do in Flash, more specifically Flex. Flash Player was developed specifically around cross platform visual fidelity with a web bent. More importantly, though, it was built around redraw. This perspective of &#8220;frames per second&#8221;, and continual improvements around the underlying <a href="http://blog.kaourantin.net/?p=82">timing of redraw</a>, building upon <a href="http://blog.kaourantin.net/?p=81">what a platform does well</a>, and then abandoning a &#8220;new&#8221; 5 year old display technology to support a <a href="http://blog.kaourantin.net/?p=138">GPU future</a>.</p>
<p>Browser vendors are doing some pretty amazing things with the DOM, from hardware accelerating the display, continuous redraw optimizations, all the while doing their best to follow ever evolving standards amongst our changing technological landscape. &#8230;based on a tech designed and created to show text. That&#8217;s awesome.</p>
<p>Sadly, the redraw performance isn&#8217;t awesome. While a lot of Flash and Flex developers never really got the <a href="http://jessewarden.com/2007/01/invalidation-strategies-for-flash-player.html">purpose</a> and <a href="http://jessewarden.com/2008/03/how-to-fix-the-flash-cs3-components.html">value</a> of invalidation in Flash Player, even with a technology created for displaying and animating composited graphics, as your application scales, it&#8217;s easy to create a system that redraws too much. Invalidation helps mitigate (usually solve) that problem for 90% of the use cases in applications. In a nutshell, it means you can set properties on your visual components as much as you want to in a single thread and ensure it only actually redraws the screen 1 time.</p>
<p>For browser DOM&#8217;s, this is exemplified even with the drastic CSS improvements. The philosophy is to never redraw the DOM if you have to, and if you do, do so on the smallest section possible. Browser toolkits such as Ext JS,  <a href="http://dojotoolkit.org/features/desktop">Dojo</a>, and some others do this very well. While they have the advantage of browser CSS to help mitigate some of the redraw performance drags, compensating for both past, current, and future browser incompatibility in an easy to use &amp; scalable API shows just how brilliant some of those browser developers really are. Based on what I&#8217;ve continued to read, this seems to be getting better although not as fast, nor as widely deployed, as Flash Player did which means the problem isn&#8217;t going away soon and thus the need for x-browser, x-platform invalidation continues to be important. Thus, Ext JS&#8217; commitment to efficiently redraw the DOM is appealing.</p>
<p>One thing John brought up at the <a href="http://www.sencha.com/training/">Ext JS Fast Track training</a> last week was the lack of positive sales around hybrid solutions: using Flash Player and the HTML stack together. If you need to play video or animate/show a lot of composited objects, combining the 2 technologies together.</p>
<p><a href="http://hulu.com">Hulu</a> and <a href="http://youtube.com">YouTube</a> proved it can work with video and movie subscriptions. <a href="http://Grooveshark.com">Grooveshark</a> proved it can work with music (and video, heh). <a href="http://google.com/finance/">Google Finance</a> and <a href="http://google.com/analytics">Analytics</a> proved it can be done with charting.  <a href="http://balsamiq.com">Balsamiq</a> proved it can be done with desktop designer tooling.</p>
<p>Bottom line, things are pretty bad but getting better slowly, and there are mitigation paths that can utilize Flash Player in the interim. Canvas is finally getting hardware acceleration across platforms also making it another another tool to help.</p>
<p>This doesn&#8217;t seem to be getting much play, but considering we&#8217;re all supposed to magically know a multitude of platforms, languages, and yet have multi-talented sub-contractors that meet that criteria and deliver the projects in the same time frame clearly means that option is also on the magical table.</p>
<p><strong>JavaScript in the Enterprise</strong></p>
<p>Surprisingly for me, JavaScript the language has dominated the discussion the past 3 months in where I&#8217;ve lurked in social media circles amongst the Flash &amp; Flex Developers. For those of us who grew up in the industry and our careers with Flash, it came quite as a shock for the industry to fall back in love with JavaScript.</p>
<p>While it made sense for server-side developers to reduce their code size as more logic goes to the client and their servers get faster and cheaper, we&#8217;re still a little confused as why the industry isn&#8217;t salivating for a statically typed <a href="http://wiki.ecmascript.org/doku.php?id=harmony:proposals">Harmony</a> (resurrected, non-elven remains of ECMA 4).</p>
<p>Most of us Flash turned Flex developers grew up using ActionScript 1. For those who don&#8217;t know, this is near exactly the same as JavaScript/ECMA 3. The difference is instead of doing an innerHTML on a div tag, you just call methods/properties on a Sprite. As our projects grew in scope and # of developers, the language started to show its scalability problems. You&#8217;d run into more and more null pointers from misspellings, even with better tooling to help provide code hinting. You&#8217;d also get errors, but no clue where they came from since there was no common way of handling errors in ActionScript 1.</p>
<p>Furthermore, if you didn&#8217;t provide source, the developer was screwed because there was no way to easily introspect API&#8217;s unless you read the documentation or source; things like <a href="http://aptana.com/">Aptana</a> didn&#8217;t exist back then. This also implied, however, that even though there were things that weren&#8217;t public, developers would still call them anyway if they didn&#8217;t understand your name spacing convention (such as using an underscore (_) prefix for private variables and method names). While <a href="http://lua.org">Lua</a> and other languages have <a href="http://www.lua.org/pil/15.2.html">tricks</a> using closures to emulate access modifiers, this never caught on in the early Flash world. The path for RIA&#8217;s at the time was larger projects with larger teams, and thus they adopted a more Java esque method of language development while still trying to match ECMA 4 as best they could.</p>
<p>Finally, loose typing/variants also made it harder (in theory&#8230; which has been proven wrong by Google&#8217;s V8) for Macromedia/Adobe compiler engineers to make the language run faster than JavaScript.</p>
<p>Thus, the natural evolution was for a strongly-typed language with proper packages and namespaces (or access modifiers like public/private) to help us address the larger applications we were developing. It did. It was, and is, awesome.</p>
<p>&#8230;for some. About the same time as I started getting more consulting, I also started noticing a larger awareness to the different types of businesses using Flash and Flex. In the Design Agency world, the majority of the work was 2 months to 2 days, and in between. The teams were often 1 developer; if there were more devs, they both weren&#8217;t on the project the whole 2 man months. They hardly ever payed their technical debt (unless you were a consultant with them). You started to see a strange love/hate relationship for a lot of these devs. In some cases ActionScript 3 helped these developers, who were on a deadline and often never paid their technical debt, manage said technical debt with AS3&#8242;s improved strong-typing and runtime exceptions with the ability to use loosely typed constructs when needed or in unknown territory.</p>
<p>On the flip side in the Flex world for larger companies that gave a flip about design, and more about feature count, the language constructs were barely enough. Constantly we&#8217;d get barraged from developers in more low-level languages like Java, C#, and C++ about why is AS3 is missing this or that (true Singletons, true Abstract classes, threads, blah blah blah), and how do you emulate such features.</p>
<p>It was very clear there was a split was growing. I could elaborate on all the niceties, but suffice to say, the Flash Devs didn&#8217;t need all the language features &amp; strict complexity rules whereas the Flex Devs couldn&#8217;t get enough. Again, a simplification on the nuances of  a thriving, diverse, and changing community, but accurate.</p>
<p>Most of the Flash devs have had little trouble beyond the first 2 hellish weeks of getting immersed back in the DOM, CSS, and JavaScript variant world&#8230; only with better tooling and libraries + choices than they had 7 years ago when they 1st abandoned it for more creative pastures.</p>
<p>The Flex devs, however, haven&#8217;t seemed to budge en-masse. We have people telling us we don&#8217;t need those things in a language, yet when we ask them to show us a large Enterprise Application that utilizes JavaScript, they either are using an intermediary language to compile to it (Java in Google GWT or Oracle ADF, C#/VB in .NET, or CoffeeScript), or just can&#8217;t deliver the goods. Same excuse us Flex developers gave the <a href="http://slashdot.com">Slashdotters</a> around &#8220;show me a cool app built with Flex&#8221;: &#8220;It&#8217;s behind the firewall&#8221;.</p>
<p>There&#8217;s also a lot of misunderstanding about simple things like OOP. Using Object.prototype for &#8220;emulated&#8221; classes is what I did for 4 years&#8230; I have no major qualms about going back. Ext JS in version 4 abandoned this practice as well. While I grew up with Object.prototype insanity and learned to love it, the debate vs. clsoure/function inheritance vs. Object.prototype rages still. If you care, Keith Peter&#8217;s has a <a href="http://www.bit-101.com/blog/?p=3420">good article on the nuances of it</a>, or you can read what I did to learn ActionScript, <a href="http://www.debreuil.com/docs/">Robin Debreuil&#8217;s book</a>.  There are others, but the point here is we Flex Devs expect classes not just for encapsulation, but create organized code with a common workflow to share code amongst many developers. JavaScript wasn&#8217;t made for classes, but using Object.prototype or the closure method in a declarative manner works just fine (like <a href="http://impactjs.com/">ImpactJS</a> or Ext JS does).</p>
<p>While I like Keith&#8217;s take and respect his opinion, not having classes and encapsulation won&#8217;t work in large teams, often setup to fail at the outset by politics, nor all being Keith Peter&#8217;s caliber (me included). The other option to &#8220;not working&#8221; of course (Goonies never say die), which I&#8217;ll cover later, is that it&#8217;ll just take longer and/or we&#8217;ll accomplish less. The rules of <a href="http://en.wikipedia.org/wiki/The_Mythical_Man-Month">Mythical Man Month</a>, <a href="http://en.wikipedia.org/wiki/Technical_debt">Technical Debt</a>, etc. still apply regardless of  language/platform. It&#8217;s worse in <a href="http://jessewarden.com/consulting-chronicles">Consulting</a> when coding software, extremely hard in it&#8217;s own right, is the least of your problems.</p>
<p><strong>Compiling to JavaScript</strong></p>
<p>In fact, some are so staunchly opposed to utilizing JavaScript as a serious language to build Enterprise Applications, that they&#8217;ve investigated alternatives to compile TO JavaScript using an intermediary language. This has long been the process for server-side platforms with a variety of templating engines out there that make it a hybrid process of injecting data into your HTML. The problem is, they either have a server-side bias, or aren&#8217;t ready for prime time in a large Enterprise Scale. Remember, you can&#8217;t just be good; you have to have money, a company of decent size behind the tech, funding, and have reached critical mass for your product.</p>
<p>While the reaction was very positive around the work Adobe was doing with <a href="http://blogs.adobe.com/bparadie/2011/11/19/what-is-falconjs/">FalconJS</a> for those in attendance at the <a href="http://blogs.adobe.com/flex/2011/12/an-update-on-flex.html">FlexSummit</a>, it was very clear to me it was a science experiment with no hope in providing the needed migration path for Enterprises. The amount of work, resources, and time needed to bring it to Oracle ADF, Google GWT, or .NET caliber is clearly something Adobe didn&#8217;t seem willing to devote. That, combined with their clear direction of no longer focusing on developers.</p>
<p>Google <a href="http://www.dartlang.org/">Dart</a> seemed like a light at the end of the tunnel. It, too, however, seems to be a science experiment of Google scale. It has all the hallmarks for a bright new project:</p>
<ul>
<li>Google is behind the engineering effort</li>
<li>has a strongly-typed language that, like CoffeeScript, not only sets out to improve upon JavaScript&#8217;s problems, but provide mature language constructs you need in larger applications within the language itself (unlike CoffeeScript&#8217;s/<a href="http://code.google.com/closure/compiler/">Google Closure&#8217;s</a>/<a href="http://typedjs.com/">TypedJS</a> annotations</li>
<li>has 2 <a href="http://www.dartlang.org/support/faq.html#hello-world-js-size">compilers</a>: 1 a Flex Developer would use (dartc) and 1 a Flash Developer would use (frog).</li>
<li>is based on Eclipse (good and bad, let&#8217;s just pretend the good parts here)</li>
<li>brought on <a href="http://infrequently.org/">Alex Russell</a> of <a href="http://dojotoolkit.org/">Dojo</a> fame to take a fresh look at the DOM event API</li>
<li><a href="http://futurescale.com/v3/">Cliff Hall</a> of <a href="http://puremvc.org/">PureMVC</a> fame (multi-language framework used a lot in Flex) made a <a href="https://plus.google.com/108661011132885730615/posts/Z2apdshvWnA">first version port for Dart</a>.</li>
</ul>
<p>&#8230;yet doesn&#8217;t seem a priority since while a web based technology, it still hasn&#8217;t reached critical mass, nor does it show any signs of doing so yet. I&#8217;m more concerned about the amount of resources I&#8217;m seeing being devoted; maybe there are more, and like all things Google, they just don&#8217;t advertise it. I really wish I could just parachute drop a Porter &amp; Bogusky contingent in Google someday&#8230;</p>
<p>So far, the only contender is <a href="http://coffeescript.org/">CoffeeScript</a>. Here is a <a href="http://bodil.tv/coffeescript-at-javazone">video</a> and <a href="http://bodil.github.com/coffeescript/#landing-slide">slide presentation</a> to check out on if you have time. However, Ext JS uses declarative <a href="http://json.org/">JSON</a> + JavaScript. I have not seen any signs to see if Sencha is interested in porting Ext JS to Dart. Just say it&#8230; &#8220;Ext Dart&#8221; (pronounced &#8220;X Dart&#8221;); sounds like a dope <a href="http://www.youtube.com/watch?v=itm7SdwYTjo&amp;feature=fvst">dubstep</a> ninja weapon, right? You&#8217;d certainly get better jokes from non-tech savvy people at parties when someone hears you&#8217;re a &#8220;Flash Developer&#8221;.</p>
<p>The other problem is that you need everyone in your organization coding the same language. In product companies, it is TOTALLY fine to have a technology du jour with Ruby running your builds, PHP running your render farm, and Java running your back-end, but for development purposes on 1 particular platform, you standardize on a language and usually have company ordained standards on it. This is for maintenance costs, and hiring standards, and a variety of other reasons that aren&#8217;t just around cost.</p>
<p>If anyone has CoffeeScript running atop Ext JS, let me know how you got your build process setup.</p>
<p><strong>Browser Issues</strong></p>
<p>Notice I&#8217;m specifically talking not just about incompatibilities between browsers, but missing features. For example, just 3<a href="http://blog.chromium.org/2012/02/future-of-javascript-take-peek-today.html"> days ago</a> Google added weak collection keys into V8 (their JavaScript engine for Chrome). Developing data models with string based keys can be extremely hard for complex model logic. Having a Dictionary (or Object) that can use something other than a String as a key is extremely useful&#8230; until you have to remember to kill the key when the object is destroyed. Enter weak keys and queue the &#8220;woo hoo!&#8221;.</p>
<p>One of the great things about Google&#8217;s approach with Chrome is not only is it the fastest updating piece of software that matters in history (faster than Flash Player), but they iterate quickly on features. While we&#8217;d wait 18 months for AS2 and then 24+ months for AS3, and in between get language updates&#8230; JavaScript is getting that piece by piece. It&#8217;s a wonderful thing, but also brings up a larger issue.</p>
<p>What do you today?</p>
<p>You have to do SOMETHING. Given each browser implements different features different ways, and JavaScript&#8217;s functional + prototype nature, you can easily (*ahem*) abstract away these problems into a useable API that hides the differences. Certain low level things like maps can be tricky, however, and come at the cost of performance, library maintenance costs, etc.</p>
<p>Fine, no big deal, you just move forward using an Object hash approach. We&#8217;ll just wait a couple of projects before maps + Dictionaries catch on in all browsers.</p>
<p>&#8230;but what about <a href="http://www.whatwg.org/specs/web-apps/current-work/multipage/workers.html">Web Worker</a> (also known as threads for web developers)? It&#8217;s only supported in IE9 while Firefox/Safari/Chrome are good to go. While you can emulate via green threading, this is a FAR cry from emulating the lack of getter/setters in older versions of IE, or even <a href="http://code.google.com/p/explorercanvas/">emulating Canvas for Internet Explorer 8 via a VML wrapper</a>. Those work. <a href="http://en.wikipedia.org/wiki/Green_threads">Green threading</a> is not the same thing as a separate process that ensures it doesn&#8217;t lock up your GUI thread. The lack of full browser support will prevent some features from actually working and there aren&#8217;t any fall backs that can be utilized.</p>
<p>For some charting/plotting applications, these are essential features: no web worker, no application. Now in Flash, you&#8217;d just plan around upcoming features, both those you voted to be actual features, or those you knew were coming down the pipe. One tactic of design agencies, and Macromedia/Adobe in general was to have them launch a high profile app/site/widget to showcase these features upon launch.</p>
<p>If you are to inspect all upcoming features in browsers, not just JavaScript, but CSS, hardware &amp; display related, etc. it really slows down when we expect certain experiences in our applications. While Macromedia/Adobe would drag their feature on certain things like right click and threads, the process was generally the same:</p>
<ol>
<li>identify a problem you had on projects</li>
<li>bring it to your peers &amp; Macromedia&#8217;s attention</li>
<li>rally support through email list/blog/twitter posts/talking to company reps at conferences</li>
<li>make writing &amp; validating the use case easy</li>
<li>get community votes when desperate</li>
<li>await new feature(s) in upcoming Flash Player, beta test if lucky</li>
</ol>
<p>While this process for Chrome seems EXTREMELY quicker, for the rest of the browser market as a whole, including smart phones and tablets, not so.</p>
<p>My college professor said, &#8220;There will always be work to be done.&#8221; Unless we use hybrid implementations, clients will just have to live with the slower pace of innovation if they want broad adoption. I guess I&#8217;ll live, I&#8217;m just curious where my excitement will come from if the toys remain the same, or only 1 browser implements a new feature I can&#8217;t easily abstract. That, and it seems a lot of innovative projects will either start to be browser specific feature branches, or just wait for broader adoption amongst modern browsers. It&#8217;s sad. And frustrating for both my clients and my team.</p>
<p><strong>Wild West: Libraries and Frameworks</strong></p>
<p>What&#8217;s fascinating to me about the JavaScript landscape is how much longer it has been around with a lot more people and yet the landscape with regards to frameworks and libraries is still in major flux on a few fronts.</p>
<p>In the Flash World, there were 2 frameworks that people would use, if ever: <a href="http://osflash.org/projects/arp">ARP</a> and&#8230; just kidding, 1. While the tweening libraries got a little out of control, and the component frameworks became pretty niche, overall there was a library for everything, sometimes with an alternative if you didn&#8217;t like one particular implementation. A lot were ported from other languages, like Java and C/C++.</p>
<p>Frameworks didn&#8217;t really start to rear their head until Flash RIA applications started to become mainstream, and Flex was born. The Java developers coming over didn&#8217;t see any common <a href="http://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller">MVC</a>/<a href="http://martinfowler.com/eaaDev/ModelViewPresenter.html">MVP</a>/<a href="http://en.wikipedia.org/wiki/Model_View_ViewModel">MVVM</a> frameworks that allowed them to manage copious amounts of code on the client side vs. middle tier. <a href="http://opensource.adobe.com/wiki/display/cairngorm/Cairngorm">Cairngorm</a>, <a href="http://puremvc.org/">PureMVC</a>, <a href="http://swizframework.org/">Swiz</a>, <a href="http://www.spicefactory.org/parsley/">Parsely</a>, and <a href="http://robotlegs.org">Robotlegs</a> were born. Cairngorm is still around, but Swiz/Parsely get most of the play in the Flex world with PureMVC and Robotlegs hitting both Flash and Flex.</p>
<p>With exclusion of Cairngorm, all 3 have a lot in common. While everyone somehow manages to make their own implementation, learning one helps in learning another. Additionally, most never made it past a version 2, and even then most of the changes weren&#8217;t a dramatic workflow change.</p>
<p>JavaScript is nuts on the framework front. While the libraries themselves are great in that once you get over the burden of reviewing 5 of the same thing, the frameworks on the other hand are all over the map. Some are just query helpers with binding thrown in. Some are actually a certain group of existing libraries with a defined way of working with them, and thus named a framework&#8230; even though no code is actually associated with the framework itself. Worse is the versions can sometimes be drastically different. If few in #, this wouldn&#8217;t be a problem.</p>
<p>Worse, there are 100 times more people in the JavaScript community with their own opinions on what MVC means. What MVP means. What MVVM means. What the differences are between the 3. Their own descriptions for what the differences are between Passive View, Supervising Controller, and Presentation Model&#8230; and sometimes pretending (innocently) that the only thing that exists is MVC, period.</p>
<p>The other thing that is clear is that there are a variety of applications (not progressively enhanced websites) that are done with JavaScript, and thus each framework targets that particular version. For example, PureMVC and Robotlegs have Mediators which make it easier for the View (what you actually see) to change a lot during the project, yet still keep its ability to get it&#8217;s data without race conditions, and have it produce the necessary  user gestures through Events. Swiz on the other hand, had a Presentation Model injected into the View, and you had a nice API the View could call/get it&#8217;s data from. A lot of Swiz guys I talked to NEVER used the states features in Flex 4&#8230; nor saw the point. GUI changes didn&#8217;t affect PM API, they weren&#8217;t complex enough that you had to use mock interfaces for the PM&#8217;s to test View&#8217;s in isolation&#8230; so for this group, it worked well. In retrospect, this was a nice, natural evolution that happened.</p>
<p>I&#8217;m seeing the same thing in JavaScript, but it&#8217;s massively larger, and a lot of times you&#8217;re cherry picking either a specific feature of a specific library to be used with other ones, and you&#8217;re settling on a version. The last one is worrisome from a consulting perspective. When dealing with clients, Technical Architect/Directors want to ensure whatever framework you settle upon has good online documentation, you can hire people who know it, and it has a future. Using the same metrics I use to do so for frameworks in the Flash/Flex world is a little harder; just because its someones side science project doesn&#8217;t mean it&#8217;s not immensely useful, nor easy to learn.</p>
<p>The other challenge from a consulting perspective is leaving clients with work that they can support&#8230; or my firm would even want to get involved in. For example, there are copious reasons Ext JS 4 moved away from Object.prototype modifications. If you adopt a Ext JS 3 project from a client, you now adopt those problems even if you didn&#8217;t write it. With Flex projects, you eventually learned what problems there were from porting a Flex 2 app to 3, or what parts of mx were supported in Flex 4, and could find blog posts covering these challenges. With JavaScript, I&#8217;m finding a hard time finding commonality between the stacks that different companies are using.</p>
<p>I. Do. Not. Want&#8230; to be a non-Enterprise TA right now. Holy fish. Like, it&#8217;s 2008: &#8220;Yes, we&#8217;re using YUI version 2, it&#8217;s rad, has a large company backing it, and we can hire for it.&#8221; It&#8217;s 2012, and you&#8217;re either a jQuery, Sencha, or Dojo kid&#8230; oy vey.</p>
<p>So far, with the exception of Ext JS&#8217;s MVC implementation, it seems to have all of that solved in version 4 as best it can with the ability to have your own libraries added in with your own modified build process over theirs as well if you see fit to do so.</p>
<p><strong>Video Codecs</strong></p>
<p>No one has solved the codec problem yet. This is where HTML5 video just doesn&#8217;t work as advertised. I won&#8217;t go too much into this topic as for Enterprises, you&#8217;re usually more concerned about VOD, DRM, multicast and live streaming which Flash owns for desktop and HLS owns on iOS. More info about the <a href="http://www.longtailvideo.com/html5/">WTF</a> here and the <a href="http://transitioning.to/2012/01/the-world-of-pain-that-is-html5-video/">OMG</a> here.</p>
<p>I only bring it up because it&#8217;s just accepted in our world that video and compositing of it + assets is expected in our content, yet now&#8230; it&#8217;s not. Good designers can make it work, but the point here is from an integration perspective the cost of integrating that content.</p>
<p><strong>Tooling</strong></p>
<p>Lastly is tooling. While Aptana makes an attempt, it seems that Microsoft&#8217;s <a href="http://www.microsoft.com/visualstudio/">Visual Studio</a> is the only IDE that seems to take web development seriously for those building large applications. Since me and a lot of people I know in Flex development use Mac&#8217;s, it seems our only alternative is JetBrain&#8217;s <a href="http://www.jetbrains.com/webstorm/">WebStorm</a>. Granted, they have other flavors of their IntelliJ IDE,  but without commonly expected functionality like code hinting, intelli-sense, and re-factoring, it&#8217;s hard for use to take web development seriously.</p>
<p>There is a huge productivity cost that people seem to forget when you move from Eclipse/IntelliJ with those features to Notepad. When you have multiple developers, that time spent adds up, as does the lack of accuracy on your team&#8217;s velocity in solving issues.</p>
<p>In 2004, a lot of Java Developers tried out Flash. They then left. Adobe then created Flex. Some came. When Flex 2 came out, the runtime worked, the language worked, the components worked, but more importantly, the Eclipse IDE at the time&#8230; worked. The refactoring was, and still is not the best compared to IntelliJ and Visual Studio, but it&#8217;s enough for them to take it seriously. That&#8217;s when they came en masse, and peeps like <a href="http://en.wikipedia.org/wiki/Bruce_Eckel">Bruce Eckel</a> were like, &#8220;Flex is good stuff&#8221;.</p>
<p>Going into an Enterprise and telling developers they are no longer allowed to work on Enterprise software with intelli-sense and code hinting isn&#8217;t going to work. Thankfully Ext JS is working with a few tools vendors, and some, like WebStorm, can be customized to improve the hints you get, including on your own code.</p>
<p>At the end of the day, we Flex Developers are concerned about the overall reduced project velocity &amp; resolution prediction that comes with losing static typing (&#8220;What and where is the problem and when is it going to be resolved?&#8221;). For smaller projects with smaller teams, I guarantee you the point is moot. In doing both, if you CAN do both, dynamic languages are so much faster and fun to develop quickly, and flexibly in. For 18 month, multi-developer teams on code that&#8217;s alive for 5 years, it doesn&#8217;t.</p>
<p><a name="introduction"></a><strong>Introduction</strong></p>
<p>As a business owner, we have to meet the needs of those clients that have adopted the HTML Stack, or feel they need to and cannot be convinced otherwise. In the following article I&#8217;ll cover what Ext JS is from a Flex Developer&#8217;s perspective, why you should care, and some conclusions on how using it + Flex changes our business for the better.</p>
<p>As I mentioned before, the events of November 9th, 2011 shook the Flash &amp; Flex world to the core, and I had 2 choices: figure out where to go, or let other key members of the community figure it out.</p>
<p>I chose the latter plan: play <a href="http://www.elderscrolls.com/skyrim/">Skyrim</a> and disappear for 3 months to let it all shake out. If things hadn&#8217;t been figured out by key members of the community, I&#8217;d just figure them out for myself. It&#8217;d also be around the same time as <a href="http://en.wikipedia.org/wiki/Groundhog_Day">Groundhog Day</a>: If the Flex community saw their shadow, and freaked out, I could come out and help them weather the longer winter.</p>
<p>It&#8217;s been 3 months and so far, it seems all the Flash Devs went <a href="http://jquery.com">jQuery</a>/<a href="http://documentcloud.github.com/backbone/">Backbone</a> (or <a href="http://angularjs.org/#/">Angular</a>) whilst the Flex Devs are debating between <a href="http://dojotoolkit.org/">Dojo</a> and <a href="http://www.sencha.com/products/extjs/">Ext JS</a> (pronounced &#8220;X Jay S&#8221; if you&#8217;re French Canadian) (yes, I tried <a href="http://developer.yahoo.com/yui/">YUI</a> and left just as quickly). After talking with members of the community and doing some of my own research, it seems Ext JS is the right choice for the type of work I do. Like using Flash vs. Flex, it&#8217;s clear it may not be the right choice for you. If you&#8217;re a Flex Dev doing large, multi-developer projects, I&#8217;ll bet it IS the right choice. Read on.</p>
<p><strong>What is Ext JS?</strong></p>
<p>Ext JS is a component framework for building web applications atop JavaScript, HTML, and CSS. It&#8217;s made by a company called Sencha who also makes a mobile version called Sencha <a href="http://www.sencha.com/products/touch/">Touch</a>.</p>
<p>It&#8217;s attractive to Flex Developers because:</p>
<ol>
<li>It has components. Lots of components.</li>
<li>It has styling and theming features.</li>
<li>It has a Model architecture built around data store &amp; server CRUD operations.</li>
<li>It has charting components that do not utilize Flash Player (for good and ill)</li>
<li>It has awesome item renderers for grids.</li>
<li>It has classes for JavaScript with inheritance.</li>
<li>Layouts with Containers</li>
<li>Standard Focus Manager</li>
<li>Core Library with DOM helpers as well as JavaScript language extensions</li>
<li>A big company, with investment, and tons of docs who&#8217;ve adopted a prescriptive MVC framework.</li>
</ol>
<p>There&#8217;s a lot more, but that is what we Flex devs actually care about.</p>
<p><strong>How&#8217;s it work?</strong></p>
<p>Ext JS is a framework; a collection of classes, 3rd party technologies, and a prescribed methodology for building web applications. HTML is used to show the components. CSS is used to style and modify interactivity. JavaScript and declarative JSON is used tomake things appear and work.</p>
<p>JSON, traditionally used by Flash and Flex Developers for data transfer, is actually the main way you code Ext JS, similar to how MXML makes up most of your GUI in Flex. Since JSON itself can be written in a declarative way, this is usually the core of how you define a lot of your application; both GUI and data. This JSON + JavaScript is interpreted to create classes, components, and listen to event handlers. Internally, the Ext library will redraw the GUI as necessary, whether that&#8217;s modifying CSS styles on the DOM objects that visually represent them, or swapping out innerHTML wholesale.</p>
<p>You include a javascript library on your HTML page, code some boostrap JavaScript/JSON on the page, and voila, you have an Ext JS app. It can be as small as using 1 or 2 classes from the Ext JS library, to a full blown application that uses their components, their model classes, their MVC, their default module loader, their implied CSS abstraction layer, and their build system&#8230; up to you how much you want to use.</p>
<p><strong>Prescription &amp; 3rd Party Integration</strong></p>
<p>Sencha has to walk a fine line with Ext. From an Enterprise stand point, they have to lay the ground work for a prescriptive way to utilize their technology. You need to make a framework easy to work with, have good documentation, and not be too flexible that developers can all go their own way. This allows larger organizations to hire/cross-train easier, have those developers actually be successful with minimal investment, and basically ensure any skillset &#8220;knows how to build an app&#8221;.</p>
<p>It&#8217;s a sales pitch, yes, but it does need to try to work like that. In reality it never does, hence consultants like me existing, but that&#8217;s not the point. You don&#8217;t want many different ways to skin a cat from an architecture perspective. It&#8217;s fine if you cuddle your brackets, use TextMate to code, and prefer Mercury over Git&#8230; it&#8217;s not fine if you prefer MVVM over MVC, want to be intimate with the DOM, and the other developers in another part of the company on a companion product don&#8217;t. Unlike Design Agencies, Enterprise companies do have to pay their <a href="http://martinfowler.com/bliki/TechnicalDebt.html">Technical Debt</a>. In fact, I&#8217;d argue they pay more than they should, compensating in a bizarre karma like way for Design Agencies who get away it. You want to mitigate this problem by making something easy to use, easy to hack, but prescriptive enough that if you don&#8217;t know any better, you won&#8217;t cause undue costs down the line in the way your team built something.</p>
<p>JavaScript, currently, is all about libraries, more so than Flex and Flash was for a variety of reasons. Namely abstracting browser differences, abstraction over new features with fallbacks, and the sheer number of developers from a variety of backgrounds. Each company is going to use different libraries merely based on the number of library choices out there. The same goes for internal projects. A lot of companies have their own internal libraries utilized on products for their business, whether B2C or B2B. You need to be able to integrate with these in your native language.</p>
<p>Sencha needs to support prescribed direction in how you build web applications with the ability to support 3rd party libraries.</p>
<p>There are a few things they&#8217;ve done to facilitate this. Here are a few that matter.</p>
<p>First, they&#8217;ve abandoned Object.prototype as of Ext JS 4. If you&#8217;re a Flash Developer, you&#8217;ll remember having your language suddenly act different because some developer or 3rd party library overwrote a core property/method in Flash, and suddenly your entire application worked differently&#8230; or it only did it sometimes because of later loaded class. Unless you knew what you were doing, these were nearly impossible to debug since the documentation stated a method did one thing, but clearly during testing did another. Even if you did know what you were doing, there aren&#8217;t many language, nor tooling facilities to help you debug this inheritance mixin whackness.</p>
<p>Considering JavaScript library inclusion amounts are significantly higher than say Flash or Flex, the risk of collisions are higher. On multi-person teams across an organization, with already strained communication this can be horrible to try to resolve.</p>
<p>Also, from a module perspective (those of you using PureMVC multi-core or many Robotlegs Contexts will get this), you need to sometimes run may applications in parallel on the same page. Not having to worry about stomping on someone&#8217;s method/properties is a nice feeling to have.</p>
<p>Second, they&#8217;ve commited to <span style="text-decoration: line-through;"><a href="http://twitter.github.com/bootstrap/">bootstrap.js</a></span> their own bootstrap.js from a library/module perspective which supports both debug and production mode. With the build process, this allows you to develop with new classes on the fly, and in production mode actually have 1 file for you&#8217;re entire application. This is for speed &amp; ease of development purposes.</p>
<p>We take this for granted in Flash/Flex where all our classes are included, and zlib compressed in a minified bytecode format into a single SWF file.</p>
<p>Remember, Day 1 of Flash Development had 1 SWF. As a binary format, everything you needed was right there for you, ready when you started. The HTML stack was different. Everything is a bunch of files all loaded at different times from different places. As a coder, you know this is a nightmare to figure out. From a networking perspective, initiating a lot of HTTP requests to the server and downloading them in parallel is also slower. So JavaScript has a habit of allowing you through build processes to put all of your classes into 1 massive file to help alleviate the race condition pain as well as improve performance, compression, etc. However, during development or when building modules/lazy loading, you still need the option to load on the fly.</p>
<p>Third, their MVC is prescriptive. I won&#8217;t get into too much detail because as a Swiz/Robotlegs aficionado and PassiveView h8tr, I already want to use my own or Angular&#8230; anything but theirs. That doesn&#8217;t matter, though, the point here is that they&#8217;ve provided the built in mechnisms, it works great with the framework, and they have documentation on it as such. This ensures organizations take them more seriously, have a chance to at least be forced into some known structure, and you as a consultant have a chance of understanding how they did things if you come onto an existing project (assuming they didn&#8217;t just use Ext JS for it&#8217;s query syntax and get all intimate with the DOM&#8230; which you can do if you wish).</p>
<p><strong>That&#8217;s Great, Show Code</strong></p>
<p>Here is some Hello World code:</p>

<div class="wp_syntax"><div class="code"><pre class="html" style="font-family:monospace;">&lt;html&gt;
	&lt;head&gt;
		&lt;meta http-equiv=&quot;Content-Type&quot; content=&quot;text/html; charset=UTF-8&quot; /&gt;
		&lt;title&gt;Ext JS Hello World&lt;/title&gt;
		&lt;link rel=&quot;stylesheet&quot; type=&quot;text/css&quot; href=&quot;/extjs4/resources/css/ext-all.css&quot; /&gt;
		&lt;script type=&quot;text/javascript&quot; src=&quot;/extjs4/bootstrap.js&quot;&gt;&lt;/script&gt;
		&lt;script type='text/javascript'&gt;
			Ext.onReady(function()
			{
				Ext.Msg.alert('Welcome to Ext JS 4', 'Hello World!');
			});
		&lt;/script&gt;	
	&lt;/head&gt;
	&lt;body&gt;
	&lt;/body&gt;
&lt;/html&gt;</pre></div></div>

<p>As you can see right off the bat, closures are the word of the day. Ext JS is full of either closures (anonymous functions or variables that equal functions) and/or JSON. You&#8217;ll intermingle both a lot.</p>
<p><strong>Components</strong></p>
<p>Components are the main reason most Flex Developers dig Ext. Not only are there are a lot of components, but some of the ones they have are better than their Flex equivalents. And this, folks, is one of the reasons why software developers often tell you to try another language or platform, at least 1 per year. You&#8217;ll see what the competition has, and YOU&#8217;LL GET PISSED OFF!</p>
<p>Why didn&#8217;t Adobe build this level of components for Flex? Why does Django, Rails, Coccoa, and countless other frameworks have a Model with optional Facade on top to support offline storage with online CRUD syncing out of the box&#8230; and Flex does not? How come our DataGrid didn&#8217;t come with built-in paging?</p>
<p>Enough ranting, <a href="http://www.sencha.com/products/extjs/examples/">check them out yourself</a> (scroll down, check out list on bottom left) while I cover a few here.</p>
<p><strong>T3h Über Grid</strong></p>
<p>You&#8217;ll notice right off the bat their DataGrid is pretty bad ass. Three things I want to point out about it.</p>
<p><a href="http://jessewarden.com/wp-content/uploads/2012/02/Screen-shot-2012-02-13-at-11.49.36-AM.png"><img class="size-full wp-image-3023 alignnone" title="Screen shot 2012-02-13 at 11.49.36 AM" src="http://jessewarden.com/wp-content/uploads/2012/02/Screen-shot-2012-02-13-at-11.49.36-AM.png" alt="" width="259" height="43" /></a></p>
<p>Notice they have paging built-in. This is, in part, to their Model/Proxy/Store setup. In Flex, you had to code this yourself (don&#8217;t get me started on Blaze DS/LiveCycle).</p>
<p>&nbsp;</p>
<p><a href="http://jessewarden.com/wp-content/uploads/2012/02/Screen-shot-2012-02-13-at-11.49.58-AM1.png"><img class="alignnone size-full wp-image-3025" title="Screen shot 2012-02-13 at 11.49.58 AM" src="http://jessewarden.com/wp-content/uploads/2012/02/Screen-shot-2012-02-13-at-11.49.58-AM1.png" alt="" width="308" height="252" /></a></p>
<p>Notice their filtering actually has a GUI with a drop down menu to customize (and which YOU can customize) on how to filter the data. No server trip needed. Hot.</p>
<p><a href="http://jessewarden.com/wp-content/uploads/2012/02/Screen-shot-2012-02-13-at-11.50.20-AM.png"><img class="alignnone size-full wp-image-3026" title="Screen shot 2012-02-13 at 11.50.20 AM" src="http://jessewarden.com/wp-content/uploads/2012/02/Screen-shot-2012-02-13-at-11.50.20-AM.png" alt="" width="611" height="410" /></a></p>
<p>And finally&#8230; &#8220;row editing&#8221;. Yes, an entire row can be modified. You can also allow a row to be edited, but only allow certain columns in that row to be edited, as well as customize this renderer. Awesome, right?</p>
<p><strong>Charts</strong></p>
<p><a href="http://dev.sencha.com/deploy/ext-4.0.7-gpl/examples/charts/Area.html"><img class="size-medium wp-image-3027 alignleft" title="Screen shot 2012-02-13 at 12.07.09 PM" src="http://jessewarden.com/wp-content/uploads/2012/02/Screen-shot-2012-02-13-at-12.07.09-PM-300x226.png" alt="" width="300" height="226" /></a></p>
<p>Charts, like Grids, play a central role in a lot of financial &amp; insurance software. You see the data in lists and you visualize it in charts. Ext JS 3 used Flash, but now they use SVG (and I think VML in some cases) and no canvas. This ensures it&#8217;ll work without a plugin. The downside is you can&#8217;t print yet. They&#8217;re working on it, and there are a lot of server-side plugins where you can easily wire up the chart data to a button to have the server assemble a PNG or PDF for you to print so solutions do exist.</p>
<p><a href="http://dev.sencha.com/deploy/ext-4.0.7-gpl/examples/charts/Bar.html"><img class="alignright size-medium wp-image-3028" title="Screen shot 2012-02-13 at 12.07.19 PM" src="http://jessewarden.com/wp-content/uploads/2012/02/Screen-shot-2012-02-13-at-12.07.19-PM-300x225.png" alt="" width="300" height="225" /></a>You&#8217;ll notice, too, that they are interactive. You can customize a lot of their display + tooltips I believe to degree using templates (I&#8217;ll go over that later). They also have the standard animation built in as well. From a sales perspective, these charts  + the grids demo very well.</p>
<p>While we at <a href="http://webappsolution.com/">WASI</a> have our own <a href="http://webappsolution.com/what-products.html">Dashboard</a>, it&#8217;s nice to know you can accomplish the same style of application and product using Ext&#8217;s components to create Dashboards.</p>
<p><a href="http://dev.sencha.com/deploy/ext-4.0.7-gpl/examples/charts/FormDashboard.html"><img class="size-medium wp-image-3029 alignnone" title="Screen shot 2012-02-13 at 12.07.32 PM" src="http://jessewarden.com/wp-content/uploads/2012/02/Screen-shot-2012-02-13-at-12.07.32-PM-300x248.png" alt="" width="300" height="248" /></a></p>
<p><strong>Everything Else</strong></p>
<p>Everything else is what you&#8217;d expect your team would need from <a href="http://www.sencha.com/products/extjs/examples/#sample-4">Tabs</a> to <a href="http://www.sencha.com/products/extjs/examples/#sample-7">layouts</a> to <a href="http://www.sencha.com/products/extjs/examples/#sample-13">forms</a>. The layouts are a little tricky if you&#8217;re not a CSS/DOM savant, but again, they abstract a lot of that from you (including that weird IE vs. the rest of the world padding measurement insanity).</p>
<p>There are a lot of little innuendo features too that make a big overall difference like all windows having the capability of being resized with a resizer, from all sides.</p>
<p>The components all have the standard DOM interaction events usually abstracted away so you just add an event handler for it, and you can create your own as well.</p>
<p>Yes, they have drag and drop.</p>
<p>Yes, they have a variety of ways to handle state, both in components and within your application itself.</p>
<p>Their drawing package uses SVG I think&#8230; not really sure why they aren&#8217;t using Canvas, but I&#8217;m sure they have their reasons.</p>
<p><strong>Localization &amp; Accessibility</strong></p>
<p>They have localization and accessibility built in. I had some concerns during the fast track course because it seems the localization requires the application to be totally reloaded just to have text changes take effect. Meaning, there aren&#8217;t default framework bindings to a resource manager like you do in Java or Flex.</p>
<p>Either this was a bug or we couldn&#8217;t figure it out, but bottom line the components built into Ext JS do work with it, and you can see their text match the language; we just couldn&#8217;t get this to work at runtime, only compile time which is fine.</p>
<p><strong>Event Model</strong></p>
<p>Just a quick note on the event model. In Flash Player, we have the standard ECMA event model in terms of capture, target, and bubble phase. Since IE is backwards from the rest of the world and is in the minority camp, Ext JS flips it around and gives you their own <a href="http://docs.sencha.com/ext-js/4-0/#!/api/Ext.direct.Event">Event</a> class as well.</p>
<p>They key difference, however, is that interaction burdens are put on developer, much like <a href="http://anscamobile.com">Corona SDK</a> does in <a href="http://www.lua.org/">Lua</a>. If you want to handle an event, you need to return true to ensure it doesn&#8217;t bubble up and get run. I&#8217;ve seen other frameworks which just code gen the event.stopImmediatePropagation() and event.preventDefault(), but not here&#8230; and sometimes you need to return true from event handlers vs. calling the event methods. I haven&#8217;t figured out yet where the consistency is.</p>
<p>Anyway, a small thing, but good that they abstract the browser differences for you and provide a common event class + mechanism for you. The addEventListener and/or callback way of doing things will be extremely familiar. I believe they have an event bus, but it&#8217;s not like Robotleg&#8217;s Actor or PureMVC&#8217;s Notification system.</p>
<p><strong>Styling &amp; Theming</strong></p>
<p>If you know CSS, you know how to style and theme a Ext JS application. Yes, that&#8217;s it. I unfortunately didn&#8217;t get to see, nor play with, a lot of the skinning in the Fast Track, just styling. I&#8217;m not sure how much of the image issues in various browser they abstract away since you&#8217;re using your own CSS styles.</p>
<p>Ext provides some template theme CSS files for you that you can modify, both built in classes as well as Ext JS ones. Combined with <a href="http://sass-lang.com/">SASS</a>/Compass, this really makes things a lot easier to handle. If you&#8217;re not familiar with SASS, there are just 4 things you need to know:</p>
<ol>
<li>You write 1 CSS style, and it&#8217;ll generate the browser/vendor specific ones if any (1 line of SASS could be 3 lines of CSS)</li>
<li>You can utilize variables in your SASS code which helps dynamically create the appropriate CSS (like determining width/height on the fly, etc).</li>
<li>They actually treat it like css CLASSES&#8230; so all the inheritance feels like inheritance vs. some &#8220;I&#8217;m not really code, but I&#8217;ll pretend I know what OOP is&#8221;</li>
<li>SASS files get generated through Ruby&#8217;s Compass into CSS files for your project. You don&#8217;t write CSS; you write SASS and Ruby&#8217;ll regen the CSS for you.</li>
</ol>
<p><strong>Models, Proxies, and Stores </strong></p>
<p>Most Flash and Flex projects I&#8217;ve worked on have some form of Value Objects (classes that hold data that represent a server-side entity with additional data the client needs), Models or Proxy classes that allow the client retain data and state, and service classes that form the basis of the CRUD operations with the server.</p>
<p>In branching out into other languages/frameworks/platforms, it&#8217;s clear most have a large sub-system and abstraction layer upon this setup. Django has Model, Rails has ActiveRecord (or did&#8230; been awhile), Coccoa has CoreData (amongst other things), and Java has all sorts of things. Even with the large influx of Java, Flex never really got that kind of abstraction unless you went with the full Blaze DS / LiveCycle stack. It was abstracted away enough that you could build both non-Blaze/non-LC apps and not know the difference, but the point is that it was clear Adobe didn&#8217;t think that was a core part of most apps, or rather that particular part could be monetized in Enterprise only offerings.</p>
<p>Whatever the reasons, it&#8217;s a core need in a lot of applications nowadays. I need to persist data in RAM, on the client cache (whether SQL or cookies), and with the server. Using a Facade or Proxy to make this part not only easier, but allow client side validation, as well as being built into all components, is a huge win.</p>
<p>All you need to know is it&#8217;s like an ArrayCollection that can save both locally to disk as well as sync with the back end as well as work as a dataProvider to all your components. And yes, when the dataProvider updates, Ext JS will update your GUI controls. Yup.</p>
<p>Sencha has specific meanings in the Ext world between Model, Proxy, and Store so don&#8217;t necessarely think design pattern as each is completely different than the other.</p>
<p><strong>JavaScript and Core Classes</strong></p>
<p>While Ext JS primary value to Flex Developers is their component framework and browser insanity abstraction, they also have a plethora of helper/utility classes for JavaScript, CSS, and the DOM as well. You can actually just use Ext just with the DOM using their <a href="http://docs.sencha.com/ext-js/4-0/#!/api/Ext.DomHelper">DomHelper</a>, <a href="http://docs.sencha.com/ext-js/4-0/#!/api/Ext.DomQuery">DomQuery</a>, and your own JS stack if you wish as their helper classes alone are nice to have. Some of it is open source, not sure.</p>
<p>You&#8217;ll notice they actually have a layer over top of low-level functions of JavaScript like <a href="http://docs.sencha.com/ext-js/4-0/#!/api/Ext-method-apply">apply</a>, they have their own version of <a href="http://docs.sencha.com/ext-js/4-0/#!/api/Ext.Function-method-createInterceptor">Delegate</a> (yeah, <a href="http://help.adobe.com/en_US/AS2LCR/Flash_10.0/help.html?content=00001842.html">remember</a> that <a href="http://jessewarden.com/2007/10/converting-as3-to-as2-and-surviving-as2-in-general.html">bullshit</a>? LIVE IT LOVE IT SUCKAZ AND THANK <a href="http://jessewarden.com/2010/04/steve-jobs-on-flash-correcting-the-lies.html">STEVE JOBS</a> FOR IT), as well as a rudimentary <a href="http://docs.sencha.com/ext-js/4-0/#!/api/Ext.Function-method-bind">binding syntax</a>.</p>
<p>They support inheritance and package names for your components. Although I&#8217;ve never done Ext JS 3, it&#8217;s clear they are constantly improving because the syntax in 3 was nasty compared to 4.</p>
<p><strong>Templates</strong></p>
<p>I&#8217;m still learning about the world that is HTML Templates but suffice to say there are 2 main uses in Ext JS.</p>
<p>The first is custom components. Creating custom components in Ext JS is pretty straightforward; you just extend <a href="http://docs.sencha.com/ext-js/4-0/#!/api/Ext.Component">Component</a> or <a href="http://docs.sencha.com/ext-js/4-0/#!/api/Ext.layout.container.Container">Container</a>, similar to Flex. However, they&#8217;re creating the DOM for you. What if you want to create your own HTML elements based on some strange PSD/AI design comp the company Crayon Pusher sent you? You can create your own HTML and have the data actually bound into it through a similar binding syntax we&#8217;re used to.</p>
<p>The second is item renderers. Any type of list, whether a small Container, or an actual component within a DataGrid itemRenderer can use a template. This allows quick creation of an itemRenderer without having to write a lot of code if you want to. Pretty sick.</p>
<p><strong>MVC, MVP, MVVM, Your Mom</strong></p>
<p>I&#8217;m not going to go into their MVC too much. Suffice to say, they like the <a href="http://martinfowler.com/eaaDev/PassiveScreen.html">Passive View</a> and have no qualms with a Controller managing multiple Views (at least, that&#8217;s what the Fast Track implied, but they don&#8217;t have time in those types of courses to show you all avenues). Worse, their naming scheme assumes you have a flat file structure, so you don&#8217;t name something &#8220;MyModel&#8221;, just &#8220;My&#8221; because they&#8217;ll append a name to it anyway causing it to be MyModelModel. That, and I fail to see how a flat directory structure of model, view, controller will scale to an application of any reasonable size, even with Ext ability to use string namespace aliases to refer to your classes.</p>
<p>Keep in mind the instructor was only given 1 day to show 1 way to do MVC, and we didn&#8217;t get too much time to dive hard core into the internals. It was clear, though, none of us liked it, and already Flex 1 era framework ideas were churning to bring our ideas (and biases) to Ext JS.</p>
<p><strong>What Sucks</strong></p>
<ol>
<li>Built on JavaScript, not CoffeeScript or Dart</li>
<li>They have horrible naming conventions for optimization purposes that no longer matter in todays world.</li>
<li>Tooling</li>
</ol>
<p>The top of this post covers my major concerns about JavaScript for applications of this size. I&#8217;m not worried about performance, just team velocity compared to ActionScript. In my experiences with Lua and ActionScript 1, your velocity in the beginning tends to be faster, but you hit a plateau and the lack of strong-typing annihilates your teams velocity and ability to project accurately. Unit tests help, but are more of triage vs. a tool.</p>
<p>The naming conventions are bourne of an era no one should care about but they still do. We&#8217;re in a gray transition as browser makers bring the HTML Stack up to speed to build applications, so you can&#8217;t just full stop ignore all the lessons learned.</p>
<p>However, I&#8217;d argue, as would countless others, that code readability trumps performance concerns. This goes way beyond &#8220;premature optimization is the root of all evil&#8221;. On extremely large code bases, verbosity is a virtue. You want readable code that it is easy to understand, both for your team and for yourself.</p>
<p>Because of String lookup costs and the ability for JavaScript minifiers to only compress none-reserved words like &#8220;this&#8221;, countless techniques are used to obfuscate the code to compensate. That may have mattered back then, but it doesn&#8217;t matter now. Worse, though, is that the counter justification is that for larger code bases, you do in fact need to make every optimization you can which in turn I counter double fold:</p>
<ol>
<li>Readable code trumps performant code.</li>
<li>If this is such a concern, why are we using this over Flex again?</li>
</ol>
<p>More importantly, however, is for API development. API&#8217;s are given to people who you sometimes have no contact with, nor have any clue about their adeptness. Thus, you need to make it as easy and obvious as possible. For an Enterprise framework such as Ext JS, you&#8217;d think this would be top priority. It&#8217;s clear Ext JS has some highly experience web developers involved in developing the API. I respect their knowledge, but it&#8217;s time to change.</p>
<p>Examples include Ext.getCmp vs. Ext.getComponent, Ext.getEl vs. Ext.getElement, and baseCls vs. baseClass. It&#8217;s prevalent throughout the framework, and mixed in with good verbosity&#8230; which makes it worse.</p>
<p>Ext JS 4.5 clearly needs a name overhaul if they expect senior programmers to take it seriously. Considering it&#8217;s JavaScript with Ext JS&#8217;s alias support, you&#8217;d think this would be easier to do.</p>
<p>While <a href="http://www.sencha.com/products/designer/">Ext Designer</a> completely blows away <a href="http://www.adobe.com/products/flashcatalyst.html">Adobe Catalyst</a>, it still has some issues with regards to the code generated and code round trip/merging. While looking nice, the results are not always being correct. We had easily duplicatable issues where the code generated did not match what was in the IDE GUI. Still, an extremely useful tool for generating a lot of the needed visual component code.</p>
<p>Finally, the lack of out the box code IDE is a near deal killer, at least for strict TA&#8217;s we deal with at large organizations. I know <a href="https://twitter.com/__ted__">Ted</a> said they&#8217;re working on it. Without things like intellisense and code hinting, you&#8217;ll make it hard for people to take things seriously, as well as making it harder to learn for more traditional programmers who suddenly have none of their mature toolset available&#8230; like&#8230; Java Developers&#8230; who came to Flash&#8230; and left&#8230; and&#8230; then they created Flex Builder&#8230;</p>
<p><strong>Critical Mass</strong></p>
<p>It seems Sencha has all the hallmarks for success and reaching critical mass with Ext JS. This is the ONLY reason I and others have given them any attention. As previously mentioned, you need a mid-size company, with money, and a good product to have it adopted as a targetable platform for large organizations. Sencha seems to have all 3. That, and again their components are pretty cool.</p>
<p>As a consultant, their components, charts, Ext Designer, and website all demo nice as well making it easier to sell as an alternative to Flex.</p>
<p><strong>Mobile Story</strong></p>
<p>I won&#8217;t get into much here, but suffice it to say I&#8217;ve yet to see the mobile revolution impact our clients as much as it has impacted the Design Agency sphere. While both focused on consumers, for a lot of brands, smart phones and tablets are seen as a growth market, or the ONLY market, to reach certain demographics. All the statistics point to both the behavioral change of society using their devices to interact with the digital world vs. computers, yet those same statistics also who the desktop still being the leader in PRODUCING that content that the world consumes. Yet given that, the money doesn&#8217;t seem to be flowing in lock step.</p>
<p>As such, most initiatives have been &#8220;it&#8217;d be cool to blow some money on&#8221;, &#8220;we have to provide something for iOS, even if it&#8217;s crap&#8221;, and the most common &#8220;wait&#8230; this won&#8217;t make any money&#8221;. While I know there are a lot of device work going on out there, it&#8217;s just not in my consulting sphere, or if it is, it&#8217;s at a extremely low profitability area and thus not worth investing in.</p>
<p>For now, the same large interfaces that we make on desktops do not transfer at all to smart phones nor tablets. Just like how people started to taking their iPhone&#8217;s to work, and companies stopped installing company phones, and later with Macs so companies started offering Mac&#8217;s as well as PC&#8217;s&#8230; so too will this have to happen with tablets before large companies even have it on their radar as a focused set of initiatives.</p>
<p>Obviously this is dependent on industry type, but we&#8217;re just not seeing it in the financial/insurance area, only slightly in the media company area (which I might add are the only ones who seem to care about Android).</p>
<p>&#8230;but let&#8217;s pretend it DOES matter. Let&#8217;s say a Director wants to know your mobile portability story? What do you tell them?</p>
<p>With Flex it was pretty straightforward: 60% to 80% of your Service and Application Layer code could be ported, with no change, to have the same Flex desktop application work on iPhone, iPad, Playbook, and Android devices. The missing piece here, is the device&#8217;s web browser.</p>
<p>While I&#8217;m a huge/firm believe in a long term native future for devices, there are still many use cases when a consumer is in a hurry and hits a company&#8217;s website expecting it to work. Considering some Operators only allow some applications to be downloaded over Wifi vs. 3G, this makes the website more important since even 3G can act as Edge. If you&#8217;re a business traveller, regardless if you&#8217;re on AT&amp;T or Verizon, you know exactly what I&#8217;m talking about.</p>
<p>2 key examples include <a href="http://marriott.com">Marriott.com</a> and <a href="http://www.papajohns.com">PapaJohns.com</a>. I encourage you to play with both on your iPhone/Android&#8217;s web browser. You&#8217;ll notice they try to duplicate the native  look &amp; feel paradigm. &#8220;It works like an app!&#8221;. Sometimes it works, sometimes it doesn&#8217;t. The responsiveness is the first thing you&#8217;ll notice that falls on it&#8217;s face. Apps just perform better, and consumers can tell. At least for now.</p>
<p>That&#8217;s not the point, though; notice how the functionality they need is forced to be simple because of the screen real estate being so small. There are a lot of use cases where even just a company mobile app is needed for its Desktop equivalent. Other times, you really do want to get as much information as possible from the user (a la Papa Johns). To me, Papa Johns is the perfect example of an application that an Enterprise would want on a phone, then they realize at the design/analyze phase/outset that most funtionality couldn&#8217;t be done, but shove in as much as they could anyway.</p>
<p>If you&#8217;re forced to comply, what do you do?</p>
<p>You use <a href="http://www.sencha.com/products/touch/">Sencha Touch</a>.</p>
<p>Now the same story applies like it did in Flex with 1 key differnence: Using <a href="http://phonegap.com/">PhoneGap</a>, you can now target everything. All devices including their web browser, all while sharing 60% to 80% of your Service and Application Layer code. In theory&#8230; I&#8217;ve heard a lot of negativity towards Sencha Touch v1, but apparently v2 is a lot better, haven&#8217;t investigated the code yet, just testing the components on devices.</p>
<p>Pretty cool, huh?</p>
<p><a name="conclusions"></a><strong>Conclusions</strong></p>
<p>If you haven&#8217;t read <a href="https://plus.google.com/109047477151984864676/posts/CVGJKLMMehs">João Saleiro&#8217;s article</a>, and you&#8217;re a Flex Developer, I encourage you to do so. I&#8217;ve reached many of the same conclusions as he did. The comments also have a lot of good info as well. The most important being team velocity. Time is money. This isn&#8217;t important to just large companies, either.</p>
<p>There are a lot of things we can do better and faster in Flex for large scale applications. It doesn&#8217;t matter, however, for 2 reasons. First, while from a technical perspective Flex&#8217; future is bright, from a marketing and business one it&#8217;s over. The next 5 years are the sunset. Like FORTRAN and Cobol, companies invested billions, and those applications that run parts of their business don&#8217;t magically disappear overnight. Second, even if we know it may be a better solution for some use cases (many objects like Visio, highly dynamic interactions w/many redraws, compositing images &amp; video, etc), we&#8217;re ultimately beholden to what our clients want, even if we know what they need is different. Thus we have to do both: Flex and Ext JS.</p>
<p>Based on all of read and seen, next to Dojo, Ext JS is the best solution to utilize for HTML5 web application development if you are a Flex Developer dealing with large applications and teams. Their components, documentation, mobile story, company size, and growth show that they are close to reaching critical mass where it can be adopted by large companies as a viable product to use for things traditionally done by Flex. Additionally, a lot of what you already know carries over to Ext JS quite well. If you&#8217;re like me, you just need to freshen up on your DOM and CSS knowledge, and re-examine JavaScript with fresh eyes compared to the AJAX revolution bs of 7 years ago.</p>
<p>Furthermore, unlike other server-side solutions, Ext JS lends itself quite well to hybrid solutions with Flex being used for certain use cases and the HTML stack for others, all on the same project. You and/or your firm having the capability to provide both is immensely valuable. Utilizing Sencha Touch and PhoneGap, you now have multiple mobile options in your tool belt as well.</p>
<p>For the record, I still believe using Ext JS will take longer and have a harder to track velocity compared to using Flex. That said, I&#8217;m still diving into Ext JS with a positive attitude.</p>
<p>Good luck!</p>
<img src="http://feeds.feedburner.com/~r/jessewarden/~4/ycRuRkY9eK4" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://jessewarden.com/2012/02/sencha-ext-js-is-viable-technology-choice-for-flex-developers.html/feed</wfw:commentRss>
		<slash:comments>20</slash:comments>
		<feedburner:origLink>http://jessewarden.com/2012/02/sencha-ext-js-is-viable-technology-choice-for-flex-developers.html?utm_source=rss&amp;utm_medium=rss&amp;utm_campaign=sencha-ext-js-is-viable-technology-choice-for-flex-developers</feedburner:origLink></item>
	</channel>
</rss>

