petry-johnson.comMy journey to software development enlightenmenthttp://petry-johnson.com/blog/
http://www.rssboard.org/rss-specificationBlogEngine.NET 2.5.0.6en-UShttp://petry-johnson.com/blog/opml.axdhttp://www.dotnetblogengine.net/syndication.axdSeth Petry-Johnsonpetry-johnson.com0.0000000.000000The best session of CodeMash 2015? It's all about the bliss.<p>2015 was my fourth CodeMash. Or maybe my fifth; the awesome sauce tends to run together a bit in my mind.</p>
<p>In previous years my mind has been expanded, contorted, exhausted and sullied by all manner of educational days and "socially lubricated" evenings. I've walked away with lots of new ideas and technical goals, but this was the first year that my <em>spirit </em>was moved by a session. For the first time in a long time, I remembered why I love programming so much.</p>
<p>I went into&nbsp;<a href="http://twitter.com/CoriDrew">Cori Drew</a>'s "Geek Parenting Lessons Learned... so far" session hoping to learn a few practical tips for raising kids that enjoy, or at least understand, programming. Cori's 11-year-old daughter Katelyn is&nbsp;<a href="https://truncatedcodr.wordpress.com/2014/04/25/my-10yo-daughters-3-hour-scratch-workshop/">pretty damn amazing</a>&nbsp;and&nbsp;I figured I'd learn a thing or two.</p>
<p>And I <em>did </em>learn a thing or two, but honestly the value of that learning is eclipsed many times over by what I <em>felt </em>during the session. I felt joy, and hope.&nbsp;</p>
<h3><strong>Joy? Hope? At a technical conference?</strong></h3>
<p>Yup. Cori's passion for development was on full display, as was her love of the developer community and the enjoyment she gets from sharing those things with her daughter. She was truly infectious and reminded me of the early days of my own career when I'd work way into the night on a coding problem, searching for elegance amongst all of the curly braces and HTML tags. She reminded me how it felt to discover an aptitude for expressing myself through code patterns and syntax, and what it was like to discover a community of other people like me. She reminded me that what drew me to this thing was the coding itself, not the financial rewards or "leadership opportunities" that become the focus of a maturing career. She reminded me how much I love the <em>craft </em>of programming and sharing that craft with others.</p>
<p>And more than that, she was a <em>she,</em>&nbsp;talking about her own positive experiences and about a <em>young girl </em>finding a bit of that same joy.</p>
<p>You see, I spent the latter part of 2014 seeking out women to follow on Twitter. That gave me a front-row seat to <a href="http://gawker.com/what-is-gamergate-and-why-an-explainer-for-non-geeks-1642909080">GamerGate</a>&nbsp;and a bunch of other proof that women in tech have a <em>much </em>different experience than my own. And this saddened me; it sucks to see people struggling to get in, or remain in, the industry I love. Specifically, it made me sad for my daughter's chances at following in my footsteps. Can I really encourage her to explore an industry that <em>at best </em>treats her as an outsider, and at worst will threaten to rape or kill her just for having an opinion?</p>
<p>So I feel like Cori's talk was exactly the bit of perspective I needed. It was refreshing and inspiring to see a woman sharing a positive experience. She reminded me that we're fighting this fight for a <em>reason</em>, so that eventually we won't have to fight any more. And so I shared in her joy, hopeful that budding programmers like Katelyn will do amazing things not only with the tech, but with the culture as well.</p>
<p>As usual, CodeMash was great. Good content, great people, lots of fun. But the best thing it gave me was the most unexpected: a vision of a future where my kids can, if they choose, follow a love of programming out in the open, surrounded by a supporting community, and not hiding in the back of the room on BBS systems like I did.</p>
<p>I'm looking forward to 2016, CodeMash, but you have some work to do. The bar has been set pretty high.</p>http://petry-johnson.com/blog/post/2015/01/14/The-best-session-of-CodeMash-2015-Its-all-about-the-bliss.aspx
http://petry-johnson.com/blog/post/2015/01/14/The-best-session-of-CodeMash-2015-Its-all-about-the-bliss.aspx#commenthttp://petry-johnson.com/blog/post.aspx?id=060c1674-f7cd-470c-9db1-d5ffb63fff69Wed, 14 Jan 2015 19:40:00 -0700sethhttp://petry-johnson.com/blog/pingback.axdhttp://petry-johnson.com/blog/post.aspx?id=060c1674-f7cd-470c-9db1-d5ffb63fff69810http://petry-johnson.com/blog/trackback.axd?id=060c1674-f7cd-470c-9db1-d5ffb63fff69http://petry-johnson.com/blog/post/2015/01/14/The-best-session-of-CodeMash-2015-Its-all-about-the-bliss.aspx#commenthttp://petry-johnson.com/blog/syndication.axd?post=060c1674-f7cd-470c-9db1-d5ffb63fff69Six years in; do I get a gold watch yet?<p>This week marks my six-year anniversary with <a href="http://www.heuristics.net">Heuristic Solutions</a>. My longest stint prior to this was 3 years, so this feels pretty notable to me.</p>
<p>Sadly, no one brought me any cake today and I haven't received a gold watch yet. I'll attribute the lack of cake to the fact that I work from home and cake doesn't travel well in a USPS AirMail envelope, but last I checked watches won't spoil if left in the sun.... Anyways, I guess I'll have to mark the occasion myself by reflecting on my experiences here and turning them into some career advice tidbits. If you're looking to find a great place to settle down and grow, here's my advice:</p>
<h3>Work for people you trust</h3>
<p>It's a scary thing to not trust the people you work for, or to not know the content of their character or the direction of their moral compass. By contrast, it's incredibly liberating when you DO trust those people; it frees you up to take risks, to let your guard down, to align your interests for the betterment of both parties.&nbsp;</p>
<h3>Seek purpose, mastery and autonomy</h3>
<p>Immediately leave any job where you don't have a sense of purpose, you're not encouraged to seek mastery in your craft, and you have no sense of autonomy in your work or environment. A programmer with all 3 of those is truly livin' the dream. A programmer without purpose, without growth or learning, and with no freedom of thought or expression is miserable.</p>
<h3>Favor "career collaboration" over "employment negotiation"</h3>
<p><span>Three times over the past six years I've considered leaving, and all three times I decided not to. Each of those decisions was made following an open, honest and transparent conversation with my boss about my concerns. And I'm not talking about the "give notice and then take the counter offer" game, I'm talking about a collaborative discussion about goals, wants, desires, frustrations and intentions.&nbsp;</span>&nbsp;</p>
<div>It's hard to express why this is so significant, but it makes me feel less like a "resource" and more like a valued employee. And feeling valued is one of the reasons I continue to stick around.</div>
<div>
<h3>It's not about the tech</h3>
<p>By and large the reason that software projects succeed or fail is People and Process. I think you'd be hard pressed to find a project with great people and good processes that failed just because someone used the wrong data binding library, or used inheritance over composition, or put their braces in the wrong place. It's important to stay abreast of new technologies, and it's important to maintain a wide breadth of experience, but New and Shiny != Success. Find a team with the right principles and you'll be successful with pretty much any tech stack*.</p>
<p>* Unless that tech stack is VB.Net, which was built with sin and unicorn tears to maximize Eye Bleedage and WTFs Per Hour. Nothing but darkness awaits you there.</p>
<h3>If you never fail, you're not trying hard enough...</h3>
<p>The great thing about working for people you trust is that you can take risks. You can try out a new role, roll the dice on an ambitious architecture choice, or push your team in a new direction.&nbsp;</p>
<p>I've stayed in the same company for six years only because my role has changed significantly over time, and my role has changed because I wasn't afraid to try new things. If you're too busy covering your butt to try new things, you're in the wrong place.</p>
<h3>... but if you fail often, you're not managing expectations</h3>
<p>One of the most important skills I've developed over my career is "managing expectations". I can think of a number of projects where we missed some financial or calendar target but the client was still happy because we'd proactively managed surprises and given them options for managing change. Likewise, there were times that we hit the budget and deadline but the client <em>wasn't </em>happy because reality differed from their expectations. Success and failure have more to do with communication than they do with burning the midnight oil to release on time.&nbsp;</p>
</div>
<div>Manage expectations by putting yourself in someone else's shoes, looking at the situation from their vantage point, and then doing whatever you can do to make them feel informed and empowered. This skill is crucial for building trust and credibility with a client or an employer.</div>
<div>
<h3>No job is perfect, but you can always make it better</h3>
<p>No one is going to call you up out of the blue and offer you your dream job. Ain't gonna happen; every job you get offered will have parts that are awesome and parts that suck.&nbsp;</p>
</div>
<div>But that doesn't mean you can't make it <em>better</em>; I've been successful in my career, and at Heuristics particularly, by actively working to improve the things I didn't like. My team wasn't writing enough tests so I started writing helpers to make it easier; the tests weren't getting executed so I set up continuous integration; we weren't having frequent enough "lunch and learns" so I started scheduling them.&nbsp;</div>
<div>&nbsp;</div>
<div>If there's some aspect of your job that you don't like, <em>change it!</em>&nbsp;Worst case scenario is that you're unsuccessful, in which case you're no worse off than you are now. But far more likely your efforts result in a real and positive impact and you inch that much closer to <em>creating </em>your dream job.&nbsp;</div>
<div>&nbsp;</div>
<div>Remember: you can change the place you work, or you can change the place you work!</div>
<div>
<h3>In conclusion</h3>
<p>I feel blessed to have found a place so welcoming to me. I don't know what the next 6 years will bring, but I'm excited to find out.</p>
</div>http://petry-johnson.com/blog/post/2014/12/09/Six-years-in;-do-I-get-a-gold-watch-yet.aspx
http://petry-johnson.com/blog/post/2014/12/09/Six-years-in;-do-I-get-a-gold-watch-yet.aspx#commenthttp://petry-johnson.com/blog/post.aspx?id=471d8b28-f1b8-42dc-8080-8cc19cc67b38Tue, 09 Dec 2014 18:02:00 -0700sethhttp://petry-johnson.com/blog/pingback.axdhttp://petry-johnson.com/blog/post.aspx?id=471d8b28-f1b8-42dc-8080-8cc19cc67b38664http://petry-johnson.com/blog/trackback.axd?id=471d8b28-f1b8-42dc-8080-8cc19cc67b38http://petry-johnson.com/blog/post/2014/12/09/Six-years-in;-do-I-get-a-gold-watch-yet.aspx#commenthttp://petry-johnson.com/blog/syndication.axd?post=471d8b28-f1b8-42dc-8080-8cc19cc67b38Disorganization, procrastination, and the "zen desk"<p>I've been in my new house for just over a year. I have a nice little home office but the previous decor was terrible, so the first thing I did after moving in was rip up the carpet, re-paint, and buy new flooring.</p>
<p>You'll note that I said "<em>buy</em>" new flooring, and that I said nothing about <em>installing </em>new flooring. That's because I didn't actually get around to installing the floor; for a number of reasons, I just put that aside, set up my office on top of the bare wood subfloor, and went to work. Classy, right?</p>
<p>An interesting thing happens when you don't have a floor in your office. Since the floor looks like crap, there's not a lot of incentive to make anything <em>else </em>look nice. And over the course of the following year I worked in some pretty nasty conditions: papers everywhere, cables strung here-and-there, miscellaneous junk and empty Amazon shipping containers littering my bookshelves. It's very much like living in a "<a href="http://en.wikipedia.org/wiki/Broken_windows_theory">broken windows theory</a>" experiment.</p>
<p>Fast forward to May of this year when I started taking over a lot more of the technical analysis tasks for my team. These aren't tasks that I necessarily <em>enjoy </em>doing, at least not for a sustained period of time, and I've found myself struggling to stay focused. Just moving my gaze from one end of my desk to another would turn up any number of bills to pay, still-barely-edible food items to snack on, or dusty/dirty items that suddenly needed cleaned <em>right now who cares about that analysis deadline there are dust bunnies on the monitor!!!!!!</em></p>
<p>And then, just when I was most primed to be affected by it, the esteemed Cory House tweeted this:</p>
<blockquote class="twitter-tweet" lang="en">
<p>Disorganization in our physical space usually translates to feeling higher stress and less control. How's your desk looking?</p>
</blockquote>
<blockquote class="twitter-tweet" lang="en">&mdash; Cory House (@housecor) <a href="https://twitter.com/housecor/status/517313260232904704">October 1, 2014</a></blockquote>
<script charset="utf-8" type="text/javascript" src="//platform.twitter.com/widgets.js"></script>
<p>And suddenly I realized that by maintaining such a disorganized and messy office I was making it that much harder to stay focused and on task. I was basically surrounding myself with a thousand and one disruptions and making it <em>so damn easy </em>for my procrastinating brain to sabotage me. I was drowning, and it was my own hand holding me under the water.</p>
<p>And so I fixed it. I asked my wife to disappear with the kids for a weekend day, hired a little help and laid down the new floor, assembled a new desk, and organized the s!*t out of everything. I went so far as to hide every cable and piece of non-essential equipment out of view* so that my workspace is clean, uncluttered, and totally non-distracting.</p>
<p>Was my life magically transformed into a utopia of "Getting Things Done"-ness or was I equipped with the powers to call forth intense focus on command? Well, no. But I <em>do </em>feel less stress and I <em>have </em>been able to focus a little bit better. I can walk into my office, take a deep breath, and feel more relaxed than I ever could before. And that's meaningful.</p>
<p>So what about you? What does <em>your </em>home or office look like? You may not be in control of life, but you can at least be in control of your environment. Try it.</p>
<p><img src="http://petry-johnson.com/blog/image.axd?picture=2014%2f11%2foffice-desk.jpg" alt="" /></p>
<p><img src="http://petry-johnson.com/blog/image.axd?picture=2014%2f11%2foffice-shelves.jpg" alt="" /></p>
<p>* It took a ton of work but I was able to hide from view 3 USB hubs, 1 router, 1 network switch, 2 external hard drives, 1 Vonage box, 5 USB charging stations, 8 USB cables, 6 network cables, 3 standard power cables, 4 surge protectors and more wall-wart power supplies than I have fingers to keep track of. It often also holds at least 1 cat and averages less than 1 pair of pants per workday because, well, WFH and YOLO.</p>http://petry-johnson.com/blog/post/2014/11/15/Disorganization-procrastination-and-the-zen-desk.aspx
http://petry-johnson.com/blog/post/2014/11/15/Disorganization-procrastination-and-the-zen-desk.aspx#commenthttp://petry-johnson.com/blog/post.aspx?id=84f766ac-7ece-4b1d-a7e0-693dcf77ae46Sat, 15 Nov 2014 16:14:00 -0700sethhttp://petry-johnson.com/blog/pingback.axdhttp://petry-johnson.com/blog/post.aspx?id=84f766ac-7ece-4b1d-a7e0-693dcf77ae46946http://petry-johnson.com/blog/trackback.axd?id=84f766ac-7ece-4b1d-a7e0-693dcf77ae46http://petry-johnson.com/blog/post/2014/11/15/Disorganization-procrastination-and-the-zen-desk.aspx#commenthttp://petry-johnson.com/blog/syndication.axd?post=84f766ac-7ece-4b1d-a7e0-693dcf77ae46Hide Browser Link ["arterySignalR"] traffic from Fiddler<p>Visual Studio 2013 added a new feature called "<a href="http://blogs.msdn.com/b/webdev/archive/2013/06/28/browser-link-feature-in-visual-studio-preview-2013.aspx">Browser Link</a>" that allows Visual Studio to communicate with linked browsers in a two-way dynamic data exchange.&nbsp;</p>
<p>This is a great feature, but it's implemented by a super-chatty SignalR script that is dynamically injected into the website. This can be a problem if you're trying to use <a href="http://www.telerik.com/download/fiddler">Fiddler</a> to monitor or debug some traffic - the requests you care about can easily get lost in a sea of "<strong>.../arterySignalR/poll?transport-longPolling...</strong>" entries:</p>
<p>&nbsp;<img src="http://petry-johnson.com/blog/image.axd?picture=2014%2f7%2farterySignalR2.png" alt="" /></p>
<p>So how do you clean up Fiddler, without disabling Browser Link?&nbsp;</p>
<h3>Fiddler Custom Rules to the Rescue</h3>
<p>Fiddler supports <a href="http://docs.telerik.com/fiddler/knowledgebase/fiddlerscript/modifyrequestorresponse">custom rules</a>&nbsp;that can be easily extended to hide "noise" requests like this. To hide Browser Link traffic:</p>
<ol>
<li>Open <a href="http://www.telerik.com/download/fiddler">Fiddler</a>. If not already installed, chastise yourself and wonder how you made it this far in your career. Install it posthaste.</li>
<li>Click <em>Rules -&gt; Customize Rules</em></li>
<li>Search for "OnBeforeRequest" and add the statement shown below</li>
<li>Close and restart Fiddler, bask in the sudden peace and tranquility of a "arterySignalR"-less proxy session.</li>
</ol>
<p><img src="http://petry-johnson.com/blog/image.axd?picture=2014%2f7%2ffiddler-rule.png" alt="" /></p>http://petry-johnson.com/blog/post/2014/07/14/Hide-Browser-Link-arterySignalR-traffic-from-Fiddler.aspx
http://petry-johnson.com/blog/post/2014/07/14/Hide-Browser-Link-arterySignalR-traffic-from-Fiddler.aspx#commenthttp://petry-johnson.com/blog/post.aspx?id=5f531ff1-c0c7-49d1-905b-b2a622797252Mon, 14 Jul 2014 19:09:00 -0700sethhttp://petry-johnson.com/blog/pingback.axdhttp://petry-johnson.com/blog/post.aspx?id=5f531ff1-c0c7-49d1-905b-b2a622797252661http://petry-johnson.com/blog/trackback.axd?id=5f531ff1-c0c7-49d1-905b-b2a622797252http://petry-johnson.com/blog/post/2014/07/14/Hide-Browser-Link-arterySignalR-traffic-from-Fiddler.aspx#commenthttp://petry-johnson.com/blog/syndication.axd?post=5f531ff1-c0c7-49d1-905b-b2a622797252Core principles: your compass in the storm<p>Software development can be chaotic. We often need to make decisions based on missing data (or data we know is likely wrong), and it's difficult to ask outsiders for advice because the "right" answer is often context-dependent. In essence, <span style="background-color: #ffff00;">successful&nbsp;software development depends on repeatedly selecting the least bad option from a set of imperfect solutions</span>.</p>
<p>In practice, this means that developers cannot simply memorize solution patterns or "recipes". If I say "authentication" and you <em>immediately </em>think Forms Auth, then you're short-circuiting the selection process without evaluating the options. Same thing if I say "shorter feedback" and you <em>immediately </em>think "two week sprints". <strong>You can't make a good decision without evaluating your options</strong>, and just because you choose Solution A on a similar problem a month ago doesn't make it the appropriate solution to today's problem.</p>
<h2>"Been there, done that" is not a decision making process!&nbsp;</h2>
<p>Making decisions is <em>hard</em>. The deeper you analyze a problem the more variables you identify, and the more variables you identify the harder it is to reason through the myriad ways they interact. It's so much easier to look at a problem, wait a few nanoseconds while the pattern matching functions of your subconscious mind do their magic, and then do the same thing that you did the last time you had a similar problem. After all, you tell yourself, it's the "pragmatic thing to do" because you don't have to "waste time" on analysis or research. "The devil you know", and all that.</p>
<p>Not so fast.</p>
<p>Pattern matching is a great heuristic for quickly identifying <em>potential </em>courses of action, but not for selecting the best one. Making the best possible decision requires greater attention to detail and greater appreciation of nuance. If you get the details wrong then it might seem like a good decision at a high level, but eventually you'll suffer death by a thousand papercuts. [<em>Or you'll go broke under technical debt, etc. Insert your favorite metaphor here</em>]</p>
<h2>So <em>how </em>do we select from that set of imperfect solutions?</h2>
<p>The key to making good decisions is to <span style="background-color: #ffff00;">articulate your core values and principles, and then use them to derive a solution</span>. Rather than memorizing specific solutions, memorize the steps you follow and the questions you ask to <em>arrive</em> at a solution.</p>
<p>For example, at Heuristic Solutions we have identified four core values that guide everything we do:</p>
<ul>
<li><strong>Understanding: </strong>we can't be successful unless we know what "success" looks like</li>
<li><strong>Predictability</strong>: surprises are disruptive; we value procedures that minimize their impact</li>
<li><strong>Productivity: </strong>success requires efficient operations</li>
<li><strong>Quality: </strong>we value doing it right the first time; re-work is anathema to us</li>
</ul>
<p>When making a decision, we frame it in context of these values to better see the trade-offs at play. For example, a low degree of <em>Understanding</em> means we can't be very <em>Predictable</em>, so we do more up-front analysis when&nbsp;predictability is crucial. When <em>Productivity </em>is necessary then we invest in <em>Quality</em>&nbsp;so that we can preserve velocity over time.&nbsp;</p>
<p>This process forces us to consider those pesky (yet all-important) details specific to each situation. Sometimes this leads us to take radically different approaches to similar problems, but in each case we know we're maximizing for the things that truly matter to our success.</p>
<h2>What are <em>your </em>core values?</h2>
<p>What matters most to your organization? If you haven't already articulated your core values, take a minute to do so. Do you care about speed to market? What are you prepared (or not prepared) to sacrifice to get it? What does "quality" mean to you? How important are estimates to your planning process or stakeholders? Is it more important to maximize <em>developer </em>productivity, or <em>team </em>productivity?</p>
<p>When you're done, write them on your team board. Repeat them out loud each time you make a decision. Have discussions about which values are more important in each scenario, and then brainstorm ways to maximize those specific values.&nbsp;</p>
<p>One parting word of advice: <span style="background-color: #ffff00;">don't be afraid to follow your values, even if they contradict "best practices"</span>. While it's never a good idea to blindly ignore prevailing wisdom, realize that only YOU can fully appreciate the nuances of your specific situation. Core values are your compass, and by trusting them you allow yourself to select the best possible solution <em>for this specific decision</em>, ignoring "one size fits all" advice that might otherwise get in your way.</p>
<p>(Of course, if you <em>frequently </em>find yourself ignoring best practices then you might be thinking your situation is more unique than it really is. More on that in a later post!)</p>
<p>Bottom line: articulate what <em>really </em>matters to you, and then consciously and intentionally use those values every time you make a significant decision. You might be surprised at where this process takes you.</p>http://petry-johnson.com/blog/post/2013/04/30/Core-principles-your-compass-in-the-storm.aspx
http://petry-johnson.com/blog/post/2013/04/30/Core-principles-your-compass-in-the-storm.aspx#commenthttp://petry-johnson.com/blog/post.aspx?id=73d2e653-829e-4a89-bdb5-e53c077a4a64Tue, 30 Apr 2013 04:33:00 -0700consultingProgrammingsethhttp://petry-johnson.com/blog/pingback.axdhttp://petry-johnson.com/blog/post.aspx?id=73d2e653-829e-4a89-bdb5-e53c077a4a64725http://petry-johnson.com/blog/trackback.axd?id=73d2e653-829e-4a89-bdb5-e53c077a4a64http://petry-johnson.com/blog/post/2013/04/30/Core-principles-your-compass-in-the-storm.aspx#commenthttp://petry-johnson.com/blog/syndication.axd?post=73d2e653-829e-4a89-bdb5-e53c077a4a64Architecture and design are negotiable; clean code is not<p>In a perfect world, each and every feature we build would be lovingly crafted, properly factored, elegantly architected and fully tested... and we'd have enough budget for all of it.</p>
<p>I'm not lucky enough to live in that world. My job is to help clients use their limited budgets in ways that maximize their overall business objectives. Sometimes that means minimizing software maintenance costs, other times it means getting an imperfect feature into production as fast as possible. These types of decisions always involve trade-offs, often sacrificing some sacred agile calves on the altar of "getting it done".</p>
<p>So what's a pragmatic craftsman to do? How can we <strong>intentionally leverage technical debt</strong> to meet short term goals and still maintain a high bar of general quality in our code?</p>
<p>The principle I use in these situations is that <span style="background-color: #ffff00;">architecture and design are negotiable, but clean code is not</span>. This is best explained by breaking it down into component parts:</p>
<ul>
<li><strong>Architecture is negotiable. </strong>Not every project needs an <em>n</em>-tier separation of concerns. Not every project needs DI/IOC. Same for message buses, impersonation frameworks, 2nd level caching and so on. These things are often valuable and should not be forsaken lightly, but they do have costs. A pragmatic craftsman should be able to articulate those costs and weigh them against their value over time.<br />&nbsp;</li>
<li><strong>Design is negotiable</strong>.&nbsp;By "design" I mean the low level feature code. Sometimes you <em>can </em>get away with a switch statement instead of a Strategy, or tight coupling or low cohesion or large method bodies. Same for violating SOLID principles. I'm not saying do these things lightly, but be pragmatic about it. Learn to identify scenarios when their benefits will be realized, and scenarios when they won't.<br />&nbsp;</li>
<li><strong>Clean code is NOT NEGOTIABLE</strong>. Sacrificing architecture or design can be forgiven if you make it easy for future programmers to clean up and improve. This means that no matter how "dirty" your architecture is, be damn sure your code easy to read, clearly communicates your intent, and documents WHY you've made the decisions you have.</li>
</ul>
<h2>But aren't architecture and design part of "clean code"?</h2>
<p>Absolutely. Clean design trumps comments explaining bad design every day of the week. But you <em>will </em>face scenarios when you have to trade away <em>something </em>in favor of something else (time to market, hitting a budget, risk aversion, etc). This blog post is all about identifying those parts of clean code that you can give up, and which parts you should die on your sword to keep.</p>
<p>Here are some of the things I consider inviolable and strategies for preserving them:</p>
<ul>
<li><strong>Code should always be easy to read and understand</strong>. I don't care how nasty the architecture or design is, I don't care how stripped down the feature is, and I don't care what your budget is. You should <em>always </em>make it easy for the next programmer down the road to understand your intent (what you <em>mean </em>the code to do) and your implementation (what the code <em>actually does</em>).<br />&nbsp;</li>
<li><strong>The messier the architecture or design, the more you should document with comments.</strong>&nbsp;Well written clean code doesn't need a lot of "here's what I was thinking" commentary. That commentary is much more valuable when you're taking shortcuts and incurring technical debt, because it can make it much easier for someone to pay back that debt later. My rule of thumb is, <span style="background-color: #ffff00;">do it right yourself or provide clues to help the next dev make it right later</span>. (With a huge preference on the former!)<br />&nbsp;</li>
<li><strong>Keep your eye on the prize.</strong>&nbsp;In other words, always have an idea of what the end goal would be. Think about what you <em>wish </em>you could be implementing and try and "lean" the code in that direction. For example, think about what the very first step of refactoring would look like. Can you go ahead and take that first step now?</li>
</ul>
<h2>Closing thoughts</h2>
<p>Like many of my posts, I'm talking about edge cases. Most of the time we should be striving for clean code <em>including </em>architecture and design. Too many programmers (and clients!) are far too quick to take shortcuts, and this post is NOT about taking more of them.</p>
<p>But if you've fought the good fight and tried everything else first, and you <em>still </em>need a shortcut, then be sure you do it cleanly and in a way that can be easily fixed later.</p>
<p>Happy coding!</p>http://petry-johnson.com/blog/post/2012/11/29/Architecture-and-design-are-negotiable;-clean-code-is-not.aspx
http://petry-johnson.com/blog/post/2012/11/29/Architecture-and-design-are-negotiable;-clean-code-is-not.aspx#commenthttp://petry-johnson.com/blog/post.aspx?id=31658882-3048-43b7-bea8-381c51efa22eThu, 29 Nov 2012 04:42:00 -0700Programmingsethhttp://petry-johnson.com/blog/pingback.axdhttp://petry-johnson.com/blog/post.aspx?id=31658882-3048-43b7-bea8-381c51efa22e925http://petry-johnson.com/blog/trackback.axd?id=31658882-3048-43b7-bea8-381c51efa22ehttp://petry-johnson.com/blog/post/2012/11/29/Architecture-and-design-are-negotiable;-clean-code-is-not.aspx#commenthttp://petry-johnson.com/blog/syndication.axd?post=31658882-3048-43b7-bea8-381c51efa22eJOIN-less lookup fields using enums and metadata attributes<p>One of the projects I work on contains a large database with a lot of lookup fields containing status codes, record types, processing flags, etc. A great deal of these are implemented in a typical normalized fashion with two tables and a foreign key relationship:</p>
<p><img src="http://petry-johnson.com/blog/image.axd?picture=2012%2f9%2fblogpost-JOINless-ERD2.png" alt="" /></p>
<p>Pretty standard stuff, right? Sure, yet at the start of a new development phase last year I decreed <span style="background-color: #ffff00;">Thou Shalt No Longer Do This!<span style="background-color: #ffffff;">&nbsp;&nbsp;</span></span></p>
<h2><span style="background-color: #ffff00;"><span style="background-color: #ffffff;">What's the big deal with lookup tables?</span></span></h2>
<p><span style="background-color: #ffff00;"><span style="background-color: #ffffff;">On this project (and on many of my others) I had noticed the following patterns:</span></span></p>
<ol>
<li>The vast majority of the lookup tables contained a single "Name" field containing a human-readable description of that status code or record type.</li>
<li>Because the database is so large, a typical query might need to do five or six joins <em>just to get the names of the lookup values</em>.</li>
<li>The values in the lookup table rarely changed. When they did change, it was always as part of a scheduled release.</li>
</ol>
<div>In short, <strong>we were paying a performance penalty on <span style="text-decoration: underline;">each and every query</span>&nbsp;to obtain unchanging metadata about a small, discrete set of known values</strong>.</div>
<div>&nbsp;</div>
<div>In addition, dealing with these joins by hand was an annoyance whenever we needed to write manual T-SQL queries or express ad-hoc queries directly against the Linq to Sql data context.&nbsp;</div>
<h2>There's Got To Be A Better Way!&nbsp;&trade;</h2>
<p>The solution that we implemented, and that we're still using nearly two years later, is simple:</p>
<ul>
<li>All lookup-style data (status codes, record types, etc) have a corresponding C# Enum</li>
<ul>
<li>A custom Attribute associates each value with a human-readable string</li>
<li>A custom Attribute associates each value with a database key representation</li>
</ul>
<li>There are no lookup tables or foreign keys.</li>
<ul>
<li>The domain model contains properties of the Enum types</li>
<li>In the database, each lookup field is a <span style="text-decoration: underline;">string</span>, not an integer foreign key</li>
<li>When we write <em>to</em> the database, we convert the enum into its database representation and store that value</li>
<li>When we read <em>from </em>the database, we convert the stored string into an enum instance</li>
</ul>
<li>The parsing and conversion is handled via extension methods:</li>
<ul>
<li>String.ToEnum&lt;T&gt;</li>
<li>Enum.ToDescription()</li>
<li>Enum.ToStringConstant()</li>
</ul>
</ul>
<div>A picture is worth a thousand words here:</div>
<p><img src="http://petry-johnson.com/blog/image.axd?picture=2012%2f9%2fblogpost-JOINless-samples2.png" alt="" /></p>
<h2>Was it worth the effort?&nbsp;</h2>
<p>After nearly two years of use I'm pleased to say that this pattern has served us well. The extension methods make the lookup values easy to use, avoiding joins improves system performance, and storing strings (rather than foreign key integers) in the tables makes the raw data a little bit easier to use.&nbsp;</p>
<p>Of course, your mileage may vary. This technique isn't appropriate if your lookup values are dynamic (rather than a fixed set) or if you need to track a large amount of metadata in the lookup table. But if your project has the same characteristics that mine does, I recommend you give this a shot.</p>
<p>Happy coding!</p>
<h2>&nbsp;</h2>
<h2>Appendix: the source code</h2>
<p>I slopped the code for the attribute classes and extension methods onto <a href="https://github.com/spetryjohnson/Blog-Samples-and-Examples/blob/master/JOIN-less-lookups-with-enums.cs">my Github repo</a>.</p>http://petry-johnson.com/blog/post/2012/09/19/JOIN-less-lookup-fields-using-enums-and-metadata-attributes.aspx
http://petry-johnson.com/blog/post/2012/09/19/JOIN-less-lookup-fields-using-enums-and-metadata-attributes.aspx#commenthttp://petry-johnson.com/blog/post.aspx?id=94376252-f1e1-4a50-ad94-a5d61d382a85Wed, 19 Sep 2012 18:10:00 -0700sethhttp://petry-johnson.com/blog/pingback.axdhttp://petry-johnson.com/blog/post.aspx?id=94376252-f1e1-4a50-ad94-a5d61d382a85867http://petry-johnson.com/blog/trackback.axd?id=94376252-f1e1-4a50-ad94-a5d61d382a85http://petry-johnson.com/blog/post/2012/09/19/JOIN-less-lookup-fields-using-enums-and-metadata-attributes.aspx#commenthttp://petry-johnson.com/blog/syndication.axd?post=94376252-f1e1-4a50-ad94-a5d61d382a85Avoid heroics; real value comes from discipline<p>Spend any amount of time in this industry and you'll eventually end up playing the hero. Maybe you meet that deadline by pulling a 70-hour week, or you fix that production issue by editing a script or database procedure directly on the server. You shipped the product, you fixed the bug, you "got the job done". You're a hero, right?</p>
<p>The only problem is, <strong>heroic behavior is dangerous</strong>. I've played the hero enough times to know what happens&nbsp;after the dust settles:</p>
<ul>
<li>You pull a 70-hour week and hit the deadline, but the code sucks. It isn't tested, it has bugs, or it just feels like a half-assed feature.&nbsp;</li>
<li>You hot-fix a file on the web server, but forget to update source control. The next deployment replaces your fix and re-introduces the bug.</li>
<li>You hot-fix the database server, and the next deployment crashes because a table or column already exists.</li>
<li>You burn out, lose focus, and make stupid mistakes.</li>
</ul>
<div>The common pattern here is that you've <span style="background-color: #ffff99;">achieved a short-term goal at the cost of <strong>highly unpredictable</strong> future results</span>. Someone, somewhere, will have to clean up the mess when it catches them by surprise.&nbsp;<br /><br />In other words, you've created <span style="text-decoration: underline;">bad</span>&nbsp;<a href="http://blogs.construx.com/blogs/stevemcc/archive/2007/11/01/technical-debt-2.aspx">technical debt</a>&nbsp;that is unintentional, hard to manage, and hard to quantify.</div>
<h2>So what's the solution?&nbsp;</h2>
<p>It's certainly easier said than done, but <span style="background-color: #ffffff;">the solution is to <strong>stay disciplined and&nbsp;</strong><strong>stick to your process</strong></span>.&nbsp;</p>
<p>If that process says you write tests first and get QA feedback before committing to trunk, then that's what you need to do... even if it means missing a deadline.</p>
<p>If that process says you must create a formal release package to modify the production database, then that's what you do... even if it means taking longer to fix the bug.</p>
<p>Discipline yields predictability by forcing you to be <em>proactive</em>. It helps minimize future surprises and prevents you from becoming overly&nbsp;<em>reactive</em>, which can often lead to a cascading series of errors when you start jumping from fire to fire.</p>
<h2>When to cheat</h2>
<p>There are obviously exceptions. If the server is <em>totally down</em>, and you know of a quick fix to bring it back online, then maybe you should fix it. But if you've internalized these principles then you'll feel <em>real damn uncomfortable </em>doing it, and that discomfort will remind you to take the necessary "after-action" steps to pay back that technical debt immediately after the crisis passes.</p>
<p>Remember kids: avoid heroics. Real, lasting value comes from staying disciplined...&nbsp;<em>especially </em>when you feel pressure not to.&nbsp;</p>http://petry-johnson.com/blog/post/2012/08/01/Avoid-heroics;-real-value-comes-from-discipline.aspx
http://petry-johnson.com/blog/post/2012/08/01/Avoid-heroics;-real-value-comes-from-discipline.aspx#commenthttp://petry-johnson.com/blog/post.aspx?id=cea85472-fa6d-4a44-aa9e-e5188fe8b56fWed, 01 Aug 2012 19:11:00 -0700consultingProgrammingsethhttp://petry-johnson.com/blog/pingback.axdhttp://petry-johnson.com/blog/post.aspx?id=cea85472-fa6d-4a44-aa9e-e5188fe8b56f885http://petry-johnson.com/blog/trackback.axd?id=cea85472-fa6d-4a44-aa9e-e5188fe8b56fhttp://petry-johnson.com/blog/post/2012/08/01/Avoid-heroics;-real-value-comes-from-discipline.aspx#commenthttp://petry-johnson.com/blog/syndication.axd?post=cea85472-fa6d-4a44-aa9e-e5188fe8b56fTest Data Setup: Staying clean, DRY, and sane<p>There are many good reasons to avoid hitting a database in your tests. I agree with all of them, and I try my best to avoid doing it.</p>
<p>However, some tests <em>do </em>need to hit the database. Even the most dependency-injected and mock-infested system should hit the database when testing the data access layer... after&nbsp;all, what good is a test suite that doesn't test any of your actual data access logic? And if&nbsp;you're smart and follow the&nbsp;<a href="http://jamescrisp.org/2011/05/30/automated-testing-and-the-test-pyramid/">testing pyramid</a>&nbsp;then you'll have some integration and acceptance tests that need a database as well.</p>
<p>In "<a href="http://www.petry-johnson.com/blog/post/2011/12/17/Rules-for-effective-data-testing.aspx">Rules for Effective Data Tests</a>" I mentioned some strategies for setting up those data tests. This post expands on those ideas and shows how to keep your setup code clean, <a href="http://en.wikipedia.org/wiki/Don't_repeat_yourself">DRY</a>&nbsp;and maintainable.</p>
<h2>What's so difficult about setting up a data test?</h2>
<p>First, a definition. When I say "data setup" I'm talking about <span style="background-color: #ffff99;">anything you do in the body of a test [or a setup method] to create the database records needed for a given test to execute</span>.</p>
<p>While similar to the setup of a "true" unit test, interacting with a Real Life Database&trade; makes things a little more interesting. Some of the challenges we have to overcome are:</p>
<ul>
<li><strong>Test residue:&nbsp;</strong>Unless we delete it, data created by each test remains in the database when the test exits. At best this just wastes space; at worst, it starts to interfere with other tests. (<em><a href="http://haacked.com/archive/2005/06/10/4580.aspx">See here</a> for a common solution to this problem)</em>&nbsp;</li>
<li><strong>Database constraints:</strong> Foreign key constraints are a real pain. When setting up test data you need to create the entire data graph to satisfy the database constraints, regardless of if those relationships are actually relevant to the test.&nbsp;&nbsp;</li>
<li><strong>Verbosity:&nbsp;</strong>Because of the foreign key issues mentioned above, setting up data tests requires more code than setting up a unit test. This makes tests harder to write, harder to maintain, and harder to keep DRY.&nbsp;</li>
<li><strong>False negatives:</strong>&nbsp;The more complex the setup,&nbsp;the greater the change that tests will fail not because your application logic is wrong, but because you screwed up the setup.&nbsp;</li>
<li><strong>Painful to debug:&nbsp;</strong>Debugging a data test is more difficult and time consuming than a unit test. Not only does the test take longer to run, but debugging it often means poking around in both the application debugger <em>and </em>a database tool.</li>
</ul>
<div>A daunting list to be sure, but it's manageable.</div>
<h2>Characteristics of good setup code</h2>
<p>The primary contributor to the quality and maintainability of your data tests is the setup code; <span style="background-color: #ffff99;">the easier it is for someone to understand the specific scenario you are creating, the better equipped they are to maintain that test</span>.</p>
<p>Conversely, the harder the scenario is to understand and maintain, the less value that test will provide over time. Tests that contain an unintelligible jumble of setup code have a very real risk of being deleted (rather than fixed) if they ever break due to new code changes.</p>
<p>So what is "good" setup code? It should be:&nbsp;</p>
<ul>
<li><strong>Highly expressive</strong> (high signal-to-noise ratio). Readers should be able to very quickly understand the scenario(s) you are creating without mentally parsing code.&nbsp;</li>
<li><strong>Highly reusable</strong> through the use of default values. If I just need to create a Person, let me call "CreatePerson()" and fill in the details for me.&nbsp;</li>
<li><strong>Easily customizable</strong> to each test's needs. Since the customized data are usually very relevant to the test at hand, it should be easy for a reader to spot them.&nbsp;&nbsp;</li>
<li><strong>Maintainable; </strong>databases change, and its not uncommon to add a new required field. The fewer changes you need to make to existing test code to support these changes the better.</li>
</ul>
<div>These characteristics aren't specific to data tests, of course. They apply equally well to setup code of any kind.</div>
<div>&nbsp;</div>
<div>So what happens when we apply these principles? Read on for specific suggestions...</div>
<h2>Data Helpers: the Object Mother pattern for DB entities</h2>
<p>The <a href="http://martinfowler.com/bliki/ObjectMother.html">Object Mother pattern</a>&nbsp;describes a special kind of factory class that encapsulates the instantiation of an object (or group of objects) in a specific state, usually mirroring a common scenario in the underlying domain. For instance, you might have an Object Mother that creates an Order object, adds some Order Items and marks it as Shipped. <span style="background-color: #ffff99;">The goal is to turn a complex initialization process into a one-liner so that it is easier to read and maintain</span>.</p>
<div>We can use this same approach in a data test, except that instead of constructing an object in code we need to create one or more records in the database. I call these classes "<strong>Data Helpers</strong>" and they generally:</div>
<div>
<ul>
<li><strong>Are static classes</strong>: These classes have no need to ever be mocked out, and making them static makes them easier to invoke in your tests. Omitting the need to instantiate them increases the signal-to-noise ratio and keeps setup code lean.</li>
<li><strong>Follow a naming convention: </strong>It's important that other developers can discover and use your helpers, so follow an obvious naming convention. I recommend:</li>
<ul>
<li>Put all Data Helpers in the same namespace</li>
<li>Name according to the primary entity being created. OrderHelper, CustomerHelper, etc.</li>
</ul>
<li><strong>Create a single "primary" entity</strong>: I find that Data Helpers are best focused around a single primary entity, such as an Order. It's fine if they create child or related data for the primary entity, but they should avoid creating a large number of collaborating entities. See below for how to use "scenario" objects for more complicated setups.</li>
<li><strong>Treat performance as an important, but secondary, concern: </strong>Data Helpers provide their primary value by reducing the cost to create and maintain data tests, so whenever "speed of execution" and "ease of use" are at odds with each other, favor ease of use. That doesn't mean you shouldn't care about performance, and in fact you <em>should care very much</em>. Just not so much that you erode the overarching goal. You can easily offload the performance hit to the CI server. &nbsp;(<em>You <span style="text-decoration: underline;">do</span>&nbsp;have a CI server, right?</em>)</li>
</ul>
<div>The methods exposed by a Data Helper class should:</div>
<ul>
<li><strong>Use optional parameters for as much as possible:</strong>&nbsp;A primary benefit of Data Helpers is dramatically increasing the signal to noise ratio within setup logic. Callers should only have to specify the specific values that are significant to their test; all other properties should be created using reasonable defaults.</li>
<li><strong>Are semantic:</strong>&nbsp;Don't be afraid to create highly specialized methods, such as <em>CreateOrderWithBackorderedItems</em><em>()</em>, which&nbsp;usually just delegate to a more general method with a specific combination of arguments. <span style="background-color: #ffff99;">This can dramatically improve maintainability<span style="background-color: #ffffff;">; if you add a new field to the database, and you can easily infer the correct default value based on the semantics of the method call, then you can implement that new field in the helper method without touching any of the existing tests.</span></span></li>
<li><strong>Return the created entity: </strong>The caller probably needs to know about the data that was created, so return the entity object that you just created.&nbsp;</li>
</ul>
</div>
<h2>Data Scenarios: a bunch of Object Mothers working together</h2>
<p>Data Helpers are great when you need to create test data, especially if you want to specify a few key properties and use defaults for the rest.</p>
<p>But what if you want to create multiple related entities, or you want to reuse a specific setup in multiple tests? For instance, you need to create a Customer, with completed Orders in the past, and an in progress Order that's ready for checkout. In these cases, I create a special type of Data Helper that I call a "<strong>Data Scenario</strong>".&nbsp;</p>
<p>Scenario objects have these characteristics:</p>
<ul>
<li><strong>Create a large or complex set of data:</strong>&nbsp;Just like Data Helpers reduce individual object setup to a one-liner, Scenarios reduce multiple object setup to a one-liner.</li>
<li><strong>Model real-world scenarios: </strong>The whole&nbsp;point of a Scenario is to encapsulate realistic data patterns that might exist in production.</li>
<li><strong>Expose a smaller set of configurable defaults: </strong>Scenarios tend to expose fewer arguments than Data Helpers because they are better suited to creating general purpose groups of data rather than highly-specific records.</li>
<li><strong>Are often used in fixture-level setup: </strong>A common pattern is for a group of tests to share a Scenario object that is created in the test fixture's setup routine, and then provide test-specific adjustments to the Scenario via inline Data Helper calls.&nbsp;</li>
<li><strong>Are instantiated, not static: </strong>Scenario objects are NOT static methods of a helper class. Instead, they are objects that get instantiated and perform their data manipulations in the constructor. This allows Scenarios to be created, manipulated and passed around as needed.</li>
<li><strong>Expose pointers to the interesting data: </strong>A Scenario object should contain public properties containing references to the entities it creates (or at least their IDs). This allows test code to further manipulate the Scenario data or to make assertions against it.&nbsp;</li>
</ul>
<div>
<h2>Common objections to these techniques</h2>
<p>Some of the specific objections that I've heard are:</p>
<ul>
<li><strong>It takes a lot of time/code to write/maintain helpers: </strong>Yes, on a complex system you'll end up with a decent amount of non-production code implementing these helpers. And yes, it requires an investment of time to get started. But I've been using these patterns for two years on a large application and <span style="background-color: #ffff99;">I'm absolutely convinced the effort is justified</span>. Once you get a decent library of helpers set up it becomes really, really easy to write tests... sometimes even easier than setting up expectations in a true unit test!</li>
<li><strong>The tests take a long time to run: </strong>Yes, they do. You should do your best to avoid hitting the database except when necessary, and you should lean on your CI server to run the whole suite for you. If you can find a way to test the data access code without hitting the database, I'll eat my hat.</li>
<li><strong>Its hard to know what helpers exist: </strong>True, if you're not the author of the helpers then they are harder to use. That's why it's so important to follow good naming conventions. You can also, you know, <em>talk to&nbsp;</em>your teammates if you create a new helper or wonder if one exists.</li>
<li><strong>I don't wanna:</strong>&nbsp;If you don't care about testing the data access code, or you don't care about writing good tests, then I got nothin'. Go play in traffic.</li>
</ul>
<div>Let's face it:&nbsp;<strong>data tests suck</strong>, but they are a necessary evil. The goal is to maximize their value while minimizing their cost, and that's what these techniques do.</div>
<h2>Closing thoughts</h2>
<p>In my experience it works best to think of <strong>Scenarios</strong> as the broad context in which a test will execute; they create all of the background data that is necessary for a test to run, but isn't very significant by itself.&nbsp;<strong>Data Helpers</strong> are used to create specific data records that <em>are </em>significant to a specific test.&nbsp;Used together, they create a very rich language for setting up your test data in an easy to write, easy to read, and easy to maintain form.</p>
<p>I've been using these techniques on a multi-year, multi-developer, multi-hundreds-of-thousands-LOC project and I am convinced that they are directly responsible for allowing us to maintain high test coverage on a very data-intensive app.&nbsp;</p>
<p>Happy testing!&nbsp;&nbsp;</p>
</div>http://petry-johnson.com/blog/post/2012/07/24/Test-Data-Setup-Staying-clean-DRY-and-sane.aspx
http://petry-johnson.com/blog/post/2012/07/24/Test-Data-Setup-Staying-clean-DRY-and-sane.aspx#commenthttp://petry-johnson.com/blog/post.aspx?id=6d441387-70b5-44b6-bd94-e298dee9c929Tue, 24 Jul 2012 18:27:00 -0700.NETProgrammingtestingsethhttp://petry-johnson.com/blog/pingback.axdhttp://petry-johnson.com/blog/post.aspx?id=6d441387-70b5-44b6-bd94-e298dee9c9291559http://petry-johnson.com/blog/trackback.axd?id=6d441387-70b5-44b6-bd94-e298dee9c929http://petry-johnson.com/blog/post/2012/07/24/Test-Data-Setup-Staying-clean-DRY-and-sane.aspx#commenthttp://petry-johnson.com/blog/syndication.axd?post=6d441387-70b5-44b6-bd94-e298dee9c929Defensive Programming: Avoid Tomorrow's Debugging, Today<p>Just as I was trying to write a good intro to this post, Jimmy Bogard tweeted:</p>
<blockquote class="twitter-tweet">
<p>"System.OverflowException: Value was either too large or too small for an Int32." yes. what was the original value? oh, don't know? sigh.</p>
&mdash; Jimmy Bogard (@jbogard) <a href="https://twitter.com/jbogard/status/225654693085462530" data-datetime="2012-07-18T18:14:05+00:00">July 18, 2012</a></blockquote>
<script charset="utf-8" type="text/javascript" src="//platform.twitter.com/widgets.js"></script>
<p>I've felt that frustration myself many times.&nbsp;I work on large software systems and often have to troubleshoot hard-to-replicate, data-specific defects given only an error message and limited access to the production environment. Turning this limited data into an actionable bug report can be very, very difficult.</p>
<p>This experience has shown me that there are two types of programmers: those that <em>intentionally</em> craft code that it is easy to debug, and those that don't. Programmers that <em>don't</em> do this are, unfortunately, incredibly common and incredibly costly to an organization. <strong>Don't be that guy/gal whose code everyone hates to debug!</strong></p>
<p>This post explains some coding techniques that will make your systems easier to troubleshoot and less costly to maintain. Use them; your team will love you for it!</p>
<h2>What does "defensive programming" look like?</h2>
<p>"Defensive Programming" refers to a&nbsp;<span style="background-color: #ffff99;">collection of coding techniques that decrease maintenance costs by surfacing defects as early as possible, and by making them easy to troubleshoot.&nbsp;</span>There are many articles on this topic, some arguing&nbsp;<a href="http://swreflections.blogspot.com/2012/03/defensive-programming-being-just-enough.html">for</a>&nbsp;and&nbsp;<a href="http://danielroop.com/blog/2009/10/15/why-defensive-programming-is-rubbish/">against</a>&nbsp;it, and I encourage you to read them for additional insight.</p>
<p>Specifically, defensive programming means that you:</p>
<ul>
<li><a href="#clean">Write clean, simple, intent-revealing code</a></li>
<li><a href="#input">Assume inputs are tainted until proven otherwise</a></li>
<li><a href="#fail">If you can't avoid an error, fail early and with a useful message</a></li>
<li><a href="#defaults">Use "fail safe" default values, where appropriate</a></li>
<li><a href="#future">"Future proof" your program flow</a></li>
</ul>
<p><a name="clean"></a></p>
<h3>Write clean, simple, intent-revealing code</h3>
<p>This is a universal requirement, I don't care if you're coding defensively, offensively or somewhere in the middle. The easiest defect to fix is the one that never occurs, and simple code is less likely to contain defects than complex code, so keep your designs as simple as possible.</p>
<p>(If you don't agree with this statement, stop reading and go play in traffic... your team will thank you!)</p>
<p><a name="input"></a></p>
<h3>Assume inputs are tainted until proven otherwise</h3>
<p>Most applications need data to function and many programmers make assumptions about their data, such as "this string will never be empty" or "this value will always be positive".&nbsp;</p>
<p>Unfortunately, that string <em>can </em>be empty in some cases, and that value <em>will </em>be zero at some point in time. If you don't validate your assumptions before using the data then you risk intermittent, hard-to-troubleshoot errors.&nbsp;</p>
<p>Therefore, do sanity checks on your input BEFORE you use it. Use a "design by contract" tool like <a href="http://msdn.microsoft.com/en-us/devlabs/dd491992.aspx">Code Contracts for .NET</a> if you can, or do it manually if you must. In any case, <strong>validate your input before you use it <span style="background-color: #ffff99;">and display a <span style="text-decoration: underline;">helpful</span> error message if validation fails</span></strong>. (See below for more on helpful exceptions)</p>
<p>In addition to making these errors easier to diagnose, treating all input as potentially hostile is also a security best practice. Sanity check your data and make both your teammates AND your security team a little happier!</p>
<p><a name="fail"></a></p>
<h3>Fail early, with useful messages</h3>
<p>This is as important as it gets.</p>
<p>Imagine you get an error report that says "<em>Sequence contains no elements</em>". What do you do next? If you're lucky enough to get a stack trace then you can trudge through the code looking for the offending line, but what happens if the offending line contains multiple statements chained together?&nbsp;</p>
<p>Now imagine the error report says "<em>Could not obtain order items for order 1234; sequence contains no elements</em>". You haven't looked at a single line of code yet, and you already have way more information about the problem!</p>
<p>Same goes for null reference exceptions: Would you rather see "<em>Object reference not set to an instance of an object</em>" or "<em>Cannot calculate sales tax for order 1234; Tax Calculator object was null</em>"? &nbsp;</p>
<p>The key principle here is that you should anticipate errors that might occur and <span style="background-color: #ffff99;">throw exceptions that provide key debugging info directly in the error message:</span></p>
<ul>
<li>Help the programmer locate the statement that failed and understand WHY it failed.</li>
<li>Include key pieces of data needed to reproduce it: order ID, customer ID, etc. (<em>Obviously, be careful not to expose identifiers that could compromise the security of your system!</em>)</li>
</ul>
<div>Ask yourself, "if this occurs in production 6 months from now, what pointers would I need to zero in on the problem?" and then include those pointers in the exception.&nbsp;</div>
<p><a name="defaults"></a></p>
<h3>Use "fail safe" default values, where appropriate</h3>
<p>In many cases, invalid data may not necessarily require an exception.&nbsp;For example, ask yourself these questions about each variable or statement you write:</p>
<ul>
<li>Can I treat null strings the same as empty strings?</li>
<li>Can I treat null sequences (lists, arrays, etc) the same as empty sequences?</li>
<li>If a string parsing fails, can I substitute a default value instead of throwing an exception?</li>
</ul>
<div>If the answer to any of these questions is "yes" then use the null coalescing operator or conversion helpers to convert null or invalid values into something less "exception prone". I rarely need to differentiate between null and empty sequences so I've written an <em><strong>.ToEmptyIfNull()</strong></em>&nbsp;extension method that I use whenever I need to iterate over a collection. Major reduction in null reference exceptions for negligible effort.</div>
<div>&nbsp;</div>
<div>Of course, sometimes you DO care about differentiating between null and empty, or ensuring a parse succeeds. In those cases just throw a helpful error message (see above) as soon as you detect the problem.&nbsp;</div>
<p><a name="future"></a></p>
<h3>"Future proof" your program flow</h3>
<p>I've seen a lot of defects occur when business conditions change, and something that "could never happen" when the code was written suddenly becomes possible.&nbsp;</p>
<p>Examples:</p>
<ul>
<li>When you write a <em>switch</em> statement, always include a default branch. It's better to have the default branch throw an exception like "<em>not implemented condition 'FOO'</em>" than silently fall through and cause a potentially harder-to-debug error. &nbsp;(<em>Of course, you do your best to <a href="http://sourcemaking.com/refactoring/replace-conditional-with-polymorphism">avoid switch statements</a>, don't you?</em>)&nbsp;&nbsp;</li>
<li>When you have a chain of <em>if/else-ifs</em>, always include an else branch. If it should never be reached, throw an exception that explains the conditions that occurred and why you expected them to never happen.&nbsp;&nbsp;</li>
<li>If you're dealing with combinations of different states or variables, and certain combinations "should never occur", go ahead and handle those combinations anyway. It's better to throw an exception you can control than to let the system fail on its own. &nbsp;(For example,&nbsp;"<em>Order 123 has status SHIPPED, but IS_CANCELLED was true; is the update service malfunctioning?</em>")</li>
</ul>
<h2>Go, make the world a brighter place!&nbsp;</h2>
<p>Using these techniques can help you avoid errors in production and can make it easier to resolve errors that do occur.&nbsp;&nbsp;Using them will bring joy to the hearts of men and will make you beloved amongst your teammates. Use them; do it for the children.</p>http://petry-johnson.com/blog/post/2012/07/18/Defensive-Programming-Improving-Tomorrows-Debugging-Today.aspx
http://petry-johnson.com/blog/post/2012/07/18/Defensive-Programming-Improving-Tomorrows-Debugging-Today.aspx#commenthttp://petry-johnson.com/blog/post.aspx?id=cf331928-c845-4b44-983b-5d656dccbd29Wed, 18 Jul 2012 04:38:00 -0700Programmingsethhttp://petry-johnson.com/blog/pingback.axdhttp://petry-johnson.com/blog/post.aspx?id=cf331928-c845-4b44-983b-5d656dccbd291519http://petry-johnson.com/blog/trackback.axd?id=cf331928-c845-4b44-983b-5d656dccbd29http://petry-johnson.com/blog/post/2012/07/18/Defensive-Programming-Improving-Tomorrows-Debugging-Today.aspx#commenthttp://petry-johnson.com/blog/syndication.axd?post=cf331928-c845-4b44-983b-5d656dccbd29