<?xml version="1.0" encoding="UTF-8"?> <rss
version="2.0"
xmlns:content="http://purl.org/rss/1.0/modules/content/"
xmlns:wfw="http://wellformedweb.org/CommentAPI/"
xmlns:dc="http://purl.org/dc/elements/1.1/"
xmlns:atom="http://www.w3.org/2005/Atom"
xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
><channel><title>The Inquisitive Coder - Davy Brion&#039;s Blog &#187; Code Quality</title> <atom:link href="http://davybrion.com/blog/category/code-quality/feed/" rel="self" type="application/rss+xml" /><link>http://davybrion.com/blog</link> <description>inquisitive: adjective. given to inquiry, research, or asking questions; eager for knowledge; intellectually curious</description> <lastBuildDate>Mon, 14 May 2012 21:08:36 +0000</lastBuildDate> <language>en</language> <sy:updatePeriod>hourly</sy:updatePeriod> <sy:updateFrequency>1</sy:updateFrequency> <generator>http://wordpress.org/?v=3.3.2</generator> <item><title>Three Strikes And You Refactor</title><link>http://davybrion.com/blog/2012/05/three-strikes-and-you-refactor/</link> <comments>http://davybrion.com/blog/2012/05/three-strikes-and-you-refactor/#comments</comments> <pubDate>Sun, 06 May 2012 14:36:10 +0000</pubDate> <dc:creator>Davy Brion</dc:creator> <category><![CDATA[Code Quality]]></category><guid
isPermaLink="false">http://davybrion.com/blog/?p=3966</guid> <description><![CDATA[The first time you do something, you just do it. The second time you do something similar, you wince at the duplication, but you do the duplicate thing anyway. The third time you do something similar, you refactor. That's a quote from Don Roberts, found in Martin Fowler's Refactoring book (page 58). That quote didn't [...]]]></description> <content:encoded><![CDATA[<blockquote><p>The first time you do something, you just do it. The second time you do something similar, you wince at the duplication, but you do the duplicate thing anyway. The third time you do something similar, you refactor.</p></blockquote><p>That's a quote from Don Roberts, found in Martin Fowler's Refactoring book (page 58). That quote didn't really make me think twice at the time I read it, but it got stuck in my head later on when I heard it from someone who's always been very influential to me. When this person told me that this was one of his favorite rules, I was still in my "no way dude, all code needs to be as clean as it can be" phase. But it's really grown on me over the last few years. Now, just to avoid any confusion: this post is about <em>my interpretation</em> of 'Three Strikes And You Refactor', not about what may have been originally intended or what some people think of it now.</p><p>The most important thing I remember when learning about TDD was:</p><ol><li><p>Write a failing test</p></li><li><p>Do the simplest thing that could possibly work to make the test pass.</p></li><li><p>Refactor.</p></li></ol><p>With all the literature that's out there, as well as popular opinion on how important clean code is, it's tempting to go overboard with that 'refactor' step. It's tempting to go for the solution that is crispy clean. The solution that'll have your coworkers or peers go "ohhh, now <em>that</em> is nice". However, you really need to ask yourself the following question: "is it really worth it?". Wanting to make sure that every piece of code is perfect takes up a lot of time, and I've learned that it certainly isn't always worth it. Besides, it's quite easy to go off on a path of introducing new concepts and abstractions to your code that end up being totally unnecessary. If this increases complexity in parts that don't really matter, it ends up being a huge waste. Not only for the person who wrote it, but for every person who has to read it and comprehend it later on.</p><p>'Three Strikes And You Refactor' is a helpful rule of thumb here. Try to keep things as simple as possible and don't be afraid of a <em>little</em> duplication here or there. Once you find yourself (or a teammate) doing the same thing for a third time, it's worth cleaning up because that third time very often means that it wouldn't be the last time either. This way, you only introduce concepts and abstractions that are really needed, and enables you to avoid adding unnecessary cruft to the code.</p><div
class="bottomcontainerBox" style=""><div
style="float:left; width:85px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;"> <iframe
src="http://www.facebook.com/plugins/like.php?href=http%3A%2F%2Fdavybrion.com%2Fblog%2F2012%2F05%2Fthree-strikes-and-you-refactor%2F&amp;layout=button_count&amp;show_faces=false&amp;width=85&amp;action=like&amp;font=verdana&amp;colorscheme=light&amp;height=21" scrolling="no" frameborder="0" allowTransparency="true" style="border:none; overflow:hidden; width:85px; height:21px;"></iframe></div><div
style="float:left; width:80px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;"> <g:plusone size="medium" href="http://davybrion.com/blog/2012/05/three-strikes-and-you-refactor/"></g:plusone></div><div
style="float:left; width:95px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;"> <a
href="http://twitter.com/share" class="twitter-share-button" data-url="http://davybrion.com/blog/2012/05/three-strikes-and-you-refactor/"  data-text="Three Strikes And You Refactor" data-count="horizontal" data-via="davybrion"></a></div><div
style="float:left; width:105px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;"><script type="in/share" data-url="http://davybrion.com/blog/2012/05/three-strikes-and-you-refactor/" data-counter="right"></script></div><div
style="float:left; width:85px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;"><script src="http://www.stumbleupon.com/hostedbadge.php?s=1&amp;r=http://davybrion.com/blog/2012/05/three-strikes-and-you-refactor/"></script></div></div><div
style="clear:both"></div><div
style="padding-bottom:4px;"></div>]]></content:encoded> <wfw:commentRss>http://davybrion.com/blog/2012/05/three-strikes-and-you-refactor/feed/</wfw:commentRss> <slash:comments>8</slash:comments> </item> <item><title>What&#8217;s The Point Of Using WCF In A Web App?</title><link>http://davybrion.com/blog/2012/03/whats-the-point-of-using-wcf-in-a-web-app/</link> <comments>http://davybrion.com/blog/2012/03/whats-the-point-of-using-wcf-in-a-web-app/#comments</comments> <pubDate>Sun, 18 Mar 2012 16:28:28 +0000</pubDate> <dc:creator>Davy Brion</dc:creator> <category><![CDATA[Architecture]]></category> <category><![CDATA[Code Quality]]></category> <category><![CDATA[Performance]]></category> <category><![CDATA[WCF]]></category><guid
isPermaLink="false">http://davybrion.com/blog/?p=3938</guid> <description><![CDATA[A very common approach of building web applications in .NET is to put most of the non-UI related code behind an internal WCF service layer. I used to be a fan of this approach as well, but these days I just don't see the benefit of that internal service layer anymore. The overhead that an [...]]]></description> <content:encoded><![CDATA[<p>A very common approach of building web applications in .NET is to put most of the non-UI related code behind an internal WCF service layer. I used to be a fan of this approach as well, but these days I just don't see the benefit of that internal service layer anymore. The overhead that an internal WCF service layer adds to development, deployment and runtime performance just doesn't stack up favorably to the supposed benefits IMO. To be clear: I'm talking about WCF services that will <em>only</em> be used by the front end of your web application.</p><p>Let's talk about the overhead on development first. If you're using WCF services in your web app, you need proxies to access those services. Some people prefer to generate the proxies based on the WSDL of the services that will be used. In the worst case, this leads to regenerating proxies and all of the types that are defined in the WSDL every time you change a service contract or one of the types that are used by the services. If multiple people need to make changes to any of these concurrently, this easily leads to merging problems when people need to commit their changes. Another way is to share the same types on both sides (client &amp; server), and implement your service proxies by inheriting from ClientBase and manually keeping the implementation of the proxies up to date with the definitions of their service contracts. This is better than regenerating a bunch of code all the time, but you're still writing a lot of redirection code for the purpose of, well, what exactly? Another possibility is to use dynamic proxies which automatically implement the service contracts but this increases the amount of infrastructure code you need to put in place and it's not always clear to everyone how exactly communication with the services happens. There's also a lot of WCF configuration for each service that you need to maintain, and it can quickly grow unwieldy.</p><p>Then there's the overhead on performance. I hope we can all agree that any operation that goes out of process is at least an order of magnitude slower than a similar operation that can be executed in process. First of all, there's the networking overhead (even if your services are hosted on the same machine as the web app) that you have to keep into account. Secondly, there is the cost of serializing and deserializing <em>everything</em> that is transferred between the client and the server. Even with the most efficient bindings and serializers, the cost of all of this quickly adds up on high-traffic web apps. That's not to say that WCF services are inherently slow. They can be very fast and efficient, but they'll never be as fast and efficient as executing that logic in process within the web app.</p><p>Finally, there's the extra overhead it introduces to the deployment phase:</p><ul><li>more endpoints to set up and transfer artifacts to</li><li>more configuration</li><li>more monitoring of endpoints</li><li>more servers if you're not hosting the services and the web app on the same machine</li></ul><p>Of course, people will argue that there a plenty of benefits to using a WCF service layer in a web app. The ones I hear about most often are the forced separation of business logic and UI logic and improved scalability and reliability. I really disagree that you need a physical separation of business and UI logic. I much prefer approaches where the separation is based on abstractions. A good example was recently posted by Ayende (<a
href="http://ayende.com/blog/154241/limit-your-abstractions-the-key-is-in-the-infrastructurehellip">here</a> and <a
href="http://ayende.com/blog/154273/limit-your-abstractions-and-how-do-you-handle-testing">here</a>). And when it comes to scalability/reliability, a web app that isn't dependent on a WCF service layer is as easy (or even easier depending on your setup) to scale than one that is entirely dependent on WCF services. First of all, if you care about scalability/reliability your web app should already be prepared to run behind a load balancer. If you already have a load balancer in place, you can just add more web servers to your setup when needed. If you'd host the WCF services on the same machines that are hosting the web front end, you'd get less total throughput from one server than you would if that one server could just host a web app that fully executes in process (not including the database obviously). If you're hosting the WCF services on separate machines, you'd end up with more servers to handle the load and to achieve the reliability you need than you would with just being able to add more web servers to your setup. That also increases your licensing costs. And of course, it also means increased networking overhead on every service call, which also implies that the threads on your web servers will be blocked for longer periods while they wait for those service calls to return. Unless you're calling those services asynchronously, but most people simply don't. Also, if you have serious scalability and reliability requirements you're probably better off with asynchronous messaging solutions than with SOAP services.</p><p>WCF has its benefits (though I prefer Web API's or asynchronous messaging over SOAP services these days) and it has its use cases. I just don't think internal service layers for web apps is one of them.</p><p>What are the benefits that you think an internal WCF service layer brings to your web app? And what's your opinion on how they stack up versus the downsides?</p><div
class="bottomcontainerBox" style=""><div
style="float:left; width:85px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;"> <iframe
src="http://www.facebook.com/plugins/like.php?href=http%3A%2F%2Fdavybrion.com%2Fblog%2F2012%2F03%2Fwhats-the-point-of-using-wcf-in-a-web-app%2F&amp;layout=button_count&amp;show_faces=false&amp;width=85&amp;action=like&amp;font=verdana&amp;colorscheme=light&amp;height=21" scrolling="no" frameborder="0" allowTransparency="true" style="border:none; overflow:hidden; width:85px; height:21px;"></iframe></div><div
style="float:left; width:80px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;"> <g:plusone size="medium" href="http://davybrion.com/blog/2012/03/whats-the-point-of-using-wcf-in-a-web-app/"></g:plusone></div><div
style="float:left; width:95px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;"> <a
href="http://twitter.com/share" class="twitter-share-button" data-url="http://davybrion.com/blog/2012/03/whats-the-point-of-using-wcf-in-a-web-app/"  data-text="What&#8217;s The Point Of Using WCF In A Web App?" data-count="horizontal" data-via="davybrion"></a></div><div
style="float:left; width:105px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;"><script type="in/share" data-url="http://davybrion.com/blog/2012/03/whats-the-point-of-using-wcf-in-a-web-app/" data-counter="right"></script></div><div
style="float:left; width:85px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;"><script src="http://www.stumbleupon.com/hostedbadge.php?s=1&amp;r=http://davybrion.com/blog/2012/03/whats-the-point-of-using-wcf-in-a-web-app/"></script></div></div><div
style="clear:both"></div><div
style="padding-bottom:4px;"></div>]]></content:encoded> <wfw:commentRss>http://davybrion.com/blog/2012/03/whats-the-point-of-using-wcf-in-a-web-app/feed/</wfw:commentRss> <slash:comments>38</slash:comments> </item> <item><title>DTO&#8217;s Should Transfer Data, Not Entities</title><link>http://davybrion.com/blog/2012/02/dtos-should-transfer-data-not-entities/</link> <comments>http://davybrion.com/blog/2012/02/dtos-should-transfer-data-not-entities/#comments</comments> <pubDate>Sun, 19 Feb 2012 19:32:17 +0000</pubDate> <dc:creator>Davy Brion</dc:creator> <category><![CDATA[Architecture]]></category> <category><![CDATA[Code Quality]]></category><guid
isPermaLink="false">http://davybrion.com/blog/?p=3907</guid> <description><![CDATA[I've read a couple of posts recently where the authors were complaining about excessive mapping to DTO's and whether or not it's worth it. I've been a fan of DTO's for a long time, but I'm not a fan of how I frequently see them being used. More specifically, I very much dislike the all-too-common [...]]]></description> <content:encoded><![CDATA[<p>I've read a couple of posts recently where the authors were complaining about excessive mapping to DTO's and whether or not it's worth it. I've been a fan of DTO's for a long time, but I'm not a fan of how I frequently see them being used. More specifically, I very much dislike the all-too-common approach of creating a DTO for each entity in your domain model. In the worst cases, the DTO's actually reference each other and try too hard to mimic the structure of the entities. For example, an OrderDto which has a reference to a CustomerDto and a collection of OrderLineDto instances. In those cases, I absolutely agree that all of the mapping involved introduces way too much ceremony to the codebase without really offering any concrete benefits.</p><p>Of course, it really depends on the architecture of your system.  If you're using services that are only used by the front-end of your system, then I'd still advise against making those entities available outside of the service boundary for reasons that I've discussed <a
href="http://davybrion.com/blog/2010/05/why-you-shouldnt-expose-your-entities-through-your-services/">earlier</a>. That doesn't mean that you should go the entity-mimicking-DTO-route though. In fact, entity-mimicking-DTO's introduce a few of the same downsides you'd get from exposing entities directly through  your services. For an 'internal' service (i.e. only used by <em>your</em> application), I think it makes a lot more sense to use DTO's per service operation which are optimized for the use case that that service operation is meant to implement.</p><p>Essentially, an internal service's operations will be either <em>queries</em> or <em>commands</em>. When it comes to queries, why not just do the simplest thing possible? In most cases, it's sufficient to just return the data in the exact same form that the data will be displayed in. Quite often, that means a denormalized set of data where the data comes from more than one type of entity/table. There's no reason to send a bunch of entity-mimicking DTO's that reference each other to the client if you're going to use the data to populate a grid. Just send a list of DTO's which are already in the most optimal form. Populating those DTO's can then simply be done through straight SQL, a view, a stored procedure, a <a
href="http://davybrion.com/blog/2010/09/think-twice-before-you-map-entities-to-dtos/">projection through your ORM</a>, a map/reduce operation, or whatever else that makes sense. The point is that in most cases, you should just <em>populate</em> those DTO's as directly as you can instead of <em>mapping</em> to those DTO's. In this case, the DTO's offer a clear-cut benefit and don't really introduce tedious ceremony code in your codebase.</p><p>As for the commands (inserts, updates, anything that <em>creates</em> something or results in something <em>happening</em>), why even use DTO's in the first place? People will often argue that the ability to reuse the entity-mimicking-DTO's for these operations is a benefit. Personally, I don't really see the benefit. The mere presence of entity-mimicking-DTO's only encourages people to use them for the queries as well. Instead, I prefer to go with types that encapsulate all of the data relevant to the current command (the data to be inserted/updated, or whatever else the command needs). In a very simple scenario, this could be an InsertCustomerCommand type which simply has properties for the data that needs to be inserted. Nobody will be confusing these types with any other purpose than what their name communicates.</p><p>If you're building a web app where the server-side code does everything in process (i.e. without a WCF service), then you can in many cases just use the entities directly without a real drawback, though I'd recommend keeping an eye on unexpected select N+1 problems, since those will frequently come up when you're preparing your views. But even in this case, using DTO's that are optimized for the scenarios in which they're being used can really simplify the query-side of your system a lot.</p><p>There's nothing inherently wrong with DTO's if you use them to simply transfer <em>data</em>. If you're using them to transfer entities, you're robbing yourself of their biggest benefit while only making things more complex than they need to be.</p><div
class="bottomcontainerBox" style=""><div
style="float:left; width:85px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;"> <iframe
src="http://www.facebook.com/plugins/like.php?href=http%3A%2F%2Fdavybrion.com%2Fblog%2F2012%2F02%2Fdtos-should-transfer-data-not-entities%2F&amp;layout=button_count&amp;show_faces=false&amp;width=85&amp;action=like&amp;font=verdana&amp;colorscheme=light&amp;height=21" scrolling="no" frameborder="0" allowTransparency="true" style="border:none; overflow:hidden; width:85px; height:21px;"></iframe></div><div
style="float:left; width:80px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;"> <g:plusone size="medium" href="http://davybrion.com/blog/2012/02/dtos-should-transfer-data-not-entities/"></g:plusone></div><div
style="float:left; width:95px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;"> <a
href="http://twitter.com/share" class="twitter-share-button" data-url="http://davybrion.com/blog/2012/02/dtos-should-transfer-data-not-entities/"  data-text="DTO&#8217;s Should Transfer Data, Not Entities" data-count="horizontal" data-via="davybrion"></a></div><div
style="float:left; width:105px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;"><script type="in/share" data-url="http://davybrion.com/blog/2012/02/dtos-should-transfer-data-not-entities/" data-counter="right"></script></div><div
style="float:left; width:85px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;"><script src="http://www.stumbleupon.com/hostedbadge.php?s=1&amp;r=http://davybrion.com/blog/2012/02/dtos-should-transfer-data-not-entities/"></script></div></div><div
style="clear:both"></div><div
style="padding-bottom:4px;"></div>]]></content:encoded> <wfw:commentRss>http://davybrion.com/blog/2012/02/dtos-should-transfer-data-not-entities/feed/</wfw:commentRss> <slash:comments>10</slash:comments> </item> <item><title>The Non-Typical .NET Job</title><link>http://davybrion.com/blog/2011/10/the-non-typical-net-job/</link> <comments>http://davybrion.com/blog/2011/10/the-non-typical-net-job/#comments</comments> <pubDate>Sun, 23 Oct 2011 22:00:33 +0000</pubDate> <dc:creator>Davy Brion</dc:creator> <category><![CDATA[ALT.NET]]></category> <category><![CDATA[Code Quality]]></category> <category><![CDATA[Opinions]]></category> <category><![CDATA[Patterns]]></category> <category><![CDATA[Software Development]]></category> <category><![CDATA[work/career]]></category><guid
isPermaLink="false">http://davybrion.com/blog/2011/10/the-non-typical-net-job/</guid> <description><![CDATA[I recently referred to an interesting .NET job as a 'non-typical .NET job'. I hadn't used that term yet up until that point, so I thought that was rather interesting. But what exactly do I mean with 'non-typical .NET job'? It's pretty simple really: a job where you're using .NET technology without blindly following the [...]]]></description> <content:encoded><![CDATA[<p>I recently referred to an interesting .NET job as a 'non-typical .NET job'. I hadn't used that term yet up until that point, so I thought that was rather interesting. But what exactly do I mean with 'non-typical .NET job'? It's pretty simple really: a job where you're using .NET technology without blindly following the guidelines, recommendations and software from Microsoft on how to develop software on the .NET platform. It basically means that you'll use <em>whatever</em> you think is most appropriate for what you're trying to do.</p><p>The biggest problem in the .NET world is that most companies that do .NET development just stick to what Microsoft tells them to use and how to use it. Many .NET developers largely focus on that, because they know all too well that it increases their odds of getting hired. And let's face it: Microsoft has a solution for practically everything. The only problem is that those solutions are rarely the best in what they're trying to solve. But hey, no manager gets fired for going with Microsoft, right?</p><p>The result is that there are too many companies and too many developers that focus only on what Microsoft offers. But there's a lot more to software development than what Microsoft offers, or even knows about. There are countless examples of Microsoft being late to whatever technical party is interesting at the time. And when they show up, they certainly don't always make a good impression.</p><p>If you're the kind of developer that likes to learn from what other software development communities are doing, odds are high that you're screwed. There is an interesting OSS community within the .NET world, and they frequently produce great solutions, quite often based on succes stories coming from other development communities. The problem is not that .NET developers don't have great solutions available to them. The problem is that the majority of them simply don't know about them only because there hasn't been any Microsoft hype about it, or that the devs who do know about it aren't allowed to use it because their managers are sceptical about it, most likely also because there's no Microsoft backing for the technology or architectural style that is being proposed.</p><p>I'm not advocating the avoidance of Microsoft products or solutions. By all means, use Microsoft products if they are indeed the best solution to your problem. But do be aware of the things that are getting attention outside of the Microsoft sphere and use them when it makes more sense to use them. That's the essence of the 'non-typical .NET job' and that's exactly what makes it interesting: using the right tool for the right job.</p><div
class="bottomcontainerBox" style=""><div
style="float:left; width:85px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;"> <iframe
src="http://www.facebook.com/plugins/like.php?href=http%3A%2F%2Fdavybrion.com%2Fblog%2F2011%2F10%2Fthe-non-typical-net-job%2F&amp;layout=button_count&amp;show_faces=false&amp;width=85&amp;action=like&amp;font=verdana&amp;colorscheme=light&amp;height=21" scrolling="no" frameborder="0" allowTransparency="true" style="border:none; overflow:hidden; width:85px; height:21px;"></iframe></div><div
style="float:left; width:80px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;"> <g:plusone size="medium" href="http://davybrion.com/blog/2011/10/the-non-typical-net-job/"></g:plusone></div><div
style="float:left; width:95px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;"> <a
href="http://twitter.com/share" class="twitter-share-button" data-url="http://davybrion.com/blog/2011/10/the-non-typical-net-job/"  data-text="The Non-Typical .NET Job" data-count="horizontal" data-via="davybrion"></a></div><div
style="float:left; width:105px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;"><script type="in/share" data-url="http://davybrion.com/blog/2011/10/the-non-typical-net-job/" data-counter="right"></script></div><div
style="float:left; width:85px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;"><script src="http://www.stumbleupon.com/hostedbadge.php?s=1&amp;r=http://davybrion.com/blog/2011/10/the-non-typical-net-job/"></script></div></div><div
style="clear:both"></div><div
style="padding-bottom:4px;"></div>]]></content:encoded> <wfw:commentRss>http://davybrion.com/blog/2011/10/the-non-typical-net-job/feed/</wfw:commentRss> <slash:comments>19</slash:comments> </item> <item><title>The Worst Code I Ever Wrote, And Why I&#8217;m Still Happy About It</title><link>http://davybrion.com/blog/2011/09/the-worst-code-i-ever-wrote-and-why-im-still-happy-about-it/</link> <comments>http://davybrion.com/blog/2011/09/the-worst-code-i-ever-wrote-and-why-im-still-happy-about-it/#comments</comments> <pubDate>Sun, 18 Sep 2011 12:03:54 +0000</pubDate> <dc:creator>Davy Brion</dc:creator> <category><![CDATA[Code Quality]]></category> <category><![CDATA[Software Development]]></category><guid
isPermaLink="false">http://davybrion.com/blog/2011/09/the-worst-code-i-ever-wrote-and-why-im-still-happy-about-it/</guid> <description><![CDATA[My last 2 years in high school, I was lucky enough to have 13 hours of programming-related classes every week. Those classes covered a few languages, but the most of it was spent on C/C++ (and nothing advanced either… mostly basic stuff) and Visual Basic. We thought we learned a lot, and I guess from [...]]]></description> <content:encoded><![CDATA[<p>My last 2 years in high school, I was lucky enough to have 13 hours of programming-related classes every week. Those classes covered a few languages, but the most of it was spent on C/C++ (and nothing advanced either… mostly basic stuff) and Visual Basic. We thought we learned a lot, and I guess from a purely syntactical point of view that may have indeed been true. But we didn't really learn a lot about the differences between good code and bad code.</p><p>We mostly cared about getting our assignments working. When you completed an assignment, you moved on to the next one and none of the code of the previous assignment really mattered anymore. Maintainability or even readability were things that never even occurred to us. Maybe a few of the teachers tried to tell us about it at some point, but it certainly didn't stick.</p><p>In the final year, we could pick a project to work on for the majority of the year. There were no limits on the assignment, so most people picked something that interested them. I was pretty interested in manager/simulation games, so I figured I'd just build my own Formula 1 manager game. The player would get full control over a F1 team, which in my game meant:</p><ul><li>picking the suppliers for tires, fuel and engines, all of which had varying levels of quality and costs associated with it</li><li>hiring a chief-designer, chief-mechanic and drivers, all of which had a specified talent level and negotiations took the results of the team's previous year into account, as well as the results of the potential hire's previous team, which influenced prices and negotiation tactics.</li><li>landing sponsors, some of which were more than happy to sponsor your team depending on last year's results, or wouldn't even answer your calls and they all had varying budgets as well</li></ul><p>I came up with a pretty good formula to simulate realistic race results based on all these factors as well as a dose of luck, or bad luck. If you played for a few seasons, the decisions you made all added up nicely, and gradually. When the project was due, it all worked. Since I loved playing those kind of games, I tested it very extensively by playing it regularly. When issues came up, I'd fix them. When I thought of improvements, I implemented them. I delivered something that worked, and that was large enough in scope and complexity to be impressive for a school project.</p><p>But the codebase was truly atrocious. I wasn't using proper structures for either data or behavior and I ended up with a shitload of extensive multi-dimensional arrays. All of my types were in those arrays, as I just didn't know yet that they should've been types of their own. Of course, I listed all of the indices on pieces of paper so I'd know which data properties corresponded with each index. Behavior was all implemented in the UI layer. I was using VB5 at the time, which didn't really encourage me to seek out nicer ways to structure my code. I copy/pasted large gobs of code whenever I needed to reuse something. And of course, whenever I had to make a change, I needed to do it in multiple places. Quite a few places in most cases even. I was using flat files to store data, so I didn't have the opportunity to make a horrendous mess out of a SQL-based data layer but if I had used a database, my usage of it would've surely been epic.</p><p>I got a very good grade for the project, and while I was happy to see that all of my hard work was rewarded, it did kinda scare me that a codebase that was so brittle and so painful could actually work, and work well even. It was my first encounter with what is by far the biggest problem with software development to this day: <em>if you keep adding code, sooner or later it might actually work</em>. Luckily, this was just a school project. But can you imagine if this were a project done by a professional company? That codebase would've cost money to develop, and the company would actually have a working project, no matter how expensive it would've been to keep working on it. At the time, I couldn't imagine a company in such a situation that would say: "ah, it sucks… we need to start over". And I think we all know that very few companies would actually do that.</p><p>I love that horrendous codebase for the lessons it taught me so early on. I learned a lot about what you shouldn't do when you're developing something that's supposed to stick around for a while, and I'm glad I learned it without it costing a lot of money. Of course, that doesn't mean that every single thing I've written since is all roses and peaches, but it put me on the path of trying to continuously improve as a developer, not only in what I was able to do with code, but also as to how clear I could make it to others.</p><p>Note: I no longer have that codebase unfortunately. Really wish I did, if only because it'd be pretty funny going through it after all these years.</p><div
class="bottomcontainerBox" style=""><div
style="float:left; width:85px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;"> <iframe
src="http://www.facebook.com/plugins/like.php?href=http%3A%2F%2Fdavybrion.com%2Fblog%2F2011%2F09%2Fthe-worst-code-i-ever-wrote-and-why-im-still-happy-about-it%2F&amp;layout=button_count&amp;show_faces=false&amp;width=85&amp;action=like&amp;font=verdana&amp;colorscheme=light&amp;height=21" scrolling="no" frameborder="0" allowTransparency="true" style="border:none; overflow:hidden; width:85px; height:21px;"></iframe></div><div
style="float:left; width:80px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;"> <g:plusone size="medium" href="http://davybrion.com/blog/2011/09/the-worst-code-i-ever-wrote-and-why-im-still-happy-about-it/"></g:plusone></div><div
style="float:left; width:95px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;"> <a
href="http://twitter.com/share" class="twitter-share-button" data-url="http://davybrion.com/blog/2011/09/the-worst-code-i-ever-wrote-and-why-im-still-happy-about-it/"  data-text="The Worst Code I Ever Wrote, And Why I&#8217;m Still Happy About It" data-count="horizontal" data-via="davybrion"></a></div><div
style="float:left; width:105px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;"><script type="in/share" data-url="http://davybrion.com/blog/2011/09/the-worst-code-i-ever-wrote-and-why-im-still-happy-about-it/" data-counter="right"></script></div><div
style="float:left; width:85px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;"><script src="http://www.stumbleupon.com/hostedbadge.php?s=1&amp;r=http://davybrion.com/blog/2011/09/the-worst-code-i-ever-wrote-and-why-im-still-happy-about-it/"></script></div></div><div
style="clear:both"></div><div
style="padding-bottom:4px;"></div>]]></content:encoded> <wfw:commentRss>http://davybrion.com/blog/2011/09/the-worst-code-i-ever-wrote-and-why-im-still-happy-about-it/feed/</wfw:commentRss> <slash:comments>11</slash:comments> </item> <item><title>Take Advantage Of Your BDD Framework</title><link>http://davybrion.com/blog/2011/08/take-advantage-of-your-bdd-framework/</link> <comments>http://davybrion.com/blog/2011/08/take-advantage-of-your-bdd-framework/#comments</comments> <pubDate>Wed, 03 Aug 2011 18:46:23 +0000</pubDate> <dc:creator>Davy Brion</dc:creator> <category><![CDATA[Code Quality]]></category> <category><![CDATA[testing]]></category><guid
isPermaLink="false">http://davybrion.com/blog/?p=3464</guid> <description><![CDATA[NOTE: the examples in this post use JavaScript and Jasmine, but the advice is applicable to whatever BDD framework you use. I'm using Jasmine for the automated tests in my breakable toy project. It's a BDD framework, very similar to RSpec so it makes it really easy to write your tests in the given-when-then style [...]]]></description> <content:encoded><![CDATA[<p>NOTE: the examples in this post use JavaScript and Jasmine, but the advice is applicable to whatever BDD framework you use.</p><p>I'm using <a
href="http://pivotal.github.com/jasmine/">Jasmine</a> for the automated tests in my breakable toy project. It's a BDD framework, very similar to RSpec so it makes it really easy to write your tests in the given-when-then style which i'm (finally) starting to like more and more. What makes given-when-then testing interesting is that you have 3 explicit steps in a test: setting up the 'given' part, doing something in the 'when' part, and asserting on it in the 'then' part. It makes it especially easy to reuse the 'givens' and even the 'whens' if you just want to add a few 'thens'.</p><p>Let's first start off with a bad example, one that i wrote about 2 weeks ago:</p><div><pre class="brush: jscript; title: ; notranslate">
describe('given an existing customer', function() {

    describe('when it is retrieved from the database', function() {

        it('should contain the same values that have been inserted', function() {
            var customer = new CustomerBuilder()
                .withIncludeContactOnInvoice()
                .build();

            customer.save(function(err) {
                Customer.findById(customer.id, function(err, result) {
                    helper.customersShouldBeEqual(result, customer);                    
                    asyncSpecDone();
                });
            });
            asyncSpecWait();
        });

    });

});
</pre></div><p>It's organized in a given-when-then style, but in a bad way. The only benefit that i'm getting from it here, is that the structure is sort of easy to read: given an existing customer, when it is retrieved from the database, it should contain the same values that have been inserted. When i wrote it, i knew that saving the customer should be done in the 'given' step, retrieving it should be done in the 'when' step and comparing the fields of the inserted customer and the retrieved customer should be done in the 'then' step. In this case, everything is being done in the 'then' step.</p><p>When i wrote that code, i figured it would just be easier to do it this way, because on Node.JS every I/O call is asynchronous and i thought it would hurt readability if i were to split everything up according to the given-when-then rules due to the asynchronous calls.  But then i wanted to add tests for updating and deleting a customer. In both cases, the 'given' part would again be 'given an existing customer'. So i wanted to add them in the right place, which meant i had to choose between duplicating the code to save the customer in each test, or bite the bullet and split it up properly and deal with the asynchronous calls.</p><p>Let's start with our original example, and move the saving of the customer to the 'given' step, and the retrieval to the 'when' step:</p><div><pre class="brush: jscript; title: ; notranslate">
describe('given an existing customer', function() {

    var customer = null;

    beforeEach(function(err) {
        customer = new CustomerBuilder()
            .withIncludeContactOnInvoice()
            .build();

        customer.save(function(err) {
            expect(err).toBeNull();
            asyncSpecDone();
        });
        asyncSpecWait();
    });

    describe('when it is retrieved from the database', function() {

        var retrievedCustomer = null;

        beforeEach(function() {
            Customer.findById(customer.id, function(err, result) {
                expect(err).toBeNull();
                retrievedCustomer = result;
                asyncSpecDone();
            });
            asyncSpecWait();
        });

        it('should contain the same values that have been inserted', function() {
            helper.customersShouldBeEqual(retrievedCustomer, customer);
        });

    });

});

</pre></div><p>Despite ending up with more lines of code, there are some notable improvements here. We take advantage of the beforeEach method, which is executed once before each spec (in the case of Jasmine, a call to the 'it' method is a spec) is executed and once before each spec in each nested suite (in the case of Jasmine, a call to the 'describe' method creates a new suite) is executed. Most BDD-frameworks have something similar. Obviously, due to the asynchronous nature of Node.JS we use the asyncSpecWait() and asyncSpecDone() calls (added to Jasmine by jasmine-node) to wait until the asynchronous calls have completed before we move to the next step. In production Node.JS code, you really don't want to do this since that completely takes away the benefits of the platform, but for automated tests, it makes sense to do so. This enables us to put the right code in the right place: saving the customer is done in the 'given' step, retrieving it is done in the 'when' step, and the 'then' step only contains the code to verify that both instances are equal. If we need to verify something else about retrieved customers, we could easily add more specs (calls to the 'it' method) without having to repeat any of the setup work.</p><p>Now we can also add the tests for the update and delete scenario, within the context of the 'given an existing customer' scenario.</p><div><pre class="brush: jscript; title: ; notranslate">
describe('given an existing customer', function() {

    var customer = null;

    beforeEach(function(err) {
        customer = new CustomerBuilder()
            .withIncludeContactOnInvoice()
            .build();
            
        customer.save(function(err) {
            expect(err).toBeNull();
            asyncSpecDone();
        });
        asyncSpecWait();
    });

    describe('when it is retrieved from the database', function() {

        var retrievedCustomer = null;

        beforeEach(function() {
            Customer.findById(customer.id, function(err, result) {
                expect(err).toBeNull();
                retrievedCustomer = result;
                asyncSpecDone();
            });
            asyncSpecWait();
        });
    
        it('should contain the same values that have been inserted', function() {
            helper.customersShouldBeEqual(retrievedCustomer, customer);
        });
        
    });
    
    describe('when it is modified and updated', function() {
            
        beforeEach(function() { 
            customer.name = 'some other customer';
            customer.vatNumber = '0456.876.235';
            customer.address = {
                street: 'some other street',
                postalCode: '12345',
                city: 'some other city'
            };
            customer.phoneNumber = '123456789';
            customer.contact = {
                name: 'some name',
                email: 'some_email@hotmail.com'
            };
            customer.save(function(err) {
                expect(err).toBeNull();
                asyncSpecDone();
            });
            asyncSpecWait();
        });

        it('contains the updated values in the database', function() {
            Customer.findById(customer.id, function(err, result) {
                helper.customersShouldBeEqual(result, customer);
                asyncSpecDone();
            });
            asyncSpecWait();
        });

    });

    describe('when it is deleted', function() {
        
        beforeEach(function() {
            customer.remove(function(err) {
                expect(err).toBeNull();
                asyncSpecDone();
            });
            asyncSpecWait();
        });     

        it('can no longer be retrieved', function() {
            Customer.findById(customer.id, function(err, result) {
                expect(result).toBeNull();
                asyncSpecDone();
            });
            asyncSpecWait();
        });

    });
    
});
</pre></div><p>In this case, the only duplication we have are the calls to asyncSpecWait and asyncSpecDone, which can't really be avoided with this style of testing on the Node.JS platform. Other than that, each part of the code is focused solely on that what it needs to do. If you're using a BDD framework, be sure you leverage it to make sure each part of your testcode is as focused on its task as it can be.</p><div
class="bottomcontainerBox" style=""><div
style="float:left; width:85px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;"> <iframe
src="http://www.facebook.com/plugins/like.php?href=http%3A%2F%2Fdavybrion.com%2Fblog%2F2011%2F08%2Ftake-advantage-of-your-bdd-framework%2F&amp;layout=button_count&amp;show_faces=false&amp;width=85&amp;action=like&amp;font=verdana&amp;colorscheme=light&amp;height=21" scrolling="no" frameborder="0" allowTransparency="true" style="border:none; overflow:hidden; width:85px; height:21px;"></iframe></div><div
style="float:left; width:80px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;"> <g:plusone size="medium" href="http://davybrion.com/blog/2011/08/take-advantage-of-your-bdd-framework/"></g:plusone></div><div
style="float:left; width:95px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;"> <a
href="http://twitter.com/share" class="twitter-share-button" data-url="http://davybrion.com/blog/2011/08/take-advantage-of-your-bdd-framework/"  data-text="Take Advantage Of Your BDD Framework" data-count="horizontal" data-via="davybrion"></a></div><div
style="float:left; width:105px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;"><script type="in/share" data-url="http://davybrion.com/blog/2011/08/take-advantage-of-your-bdd-framework/" data-counter="right"></script></div><div
style="float:left; width:85px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;"><script src="http://www.stumbleupon.com/hostedbadge.php?s=1&amp;r=http://davybrion.com/blog/2011/08/take-advantage-of-your-bdd-framework/"></script></div></div><div
style="clear:both"></div><div
style="padding-bottom:4px;"></div>]]></content:encoded> <wfw:commentRss>http://davybrion.com/blog/2011/08/take-advantage-of-your-bdd-framework/feed/</wfw:commentRss> <slash:comments>10</slash:comments> </item> <item><title>Clean Code Versus Great Code</title><link>http://davybrion.com/blog/2011/07/clean-code-versus-great-code/</link> <comments>http://davybrion.com/blog/2011/07/clean-code-versus-great-code/#comments</comments> <pubDate>Thu, 21 Jul 2011 16:00:11 +0000</pubDate> <dc:creator>Davy Brion</dc:creator> <category><![CDATA[Code Quality]]></category> <category><![CDATA[Opinions]]></category><guid
isPermaLink="false">http://davybrion.com/blog/?p=3399</guid> <description><![CDATA[I've had some interesting discussions with other developers about writing code recently. I often have the impression that some developers put too much emphasis on clean code. Don't get me wrong, i strive for clean code as well, and have written about its importance quite a lot in the past couple of years. But when [...]]]></description> <content:encoded><![CDATA[<p>I've had some interesting discussions with other developers about writing code recently. I often have the impression that some developers put too much emphasis on clean code. Don't get me wrong, i strive for clean code as well, and have written about its importance quite a lot in the past couple of years. But when i'm coding, clean code is my secondary goal and it could never take the place of my primary goal: making it work. And preferably, i want to make it work <em>great</em>.</p><p>A lot of people love to talk the talk when it comes to writing clean code. They'll stress their dedication to it, in some cases even wearing Uncle Bob's <a
href="http://butunclebob.com/ArticleS.UncleBob.GreenWristBand" target="_blank">green band</a> while coding so they'll never lose sight of what's incredibly important to them: writing clean code. Unfortunately, i've noticed on numerous occasions that many of these people don't always put as much emphasis on <em>what the code is doing</em> compared to <em>how it looks</em>. Sometimes they don't really bother to learn what their ORM is doing behind the scenes. Or they'll prefer to use something like Automapper to map entities to DTO's even though it is woefully inefficient compared to simply retrieving projected data. They don't always think about the cost of multiple remote calls or sending way too much data over the wire. And when they're not perfecting the art of writing bowling games over and over again, they just might <a
href="http://davybrion.com/blog/2008/11/why-on-earth-would-a-developer-do-this/" target="_blank">hit the database in loop</a>.</p><p>Clean code is not necessarily great code, nor is great code necessarily clean code. To me, great code is code that works great, performs great, is easy to understand and easy to change. In that order. I know all too well how important it is to easily understand code when you first read it, and to be able to easily and safely make changes to it. But no matter how easy it is to read or change, if it's not doing what it should be doing (including covering all the corner cases) or if it's taking more than its fair share of time to do it, it's not good code. Sure, it might be clean, but it's not great, is it?</p><p>That doesn't mean that you should indulge in premature optimization. Unless you have Neo-like skills in this coding Matrix, you're unlikely to be right in even a quarter of all scenarios that you want to optimize prematurely. There are however a <a
href="http://davybrion.com/blog/2009/02/performance-rules-of-thumb/" target="_blank">few guidelines</a> which will help you avoid most common performance problems. Most other situations are better left ignored until proven by a profiler to be a bottleneck. But you should at least think about what the code is actually doing and whether or not any downsides to that are worth the cleanliness. Don't hesitate to go with the slightly less clean looking code if that code makes more sense from a correctness and performance point of view.</p><p>By all means, strive to write clean code. But think twice before you sacrifice its ability to be great.</p><div
class="bottomcontainerBox" style=""><div
style="float:left; width:85px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;"> <iframe
src="http://www.facebook.com/plugins/like.php?href=http%3A%2F%2Fdavybrion.com%2Fblog%2F2011%2F07%2Fclean-code-versus-great-code%2F&amp;layout=button_count&amp;show_faces=false&amp;width=85&amp;action=like&amp;font=verdana&amp;colorscheme=light&amp;height=21" scrolling="no" frameborder="0" allowTransparency="true" style="border:none; overflow:hidden; width:85px; height:21px;"></iframe></div><div
style="float:left; width:80px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;"> <g:plusone size="medium" href="http://davybrion.com/blog/2011/07/clean-code-versus-great-code/"></g:plusone></div><div
style="float:left; width:95px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;"> <a
href="http://twitter.com/share" class="twitter-share-button" data-url="http://davybrion.com/blog/2011/07/clean-code-versus-great-code/"  data-text="Clean Code Versus Great Code" data-count="horizontal" data-via="davybrion"></a></div><div
style="float:left; width:105px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;"><script type="in/share" data-url="http://davybrion.com/blog/2011/07/clean-code-versus-great-code/" data-counter="right"></script></div><div
style="float:left; width:85px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;"><script src="http://www.stumbleupon.com/hostedbadge.php?s=1&amp;r=http://davybrion.com/blog/2011/07/clean-code-versus-great-code/"></script></div></div><div
style="clear:both"></div><div
style="padding-bottom:4px;"></div>]]></content:encoded> <wfw:commentRss>http://davybrion.com/blog/2011/07/clean-code-versus-great-code/feed/</wfw:commentRss> <slash:comments>24</slash:comments> </item> <item><title>There&#8217;s Only One Valid Metric For Developer Productivity And Quality</title><link>http://davybrion.com/blog/2011/02/theres-only-one-valid-metric-for-developer-productivity-and-quality/</link> <comments>http://davybrion.com/blog/2011/02/theres-only-one-valid-metric-for-developer-productivity-and-quality/#comments</comments> <pubDate>Sat, 19 Feb 2011 17:37:19 +0000</pubDate> <dc:creator>Davy Brion</dc:creator> <category><![CDATA[Code Quality]]></category> <category><![CDATA[Opinions]]></category> <category><![CDATA[Software Development]]></category><guid
isPermaLink="false">http://davybrion.com/blog/?p=3086</guid> <description><![CDATA[Depending on who you ask, software developers have been programming for over 40 to 50 years. And we still have no truly objective way to measure a developer's productivity and quality level. People can think or say that a developer is fast or productive, but they can't truly quantify it. People can think or say [...]]]></description> <content:encoded><![CDATA[<p>Depending on who you ask, software developers have been programming for over 40 to 50 years.  And we still have no truly objective way to measure a developer's productivity and quality level.  People can think or say that a developer is fast or productive, but they can't truly quantify it. People can think or say that a developer is great, good or bad, but again, they can't truly quantify it with numbers.  We often look at other metrics to give us an idea on quality or productivity such as code metrics, or velocity but those numbers often reflect the efforts of a group of people.  After all, a codebase is more often the result of the efforts of more than one person, and a team's velocity is typically the result of the productivity of, well, a group of people.  Those numbers can't really be used to gain insight to the quality or productivity of a specific developer.</p><p>Not only is the current way of trying to determine the productivity or quality of a developer rather subjective, it's quite often based on things that are only one part of the equation: what they did, and the time in which they did it. I've always felt that that only really tells you half the story. I don't hold much value on knowing how long a developer took to write a certain piece of code or to complete a specific feature.  I also don't really care a lot about the code metrics for that piece of code or that specific feature.  All i know is that it took some effort.  The quality or productivity of that effort can't truly be measured without knowing how much extra effort will be introduced later on <em>because of</em> that effort.</p><p>Suppose you have 2 developers, John and Sally. You give them both the same task and you tell them that the estimated workload for that task is 12 hours.  John completes the task in 10 hours, and Sally needs 14 hours to complete it.  It would be easy to think that John is more productive than Sally based on this.  Especially if results like those were to repeat quite often.  But what if John's solution requires an extra 6 hours of effort down the line to fix some bugs, or because his code was such a mess to follow that it slowed down future tasks which required another developer to comprehend the code of John's task?  That would put John's eventual total to 16 hours of effort, instead of the originally reported 10 hours.  And what if Sally's solution didn't introduce any future effort whatsoever down the line?  Hell, maybe Sally's solution saved someone else an hour here or there because her solution was so easy to comprehend or perhaps even to reuse.  Her total for that task remains at 14 while at the same time maybe even reducing future numbers.  In this scenario, Sally is clearly a more productive and better programmer than John though we wouldn't know about it if we'd based ourselves on the initial numbers.</p><p>Consider another scenario though.  John again spends 10 hours on the same task, and Sally again spends 14 hours.  John kept it as simple and as straightforward as he could.  Hell, he actually took a shortcut or two to finish faster.  Sally is an outspoken member of the Software Craftsmanship movement and stays up to date with all of the latest and greatest patterns and approaches that are making their rounds on the internet.  Sally spent a little bit of extra effort to make sure the code is as great as it possibly can be.  It's incredibly readable and uses a great new pattern that all the cool kids on the internet rave about.  The code metrics clearly show that Sally's solution is of a much higher quality.  Unfortunately, it turns out that the other team members are having trouble understanding that code and they often lose time trying to figure it out whenever they need to do something which involves that part of the codebase.  While Sally may claim that she took more time because she did it 'better', the extra effort wasn't worth it because no matter how well her intentions with that code, it ended up costing other people time.  And what if John's shortcuts didn't introduce any future effort?</p><p>There are countless variations on this scenario which makes it virtually impossible to come up with a way to measure productivity or quality based on hours spent or code metrics. The only way to objectively measure this is to define a new metric which holds into account the extra effort that will be introduced later on. I'd call this metric Eventual Efficiency.  Quality or productivity by themselves don't really mean anything if one influences the other negatively.  Efficiency however can be seen as a combination of the two.  Did you write truly fantastic code which ended up not mattering at all? Not efficient.  Did you write mediocre code that got the job done and didn't (or hardly) introduced future effort? Sounds pretty efficient to me.  Did you write great code that reduced future effort? Very efficient!  Did you write bad code quickly that ended up introducing a lot of effort? Not efficient at all.</p><p>Unfortunately, we'll probably never get to the point where we can actually measure the Eventual Efficiency of developers.  Until we do, it's worth keeping in mind that whatever numbers we might be looking at don't really mean anything without the link to the related future effort.</p><div
class="bottomcontainerBox" style=""><div
style="float:left; width:85px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;"> <iframe
src="http://www.facebook.com/plugins/like.php?href=http%3A%2F%2Fdavybrion.com%2Fblog%2F2011%2F02%2Ftheres-only-one-valid-metric-for-developer-productivity-and-quality%2F&amp;layout=button_count&amp;show_faces=false&amp;width=85&amp;action=like&amp;font=verdana&amp;colorscheme=light&amp;height=21" scrolling="no" frameborder="0" allowTransparency="true" style="border:none; overflow:hidden; width:85px; height:21px;"></iframe></div><div
style="float:left; width:80px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;"> <g:plusone size="medium" href="http://davybrion.com/blog/2011/02/theres-only-one-valid-metric-for-developer-productivity-and-quality/"></g:plusone></div><div
style="float:left; width:95px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;"> <a
href="http://twitter.com/share" class="twitter-share-button" data-url="http://davybrion.com/blog/2011/02/theres-only-one-valid-metric-for-developer-productivity-and-quality/"  data-text="There&#8217;s Only One Valid Metric For Developer Productivity And Quality" data-count="horizontal" data-via="davybrion"></a></div><div
style="float:left; width:105px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;"><script type="in/share" data-url="http://davybrion.com/blog/2011/02/theres-only-one-valid-metric-for-developer-productivity-and-quality/" data-counter="right"></script></div><div
style="float:left; width:85px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;"><script src="http://www.stumbleupon.com/hostedbadge.php?s=1&amp;r=http://davybrion.com/blog/2011/02/theres-only-one-valid-metric-for-developer-productivity-and-quality/"></script></div></div><div
style="clear:both"></div><div
style="padding-bottom:4px;"></div>]]></content:encoded> <wfw:commentRss>http://davybrion.com/blog/2011/02/theres-only-one-valid-metric-for-developer-productivity-and-quality/feed/</wfw:commentRss> <slash:comments>17</slash:comments> </item> <item><title>What Do You Think Of This Hack?</title><link>http://davybrion.com/blog/2010/11/what-do-you-think-of-this-hack/</link> <comments>http://davybrion.com/blog/2010/11/what-do-you-think-of-this-hack/#comments</comments> <pubDate>Tue, 16 Nov 2010 14:37:58 +0000</pubDate> <dc:creator>Davy Brion</dc:creator> <category><![CDATA[C#]]></category> <category><![CDATA[Code Quality]]></category><guid
isPermaLink="false">http://davybrion.com/blog/?p=2906</guid> <description><![CDATA[I have a class which exposes a fluent interface to build something. Instances of this class contain some state based on the methods of the fluent interface you called and the arguments you passed to those methods. Now, that state is currently private but it's not private in the "oh my god we need to [...]]]></description> <content:encoded><![CDATA[<p>I have a class which exposes a fluent interface to build something. Instances of this class contain some state based on the methods of the fluent interface you called and the arguments you passed to those methods.  Now, that state is currently private but it's not private in the "oh my god we need to encapsulate this so nobody can read it!11!!!1" sense.  In fact, i actually <em>want</em> to access that state from another class.  The only 'problem' is that i don't want to add methods or properties to the class to expose this state, because it sort-of pollutes the fluent interface.  I know, that's not really a huge issue but still, it'd be nice to keep the fluent interface clean and focused.</p><p>One way to expose this state without polluting the fluent interface is to create a separate interface which defines the methods/properties and then have the class implement that interface explicitly. That way you could only access those methods/properties when you cast the instance to the interface type. While there's nothing really wrong with doing that, i kinda have a bad feeling about that because it introduces an interface which is only there to support this little exercise in Intellectual Masturbation.</p><p>Instead, i tried this:</p><div><pre class="brush: csharp; title: ; notranslate">
    public class MyClassWhichUsesAFluentInterface
    {
        private List&lt;string&gt; someState = new List&lt;string&gt;();

        public MyClassWhichUsesAFluentInterface SomethingFluent(string blah)
        {
            someState.Add(blah);
            return this;
        }

        // ...

        public static List&lt;string&gt; GetState(MyClassWhichUsesAFluentInterface constructedThingie)
        {
            return constructedThingie.someState;
        }
    }
</pre></div><p>Is it fancy? nope.
Is it cool? nope.
Does it work? yup.
Is it simple? yup.</p><p>Good enough for me.</p><div
class="bottomcontainerBox" style=""><div
style="float:left; width:85px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;"> <iframe
src="http://www.facebook.com/plugins/like.php?href=http%3A%2F%2Fdavybrion.com%2Fblog%2F2010%2F11%2Fwhat-do-you-think-of-this-hack%2F&amp;layout=button_count&amp;show_faces=false&amp;width=85&amp;action=like&amp;font=verdana&amp;colorscheme=light&amp;height=21" scrolling="no" frameborder="0" allowTransparency="true" style="border:none; overflow:hidden; width:85px; height:21px;"></iframe></div><div
style="float:left; width:80px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;"> <g:plusone size="medium" href="http://davybrion.com/blog/2010/11/what-do-you-think-of-this-hack/"></g:plusone></div><div
style="float:left; width:95px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;"> <a
href="http://twitter.com/share" class="twitter-share-button" data-url="http://davybrion.com/blog/2010/11/what-do-you-think-of-this-hack/"  data-text="What Do You Think Of This Hack?" data-count="horizontal" data-via="davybrion"></a></div><div
style="float:left; width:105px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;"><script type="in/share" data-url="http://davybrion.com/blog/2010/11/what-do-you-think-of-this-hack/" data-counter="right"></script></div><div
style="float:left; width:85px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;"><script src="http://www.stumbleupon.com/hostedbadge.php?s=1&amp;r=http://davybrion.com/blog/2010/11/what-do-you-think-of-this-hack/"></script></div></div><div
style="clear:both"></div><div
style="padding-bottom:4px;"></div>]]></content:encoded> <wfw:commentRss>http://davybrion.com/blog/2010/11/what-do-you-think-of-this-hack/feed/</wfw:commentRss> <slash:comments>14</slash:comments> </item> <item><title>The Truth Is In The Code! Unless It Isn&#8217;t&#8230;</title><link>http://davybrion.com/blog/2010/10/the-truth-is-in-the-code-unless-it-isnt/</link> <comments>http://davybrion.com/blog/2010/10/the-truth-is-in-the-code-unless-it-isnt/#comments</comments> <pubDate>Wed, 13 Oct 2010 06:00:12 +0000</pubDate> <dc:creator>Davy Brion</dc:creator> <category><![CDATA[Code Quality]]></category><guid
isPermaLink="false">http://davybrion.com/blog/?p=2388</guid> <description><![CDATA[I'm sure you've all heard phrases like "the truth is in the code" or "only the code is the truth" and stuff like that. These statements are typically used to make it clear that you can't just rely on documentation (which is very likely to be outdated anyway, if not downright incomplete) and that you [...]]]></description> <content:encoded><![CDATA[<p>I'm sure you've all heard phrases like "the truth is in the code" or "only the code is the truth" and stuff like that. These statements are typically used to make it clear that you can't just rely on documentation (which is very likely to be outdated anyway, if not downright incomplete) and that you need to look at the actual source code to know what a piece of software is doing in a certain situation.  And in most cases, the code is indeed the truth.  But i just wanted to share a little story from my past on this topic.</p><p>I was working at a client's office and one of their development policies/rules was to use stored procedures for <em>everything</em> you do with the database.  Every single CRUD operation and every single query had to be done through stored procedures.  During my time there, i was given the choice to either extend and 'refactor' (it was such a mess it would've been more like refracturing) an existing system, or to just rewrite it.  I chose the rewrite option but since there wasn't any documentation at all, i had to figure out the behavior of the system by going through the current source code... which was in a pretty bad shape (hence the decision to rewrite instead of going forward with that code).  But as bad as the code was, it was possible (though sometimes frustrating) to figure out what it was doing.</p><p>Except for one particular piece of code.  I don't remember the actual details but there was a certain situation where the system should've created a new record, but for some reason it didn't.  The code was (for once) very clear: it called a stored procedure to create a new record.  But at runtime, i could never get it to insert that record at the time it should've been created.  I actually spent about 2 hours debugging, going over the possibilities of why it wouldn't create that record even though the code was clearly telling me that it should've created a new record.</p><p>And then it hit me.  "What if the stored procedure is silently preventing this insert?".  Every single stored procedure that i had seen/reviewed from that system didn't contain any logic at all.  They were all very straightforward and didn't do anything but the actual database operation.  But for some reason, this insert stored procedure had a simple IF statement and it was silently ignoring a set of inserts based on a certain condition (the actual reason behind that IF statement was something i never figured out).  I felt like an idiot for wasting time on that without checking with the stored procedure first, but then again, i didn't really have any reason to suspect the stored procedure since they normally didn't contain any logic.</p><p>In this case, the code did <em>not</em> contain the truth and actually caused me to waste time believing something would be the case when it wasn't.  That just goes to show that as soon as an external system is involved which may contain additional logic which isn't immediately visible from the code, there is a small chance that the code is actually lying to you.</p><div
class="bottomcontainerBox" style=""><div
style="float:left; width:85px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;"> <iframe
src="http://www.facebook.com/plugins/like.php?href=http%3A%2F%2Fdavybrion.com%2Fblog%2F2010%2F10%2Fthe-truth-is-in-the-code-unless-it-isnt%2F&amp;layout=button_count&amp;show_faces=false&amp;width=85&amp;action=like&amp;font=verdana&amp;colorscheme=light&amp;height=21" scrolling="no" frameborder="0" allowTransparency="true" style="border:none; overflow:hidden; width:85px; height:21px;"></iframe></div><div
style="float:left; width:80px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;"> <g:plusone size="medium" href="http://davybrion.com/blog/2010/10/the-truth-is-in-the-code-unless-it-isnt/"></g:plusone></div><div
style="float:left; width:95px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;"> <a
href="http://twitter.com/share" class="twitter-share-button" data-url="http://davybrion.com/blog/2010/10/the-truth-is-in-the-code-unless-it-isnt/"  data-text="The Truth Is In The Code! Unless It Isn&#8217;t&#8230;" data-count="horizontal" data-via="davybrion"></a></div><div
style="float:left; width:105px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;"><script type="in/share" data-url="http://davybrion.com/blog/2010/10/the-truth-is-in-the-code-unless-it-isnt/" data-counter="right"></script></div><div
style="float:left; width:85px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;"><script src="http://www.stumbleupon.com/hostedbadge.php?s=1&amp;r=http://davybrion.com/blog/2010/10/the-truth-is-in-the-code-unless-it-isnt/"></script></div></div><div
style="clear:both"></div><div
style="padding-bottom:4px;"></div>]]></content:encoded> <wfw:commentRss>http://davybrion.com/blog/2010/10/the-truth-is-in-the-code-unless-it-isnt/feed/</wfw:commentRss> <slash:comments>12</slash:comments> </item> <item><title>Why You Don&#8217;t Need Dependency Injection In Ruby</title><link>http://davybrion.com/blog/2010/10/why-you-dont-need-dependency-injection-in-ruby/</link> <comments>http://davybrion.com/blog/2010/10/why-you-dont-need-dependency-injection-in-ruby/#comments</comments> <pubDate>Mon, 11 Oct 2010 06:00:32 +0000</pubDate> <dc:creator>Davy Brion</dc:creator> <category><![CDATA[Code Quality]]></category> <category><![CDATA[Dependency Injection]]></category> <category><![CDATA[Opinions]]></category> <category><![CDATA[Ruby]]></category><guid
isPermaLink="false">http://davybrion.com/blog/?p=2768</guid> <description><![CDATA[If you're new to Ruby and you're coming from static languages like C# or Java, you'll probably wonder why there isn't much interest in Dependency Injection in the Ruby community. The answer is quite simple: because you don't need it. Now, that's not to say that Dependency Injection isn't a valuable technique in your toolbox. [...]]]></description> <content:encoded><![CDATA[<p>If you're new to Ruby and you're coming from static languages like C# or Java, you'll probably wonder why there isn't much interest in Dependency Injection in the Ruby community.  The answer is quite simple: because you don't need it.  Now, that's not to say that Dependency Injection isn't a valuable technique in your toolbox.  In fact, if you're doing C# or Java i'd even go as far as saying it's absolutely necessary to use Dependency Injection in most of your code.  Two of the biggest reasons (i know there are more, but let's focus on these for now) why Dependency Injection is important if you're using a static language are these:</p><ol><li>Highly increased testability because you can control the dependencies during automated tests</li><li>Lowered coupling between classes which enables you to change implementations of dependencies at will (granted, not a lot of people actually do that often but it certainly is <a
href="http://davybrion.com/blog/2009/12/real-world-benefits-from-loose-coupling-inversion-of-control-and-dependency-injection/">a real benefit</a>)</li></ol><p>In Ruby however, you don't really need dependency injection to achieve the 2 benefits mentioned above as i hope the following contrived example shows.  Suppose we have the following 2 classes.</p><div><pre class="brush: ruby; title: ; notranslate">
class Dependency
  def do_something_with(some_object)
    p some_object
  end
end

class SomeClass
  def work_your_magic_on(something)
    Dependency.new.do_something_with something
  end
end
</pre></div><p>This is no good. The work_your_magic_on method from SomeClass directly instantiates a new instance of the Dependency class.  During automated tests, we could actually replace the implementation of the new method of the Dependency class to return a stub or a mock if we want to instead of an instance of the real thing.  But we could never easily change the implementation of the dependency that SomeClass requires to function properly in real production code without screwing up everything else that also happens to depend on the Dependency class.</p><p>If you're coming from a static language, you'd probably be inclined to change SomeClass to this:</p><div><pre class="brush: ruby; title: ; notranslate">
class SomeClass
  def initialize(dependency)
    @dependency = dependency
  end
  
  def work_your_magic_on(something)
    @dependency.do_something_with something
  end
end
</pre></div><p>Ahh, that's much better.  The dependency is now injected in SomeClass' initializer method and we can very easily achieve the above mentioned 2 benefits by passing whatever we want to each instance of SomeClass, as long as it has a do_something_with method.  The biggest downside however is that every consumer of SomeClass instances now needs to know about the dependencies that it requires to function properly.  This quickly becomes very painful because using Dependency Injection throughout your codebase will very quickly lead to having to satisfy the dependencies of the dependencies of the dependencies of the dependencies of the class you actually need to use.  This quickly requires the usage of a good Inversion Of Control Container to handle all of these dependencies for you.  There's just one problem: there doesn't seem to be a widely used IOC Container in Ruby.  Which in itself tells you that it's simply not needed in Ruby.</p><p>There's a better way to modify SomeClass:</p><div><pre class="brush: ruby; title: ; notranslate">
class SomeClass
  def work_your_magic_on(something)
    get_dependency.do_something_with something
  end
  
  private
  
  def get_dependency
    @dependency = Dependency.new if @dependency.nil?
    @dependency
  end
end
</pre></div><p>Now, the ALT.NET fanbois will still tell you how wrong this is because SomeClass still has a direct dependency on the Dependency class.  I should know because i was one of them.  And again, in C# or Java i'd definitely agree that this code is bad.  Not so in Ruby however because i can easily replace the actual implementation of SomeClass' dependency in both automated tests and actual production code, without impacting anything else that uses the Dependency class.</p><p>Suppose we have the following test:</p><div><pre class="brush: ruby; title: ; notranslate">
  def test_magic
    object = SomeClass.new
    object.work_your_magic_on &quot;some important string&quot;
    # TODO: assert that the string was passed to the dependency correctly
  end
</pre></div><p>Since i don't provide the dependency to the object that i'm testing, i can't really verify that the dependency was used correctly. I'm also not using any mocking framework since i want to show how the language itself takes away the need to inject your dependencies.  Given the following spy class:</p><div><pre class="brush: ruby; title: ; notranslate">
class DependencySpy
  @@passed_in_objects = []
  
  def self.passed_in_objects
    @@passed_in_objects
  end
  
  def do_something_with(some_object)
    @@passed_in_objects &lt;&lt; some_object
  end
end
</pre></div><p>I could now write my test like this:</p><div><pre class="brush: ruby; title: ; notranslate">
  def test_magic
    object = SomeClass.new
    def object.get_dependency
      DependencySpy.new
    end
    object.work_your_magic_on &quot;some important string&quot;
    assert DependencySpy.passed_in_objects.include? &quot;some important string&quot;
  end
</pre></div><p>And it'll pass.  The 'trick' is that i simply change the implementation of the get_dependency method for <em>the instance that i have</em>.  This doesn't change anything at the class level, merely at the instance level.  Technically, i don't really change the implementation of get_dependency in SomeClass, i merely insert a method in this particular instance which will precede the one in SomeClass during Ruby's method lookup procedure.</p><p>Also, i would like to point out that this kind of testing isn't exactly something that i'd encourage you to do, though this technique can be useful if you really need to do interaction testing.  But it's a good illustration of why you don't really need to do Dependency Injection in Ruby to write testable code.</p><p>Now you might be wondering, what's the difference between doing something like this and using a tool like TypeMock in .NET to basically achieve the same thing?  Well, when writing code like this in C# and testing it with TypeMock, you achieve one of the benefits that you could have with using Dependency Injection: being able to control the dependencies.  But you can't change the implementation of the dependency at runtime in normal production code.  In Ruby, with the approach outlined above, i can still easily achieve that like this:</p><div><pre class="brush: ruby; title: ; notranslate">
class SomeClass
  
  private
  
  def get_dependency
    @dependency = SomeOtherDependency.new if @dependency.nil?
    @dependency
  end
  
end
</pre></div><p>If this code is executed after the earlier definition of SomeClass, it will reopen SomeClass and change the implementation of the get_dependency method for each instance that will be created.  This effectively gives you the ability to change the implementation of a dependency at runtime in production code, without having to use Dependency Injection.  Now, some Dependency Injection purists will still claim that this approach is bad because SomeClass knows which implementation of the dependency it uses.  And my question to those people is: so what? I can easily change it in any situation i'd run into.  You can also consider the presence of the actual type of the dependency as the default implementation to use, without having to force the requirement of this knowledge on consumers.</p><p>There is still one situation where i would probably use Dependency Injection in Ruby though, and that is when you want to benefit from what i consider to be yet another great reason to use Dependency Injection in static languages:</p><ul><li>Not having to know anything about the lifecycle of your dependencies</li></ul><p>In this case, it's probably much easier to just inject a long-living dependency in an object with a shorter lifecycle.  However, if the dependency is basically a singleton (which is still the default for many of the .NET IOC Containers), then i actually would consider implementing the singleton as a class with nothing but class methods (similar to static methods in static languages, but not quite since you can still change them whenever you want) and having my other classes that depend on it call those methods directly, or through helper methods that i can still change when i need to.</p><p>I'm sure many people will disagree with some of the points i try to make in this post, but until i get some actual real-world reasons that invalidate my points, i simply don't see the point in sticking to a set of rules and guidelines that were largely made up out of necessity to deal with shortcomings of static languages.  That's not to say that dynamic languages don't have any shortcomings or drawbacks, but it does mean that the rules and guidelines of how to write good code are, well, simply different.  And as such, it wouldn't be wise to blindly stick with rules that were made for a different way of programming.  Question what you already know, because it might not be relevant to what you need to do <em>now</em>.</p><div
class="bottomcontainerBox" style=""><div
style="float:left; width:85px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;"> <iframe
src="http://www.facebook.com/plugins/like.php?href=http%3A%2F%2Fdavybrion.com%2Fblog%2F2010%2F10%2Fwhy-you-dont-need-dependency-injection-in-ruby%2F&amp;layout=button_count&amp;show_faces=false&amp;width=85&amp;action=like&amp;font=verdana&amp;colorscheme=light&amp;height=21" scrolling="no" frameborder="0" allowTransparency="true" style="border:none; overflow:hidden; width:85px; height:21px;"></iframe></div><div
style="float:left; width:80px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;"> <g:plusone size="medium" href="http://davybrion.com/blog/2010/10/why-you-dont-need-dependency-injection-in-ruby/"></g:plusone></div><div
style="float:left; width:95px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;"> <a
href="http://twitter.com/share" class="twitter-share-button" data-url="http://davybrion.com/blog/2010/10/why-you-dont-need-dependency-injection-in-ruby/"  data-text="Why You Don&#8217;t Need Dependency Injection In Ruby" data-count="horizontal" data-via="davybrion"></a></div><div
style="float:left; width:105px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;"><script type="in/share" data-url="http://davybrion.com/blog/2010/10/why-you-dont-need-dependency-injection-in-ruby/" data-counter="right"></script></div><div
style="float:left; width:85px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;"><script src="http://www.stumbleupon.com/hostedbadge.php?s=1&amp;r=http://davybrion.com/blog/2010/10/why-you-dont-need-dependency-injection-in-ruby/"></script></div></div><div
style="clear:both"></div><div
style="padding-bottom:4px;"></div>]]></content:encoded> <wfw:commentRss>http://davybrion.com/blog/2010/10/why-you-dont-need-dependency-injection-in-ruby/feed/</wfw:commentRss> <slash:comments>25</slash:comments> </item> <item><title>Compiler&#124;Interpreter Warnings Are Important Learning Opportunities</title><link>http://davybrion.com/blog/2010/08/compilerinterpreter-warnings-are-important-learning-opportunities/</link> <comments>http://davybrion.com/blog/2010/08/compilerinterpreter-warnings-are-important-learning-opportunities/#comments</comments> <pubDate>Fri, 27 Aug 2010 22:27:03 +0000</pubDate> <dc:creator>Davy Brion</dc:creator> <category><![CDATA[Code Quality]]></category><guid
isPermaLink="false">http://davybrion.com/blog/?p=2570</guid> <description><![CDATA[When i first started to write C# code, i payed a lot of attention to compiler warnings. I wanted to avoid them at all costs. And with that i don't mean suppressing them, but preventing them from being issued in the first place. I learned quite a few things from actually trying to understand why [...]]]></description> <content:encoded><![CDATA[<p>When i first started to write C# code, i payed a lot of attention to compiler warnings.  I wanted to avoid them at all costs.  And with that i don't mean suppressing them, but preventing them from being issued in the first place.  I learned quite a few things from actually trying to understand why a certain compiler warning was issued, instead of just ignoring it like so many other developers do.  In fact, when it comes to C#, i'd recommend turning on the Treat Warnings As Errors option on each project since i've <em>never</em> come across a C# compiler warning that you couldn't avoid.  And in practically every single case, avoiding the warning led to <em>better code</em>.  When writing C#, i've never seen a single warning that was pointless.  There might be a few esoteric ones that aren't worth fixing, but the vast majority of us will never run into those.  So do yourself a favor: if you get a compiler warning, make sure you understand why the warning was issued, and fix your code based on what you just learned while researching the warning.  There simply is no reason not to do so, unless you happen to bump into the few cases where it really doesn't matter but those cases will be far and between.  In fact, i'd bet that only people like Ayende will run into them while us mortals never will.</p><p>So, how do i feel about warnings in the context of my ongoing Ruby journey? I have so little experience with Ruby that i can't state that every single warning should be avoided.  But i am of the opinion that you should at least be aware of every warning, and investigate whether or not you should modify your code to avoid it.  Today i wrote my first Rakefile which automatically runs all of my RSpec tests for my EventPublisher module and one of the options of the SpecTask was to enable warnings from the Ruby interpreter.  I was actually surprised that i hadn't yet ran my Ruby code with warnings turned on.  Maybe i was just too busy being impressed with the whole Ruby + TextMate package.  Anyways, i turned on the warnings, ran 'rake' and watched a few warnings show up, much to my disappointment.  Well, i was disappointed at first because i thought the code was in good shape but then i figured "ok, this is no big deal... i just gotta fix my code and i'll learn from it".  And i did learn from it.  The first one was a simple RSpec assertion that i wrote which looked like this:</p><div><pre class="brush: ruby; title: ; notranslate">
    it &quot;should know about the subscribed method for the correct event&quot; do
        @publisher.subscribe :first_event, method(:first_event_handler)
        subscribed = @publisher.subscribed? :first_event, method(:first_event_handler)
        subscribed.should == true
    end
</pre></div><p>This generated the following warning:
warning: useless use of == in void context</p><p>I looked into it, and learned that when using RSpec, the last line should've been written like this:</p><div><pre class="brush: ruby; title: ; notranslate">
        subscribed.should be_true
</pre></div><p>You're probably thinking "now that's a tiny difference and not really worth it".  And you'd be wrong.  While the resulting modification in code is indeed minor, i learned about RSpec's Matchers and how they work.  And that knowledge is gonna help me in future code.</p><p>I also had the following piece of a code:</p><div><pre class="brush: ruby; title: ; notranslate">
            define_method getter do
                event = instance_variable_get variable

                if event == nil
                    event = Event.new(symbol.to_s)
                    instance_variable_set variable, event
                end

                event
            end
</pre></div><p>When i wrote it and saw that it worked, i was pretty happy.  But it turns out that this code causes the interpreter to issue the following warning:</p><p>warning: instance variable @first_event not initialized</p><p>In this case, @first_event was the value of the 'variable' variable, which is why the warning looks like that when the code is actually executed.   So again, i looked into it, and learned that i should've written that code like this:</p><div><pre class="brush: ruby; title: ; notranslate">
            define_method getter do
                if !instance_variable_defined? variable
                    event = Event.new(symbol.to_s)
                    instance_variable_set variable, event
                end
                
                instance_variable_get variable
            end
</pre></div><p>Moral of the story? Do not ignore compiler/interpreter warnings.  They are there to help you improve not only your current code, but also your future code.  That is, if you're willing to pay attention to them.</p><p>Note: if you have experience with a variety of C/C++ compilers from back in the day, i can imagine that your opinion differs greatly from mine.  However, i'm not talking about C/C++, so please keep the context (not to mention the decade...) in mind before you start typing a reply about how warnings in C/C++ could easily be justified depending on the compiler you were using <img
src='http://d18sni7re4ly7f.cloudfront.net/blog/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /></p><div
class="bottomcontainerBox" style=""><div
style="float:left; width:85px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;"> <iframe
src="http://www.facebook.com/plugins/like.php?href=http%3A%2F%2Fdavybrion.com%2Fblog%2F2010%2F08%2Fcompilerinterpreter-warnings-are-important-learning-opportunities%2F&amp;layout=button_count&amp;show_faces=false&amp;width=85&amp;action=like&amp;font=verdana&amp;colorscheme=light&amp;height=21" scrolling="no" frameborder="0" allowTransparency="true" style="border:none; overflow:hidden; width:85px; height:21px;"></iframe></div><div
style="float:left; width:80px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;"> <g:plusone size="medium" href="http://davybrion.com/blog/2010/08/compilerinterpreter-warnings-are-important-learning-opportunities/"></g:plusone></div><div
style="float:left; width:95px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;"> <a
href="http://twitter.com/share" class="twitter-share-button" data-url="http://davybrion.com/blog/2010/08/compilerinterpreter-warnings-are-important-learning-opportunities/"  data-text="Compiler|Interpreter Warnings Are Important Learning Opportunities" data-count="horizontal" data-via="davybrion"></a></div><div
style="float:left; width:105px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;"><script type="in/share" data-url="http://davybrion.com/blog/2010/08/compilerinterpreter-warnings-are-important-learning-opportunities/" data-counter="right"></script></div><div
style="float:left; width:85px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;"><script src="http://www.stumbleupon.com/hostedbadge.php?s=1&amp;r=http://davybrion.com/blog/2010/08/compilerinterpreter-warnings-are-important-learning-opportunities/"></script></div></div><div
style="clear:both"></div><div
style="padding-bottom:4px;"></div>]]></content:encoded> <wfw:commentRss>http://davybrion.com/blog/2010/08/compilerinterpreter-warnings-are-important-learning-opportunities/feed/</wfw:commentRss> <slash:comments>5</slash:comments> </item> <item><title>The Downside Of Providing An API Through Extension Methods</title><link>http://davybrion.com/blog/2010/08/the-downside-of-providing-an-api-through-extension-methods/</link> <comments>http://davybrion.com/blog/2010/08/the-downside-of-providing-an-api-through-extension-methods/#comments</comments> <pubDate>Thu, 26 Aug 2010 15:24:00 +0000</pubDate> <dc:creator>Davy Brion</dc:creator> <category><![CDATA[Code Quality]]></category> <category><![CDATA[testing]]></category><guid
isPermaLink="false">http://davybrion.com/blog/?p=2510</guid> <description><![CDATA[I recently used the excellent Moq mocking library for the first time, and i noticed a difference between Moq and Rhino Mocks (what i usually use) that i found interesting. Consider the following useless and contrived example code: Now suppose that we want to verify in a test that the DoSomethingReallyImportant method of SomeClass actually [...]]]></description> <content:encoded><![CDATA[<p>I recently used the excellent <a
href="http://code.google.com/p/moq/">Moq</a> mocking library for the first time, and i noticed a difference between Moq and Rhino Mocks (what i usually use) that i found interesting.</p><p>Consider the following useless and contrived example code:</p><div><pre class="brush: csharp; title: ; notranslate">
    public interface ISomeComponent
    {
        void DoSomething();
    }
 
    public class SomeClass
    {
        private ISomeComponent someComponent;
 
        public SomeClass(ISomeComponent someComponent)
        {
            this.someComponent = someComponent;
        }
 
        public void DoSomethingReallyImportant()
        {
            someComponent.DoSomething();
        }
    } 
</pre></div><p>Now suppose that we want to verify in a test that the DoSomethingReallyImportant method of SomeClass actually calls the DoSomething method of its ISomeComponent dependency.</p><p>With Moq, we could do that like this:</p><div><pre class="brush: csharp; title: ; notranslate">
    [TestFixture]
    public class TestWithMoq
    {

        [Test]
        public void CallsDoSomethingOnSomeComponent()
        {
            var mock = new Mock&lt;ISomeComponent&gt;();
            var someObject = new SomeClass(mock.Object);
 
            someObject.DoSomethingReallyImportant();
 
            mock.Verify(m =&gt; m.DoSomething());
        }
    }
</pre></div><p>And with Rhino Mocks, it would look like this:</p><div><pre class="brush: csharp; title: ; notranslate">
    [TestFixture]
    public class TestWithMoq
    {
        [Test]
        public void CallsDoSomethingOnSomeComponent()
        {
            var mock = new Mock&lt;ISomeComponent&gt;();
            var someObject = new SomeClass(mock.Object);
 
            someObject.DoSomethingReallyImportant();
 
            mock.Verify(m =&gt; m.DoSomething());
        }
    }
</pre></div><p>Not much of a difference, right? Except that Rhino Mocks provides you with a proxy that implements the ISomeComponent interface and Moq provides you with a generic Mock object, which contains a proxy that implements the ISomeComponent interface and is exposed through the Object property.  Other than that, the tests are very similar.</p><p>The key difference is what you experience when you write the tests, as the 2 pictures below will illustrate:</p><p> <img
src="http://davybrion.com/blog/wp-content/uploads/2010/08/with_moq.png" alt="" title="with_moq" width="471" height="210" class="aligncenter size-full wp-image-2511" /><img
src="http://davybrion.com/blog/wp-content/uploads/2010/08/with_rhino.png" alt="" title="with_rhino" width="757" height="303" class="aligncenter size-full wp-image-2512" /></p><p> Since Moq's API is not fully based on Extension Methods, you get a normal and clean IntelliSense experience.  Rhino Mocks on the other hand provides its API (at least the non-legacy stuff) solely through extension methods, which leads to all of them being included in your IntelliSense, even when they don't make any sense at all.It's obviously not a major issue, but i was suprised with how much i liked <em>not</em> seeing all of the extension methods all the time while writing tests.</p><div
class="bottomcontainerBox" style=""><div
style="float:left; width:85px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;"> <iframe
src="http://www.facebook.com/plugins/like.php?href=http%3A%2F%2Fdavybrion.com%2Fblog%2F2010%2F08%2Fthe-downside-of-providing-an-api-through-extension-methods%2F&amp;layout=button_count&amp;show_faces=false&amp;width=85&amp;action=like&amp;font=verdana&amp;colorscheme=light&amp;height=21" scrolling="no" frameborder="0" allowTransparency="true" style="border:none; overflow:hidden; width:85px; height:21px;"></iframe></div><div
style="float:left; width:80px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;"> <g:plusone size="medium" href="http://davybrion.com/blog/2010/08/the-downside-of-providing-an-api-through-extension-methods/"></g:plusone></div><div
style="float:left; width:95px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;"> <a
href="http://twitter.com/share" class="twitter-share-button" data-url="http://davybrion.com/blog/2010/08/the-downside-of-providing-an-api-through-extension-methods/"  data-text="The Downside Of Providing An API Through Extension Methods" data-count="horizontal" data-via="davybrion"></a></div><div
style="float:left; width:105px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;"><script type="in/share" data-url="http://davybrion.com/blog/2010/08/the-downside-of-providing-an-api-through-extension-methods/" data-counter="right"></script></div><div
style="float:left; width:85px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;"><script src="http://www.stumbleupon.com/hostedbadge.php?s=1&amp;r=http://davybrion.com/blog/2010/08/the-downside-of-providing-an-api-through-extension-methods/"></script></div></div><div
style="clear:both"></div><div
style="padding-bottom:4px;"></div>]]></content:encoded> <wfw:commentRss>http://davybrion.com/blog/2010/08/the-downside-of-providing-an-api-through-extension-methods/feed/</wfw:commentRss> <slash:comments>9</slash:comments> </item> <item><title>Once Again: Comments In Code Aren&#8217;t Necessarily Bad</title><link>http://davybrion.com/blog/2010/08/once-again-comments-in-code-arent-necessarily-bad/</link> <comments>http://davybrion.com/blog/2010/08/once-again-comments-in-code-arent-necessarily-bad/#comments</comments> <pubDate>Wed, 18 Aug 2010 20:28:43 +0000</pubDate> <dc:creator>Davy Brion</dc:creator> <category><![CDATA[Code Quality]]></category> <category><![CDATA[Opinions]]></category><guid
isPermaLink="false">http://davybrion.com/blog/?p=2533</guid> <description><![CDATA[I happened to come across some blog posts and tweets that once again mentioned how evil it is to use comments in code. Some people still like to advocate the "if you need comments, your code sucks!" sentiment. As is often the case with this kind of statement, the only correct (or dare i say [...]]]></description> <content:encoded><![CDATA[<p>I happened to come across some blog posts and tweets that once again mentioned how evil it is to use comments in code.  Some people still like to advocate the "if you need comments, your code sucks!" sentiment.  As is often the case with this kind of statement, the only correct (or dare i say realistic) point of view is: it depends!</p><p>I generally agree that you should strive to avoid comments in code.  That is, you should write your code in a way that doesn't require comments for the reader to easily understand and grasp what the code is doing.  However... there are situations where comments <em>are</em> helpful (or even required), since you simply can't write everything in such a manner that it doesn't require any comments.</p><p>To back up my point, i'd like to point you to <a
href="http://davybrion.com/blog/2009/02/challenge-do-you-truly-understand-this-code/">this challenge</a> i posted over a year ago.  That code is clean.  But pretty much everyone could use some comments to understand why that certain approach was necessary since it's just not that obvious when focusing solely on the code.  That code applies a certain pattern which isn't well known, but there is a very specific reason why the pattern is needed.  And i still believe that most developers need comments to understand it properly.  That's not to say that the guy who wrote it (which happened to be me) is better than those who're going to have to maintain it.  Hell, i wrote the code, and i would certainly be glad to see some comments in that code if i had to make a change 6 months after the fact.</p><p>The key thing to remember is this: don't blindly follow what the books and/or the 'legends' say.  If you need to write some code in a very non-obvious way, then you could really make things easier for those who need to maintain it (which could very well be you, btw) by including some comments to explain why a certain solution/pattern was chosen.  There are some details you simply can't show through good naming practices or clean code in general... some things simply need to be explained and it's quite possible that a WHY comment or two benefits not only you but whoever is going to read the code more than some kind of excessive and futile exercise in making it as easy to understand as possible without comments ever will be.</p><p>In short, strive to avoid the need to write comments by writing clean code.  But don't be afraid to use comments wisely either when clean code simply doesn't cut it.  There's nothing wrong with that.  After all, we don't all have the luxury to restrict our efforts to contrived examples.</p><div
class="bottomcontainerBox" style=""><div
style="float:left; width:85px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;"> <iframe
src="http://www.facebook.com/plugins/like.php?href=http%3A%2F%2Fdavybrion.com%2Fblog%2F2010%2F08%2Fonce-again-comments-in-code-arent-necessarily-bad%2F&amp;layout=button_count&amp;show_faces=false&amp;width=85&amp;action=like&amp;font=verdana&amp;colorscheme=light&amp;height=21" scrolling="no" frameborder="0" allowTransparency="true" style="border:none; overflow:hidden; width:85px; height:21px;"></iframe></div><div
style="float:left; width:80px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;"> <g:plusone size="medium" href="http://davybrion.com/blog/2010/08/once-again-comments-in-code-arent-necessarily-bad/"></g:plusone></div><div
style="float:left; width:95px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;"> <a
href="http://twitter.com/share" class="twitter-share-button" data-url="http://davybrion.com/blog/2010/08/once-again-comments-in-code-arent-necessarily-bad/"  data-text="Once Again: Comments In Code Aren&#8217;t Necessarily Bad" data-count="horizontal" data-via="davybrion"></a></div><div
style="float:left; width:105px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;"><script type="in/share" data-url="http://davybrion.com/blog/2010/08/once-again-comments-in-code-arent-necessarily-bad/" data-counter="right"></script></div><div
style="float:left; width:85px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;"><script src="http://www.stumbleupon.com/hostedbadge.php?s=1&amp;r=http://davybrion.com/blog/2010/08/once-again-comments-in-code-arent-necessarily-bad/"></script></div></div><div
style="clear:both"></div><div
style="padding-bottom:4px;"></div>]]></content:encoded> <wfw:commentRss>http://davybrion.com/blog/2010/08/once-again-comments-in-code-arent-necessarily-bad/feed/</wfw:commentRss> <slash:comments>33</slash:comments> </item> <item><title>Can An Object Grow?</title><link>http://davybrion.com/blog/2010/08/can-an-object-grow/</link> <comments>http://davybrion.com/blog/2010/08/can-an-object-grow/#comments</comments> <pubDate>Tue, 17 Aug 2010 20:55:09 +0000</pubDate> <dc:creator>Davy Brion</dc:creator> <category><![CDATA[Code Quality]]></category><guid
isPermaLink="false">http://davybrion.com/blog/?p=2530</guid> <description><![CDATA[As you probably know, i'm currently learning Ruby. And as you may or may not know, Ruby is a very dynamic language. And one of the things that i found immensely interesting about it is the ability to add methods to existing classes or to existing objects, which isn't the same as adding a method [...]]]></description> <content:encoded><![CDATA[<p>As you probably know, i'm currently learning Ruby.  And as you may or may not know, Ruby is a very dynamic language.  And one of the things that i found immensely interesting about it is the ability to add methods to existing classes or to existing objects, which isn't the same as adding a method to a class in Ruby btw.  And it sorta got me thinking about how the whole static vs dynamic thing can be applied to how we are often taught about objects and classes.</p><p>Chances are that when you learned about OO, you were introduced to the concept of objects using real world items.  For instance, a door could be an object.  It has certain attributes, and it has certain operations that can be invoked on it.  But once a door has been produced, it will never gain new capabilities.  It won't learn anything new.  If anything, the attributes and operations that it was created with will only deteriorate over time.</p><p>Then again, some of us will undoubtedly have heard that a person is an example of an object too.  A Person is an instance of the Human class.  There is a huge difference between a Person instance and a Door instance.  While the Door will never change (except for possible deterioration), a Person will change during its lifetime.  It will gain new capabilities depending on what the Person instance goes through during its lifetime.  It will also lose capabilities.  It will gain new attributes, and some of them will no longer apply to that Person instance after a while.  Its relationships can vary wildly from each Person to the next.  A Person instance is highly dynamic throughout its lifetime, while a Door will always be the same.</p><p>The weird thing is... a lot of us use OO to model or mimic real world behavior.  But real world behavior is pretty dynamic.  Not for everything, but it definitely is for some things.  And all this time, a large majority of us has been trying to model or mimic that behavior with static languages.  In a static language, a Person instance would never be able to grow.  You could define multiple types of Persons, but hey, a lot of people generally don't like to be put in groups based on attributes or capabilities and you'll always run into problems when doing so.</p><p>I'm not trying to convince anyone about anything specific in this post. But i am trying to get you think about what i'm saying.  I do believe that objects can 'grow' in some or maybe even a lot of cases.  And i think a lot of us can agree that static languages aren't exactly a great solution to dealing with this problem (though i prefer the term 'reality' instead).  Dynamic languages on the other hand can offer better ways to deal with this, but then again you do have to keep in mind that they come with some downsides as well.  In software development, there are very, very few win-win situations.  Everything is a trade-off.  For everything that you know and love, there will be an alternative that is more suitable in some cases, and less suitable in others.</p><p>So now i'd like to ask you the following 2 questions:
1) do you think that objects can 'grow'?
2) can developers grow? and how does that answer correspond to your answer to the first question?</p><div
class="bottomcontainerBox" style=""><div
style="float:left; width:85px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;"> <iframe
src="http://www.facebook.com/plugins/like.php?href=http%3A%2F%2Fdavybrion.com%2Fblog%2F2010%2F08%2Fcan-an-object-grow%2F&amp;layout=button_count&amp;show_faces=false&amp;width=85&amp;action=like&amp;font=verdana&amp;colorscheme=light&amp;height=21" scrolling="no" frameborder="0" allowTransparency="true" style="border:none; overflow:hidden; width:85px; height:21px;"></iframe></div><div
style="float:left; width:80px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;"> <g:plusone size="medium" href="http://davybrion.com/blog/2010/08/can-an-object-grow/"></g:plusone></div><div
style="float:left; width:95px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;"> <a
href="http://twitter.com/share" class="twitter-share-button" data-url="http://davybrion.com/blog/2010/08/can-an-object-grow/"  data-text="Can An Object Grow?" data-count="horizontal" data-via="davybrion"></a></div><div
style="float:left; width:105px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;"><script type="in/share" data-url="http://davybrion.com/blog/2010/08/can-an-object-grow/" data-counter="right"></script></div><div
style="float:left; width:85px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;"><script src="http://www.stumbleupon.com/hostedbadge.php?s=1&amp;r=http://davybrion.com/blog/2010/08/can-an-object-grow/"></script></div></div><div
style="clear:both"></div><div
style="padding-bottom:4px;"></div>]]></content:encoded> <wfw:commentRss>http://davybrion.com/blog/2010/08/can-an-object-grow/feed/</wfw:commentRss> <slash:comments>21</slash:comments> </item> <item><title>Is That How You Talk To People?</title><link>http://davybrion.com/blog/2010/07/is-that-how-you-talk-to-people/</link> <comments>http://davybrion.com/blog/2010/07/is-that-how-you-talk-to-people/#comments</comments> <pubDate>Mon, 26 Jul 2010 12:29:05 +0000</pubDate> <dc:creator>Davy Brion</dc:creator> <category><![CDATA[Code Quality]]></category><guid
isPermaLink="false">http://davybrion.com/blog/2010/07/is-that-how-you-talk-to-people/</guid> <description><![CDATA[I just spotted the following 2 methods in a piece of code: &#160;&#160;&#160;&#160;&#160;&#160;&#160; public void ShowPanelWindow(bool isVisible) &#160;&#160;&#160;&#160;&#160;&#160;&#160; { &#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; Visibility = isVisible ? Visibility.Visible : Visibility.Collapsed; &#160;&#160;&#160;&#160;&#160;&#160;&#160; } &#160; &#160;&#160;&#160;&#160;&#160;&#160;&#160; public void ShowBusy(bool isBusy) &#160;&#160;&#160;&#160;&#160;&#160;&#160; { &#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; BusyIndicator.ShowIsBusy = isBusy; &#160;&#160;&#160;&#160;&#160;&#160;&#160; } &#160; And i cringed. Personally, i think it’s weird to read lines [...]]]></description> <content:encoded><![CDATA[<p>I just spotted the following 2 methods in a piece of code:</p><div
style="font-family: consolas; background: white; color: black; font-size: 10pt"><p
style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span
style="color: blue">public</span> <span
style="color: blue">void</span> <span
style="color: #008b8b">ShowPanelWindow</span>(<span
style="color: blue">bool</span> isVisible)</p><p
style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; {</p><p
style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span
style="color: purple">Visibility</span> = isVisible ? <span
style="color: #00008b">Visibility</span>.<span
style="color: purple; font-weight: bold">Visible</span> : <span
style="color: #00008b">Visibility</span>.<span
style="color: purple; font-weight: bold">Collapsed</span>;</p><p
style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; }</p><p
style="margin: 0px">&#160;</p><p
style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span
style="color: blue">public</span> <span
style="color: blue">void</span> <span
style="color: #008b8b">ShowBusy</span>(<span
style="color: blue">bool</span> isBusy)</p><p
style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; {</p><p
style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span
style="color: purple">BusyIndicator</span>.<span
style="color: purple">ShowIsBusy</span> = isBusy;</p><p
style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; }</p><p
style="margin: 0px">&#160;</p></div><p>And i cringed. Personally, i think it’s weird to read lines of code that say view.ShowPanelWindow(false) or view.ShowBusy(false).&#160; Instead, i’d go for something like this:</p><div
style="font-family: consolas; background: white; color: black; font-size: 10pt"><p
style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span
style="color: blue">public</span> <span
style="color: blue">void</span> <span
style="color: #008b8b">HidePanelWindow</span>()</p><p
style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; {</p><p
style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span
style="color: purple">Visibility</span> = <span
style="color: #00008b">Visibility</span>.<span
style="color: purple; font-weight: bold">Collapsed</span>;</p><p
style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; }</p><p
style="margin: 0px">&#160;</p><p
style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span
style="color: blue">public</span> <span
style="color: blue">void</span> <span
style="color: #008b8b">ShowPanelWindow</span>()</p><p
style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; {</p><p
style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span
style="color: purple">Visibility</span> = <span
style="color: #00008b">Visibility</span>.<span
style="color: purple; font-weight: bold">Visible</span>;</p><p
style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; }</p><p
style="margin: 0px">&#160;</p><p
style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span
style="color: blue">public</span> <span
style="color: blue">void</span> <span
style="color: #008b8b">LookBusy</span>()</p><p
style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; {</p><p
style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span
style="color: purple">BusyIndicator</span>.<span
style="color: purple">ShowIsBusy</span> = <span
style="color: blue">true</span>;</p><p
style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; }</p><p
style="margin: 0px">&#160;</p><p
style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span
style="color: blue">public</span> <span
style="color: blue">void</span> <span
style="color: #008b8b">StopLookingBusy</span>()</p><p
style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; {</p><p
style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span
style="color: purple">BusyIndicator</span>.<span
style="color: purple">ShowIsBusy</span> = <span
style="color: blue">false</span>;</p><p
style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; }</p><p
style="margin: 0px">&#160;</p></div><p>Sure, i’m not gonna win the fewest-lines-of-code contest but then again, we’re not participating in that contest anyway.&#160; And while my version is a little bit longer, it doesn’t take more than a few extra seconds to write that extra code, and the improved readability of the consuming code is more than worth it.&#160; After all, you do prefer reading view.HidePanelWindow() over view.ShowPanelWindow(false), no?</p><p>I’ve always liked the following approach to avoid (or at least, mimimize) bad method names.&#160; Just pretend that the classes are people and that the method names are messages between them.&#160; There is after all a reason why we referred to it as “sending a message to an object” originally in OO-terms.&#160; Give it a shot, and you’ll notice that your code will become more readable with hardly any extra effort.</p><div
class="bottomcontainerBox" style=""><div
style="float:left; width:85px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;"> <iframe
src="http://www.facebook.com/plugins/like.php?href=http%3A%2F%2Fdavybrion.com%2Fblog%2F2010%2F07%2Fis-that-how-you-talk-to-people%2F&amp;layout=button_count&amp;show_faces=false&amp;width=85&amp;action=like&amp;font=verdana&amp;colorscheme=light&amp;height=21" scrolling="no" frameborder="0" allowTransparency="true" style="border:none; overflow:hidden; width:85px; height:21px;"></iframe></div><div
style="float:left; width:80px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;"> <g:plusone size="medium" href="http://davybrion.com/blog/2010/07/is-that-how-you-talk-to-people/"></g:plusone></div><div
style="float:left; width:95px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;"> <a
href="http://twitter.com/share" class="twitter-share-button" data-url="http://davybrion.com/blog/2010/07/is-that-how-you-talk-to-people/"  data-text="Is That How You Talk To People?" data-count="horizontal" data-via="davybrion"></a></div><div
style="float:left; width:105px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;"><script type="in/share" data-url="http://davybrion.com/blog/2010/07/is-that-how-you-talk-to-people/" data-counter="right"></script></div><div
style="float:left; width:85px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;"><script src="http://www.stumbleupon.com/hostedbadge.php?s=1&amp;r=http://davybrion.com/blog/2010/07/is-that-how-you-talk-to-people/"></script></div></div><div
style="clear:both"></div><div
style="padding-bottom:4px;"></div>]]></content:encoded> <wfw:commentRss>http://davybrion.com/blog/2010/07/is-that-how-you-talk-to-people/feed/</wfw:commentRss> <slash:comments>17</slash:comments> </item> <item><title>The MVVM Pattern Is Highly Overrated</title><link>http://davybrion.com/blog/2010/07/the-mvvm-pattern-is-highly-overrated/</link> <comments>http://davybrion.com/blog/2010/07/the-mvvm-pattern-is-highly-overrated/#comments</comments> <pubDate>Wed, 21 Jul 2010 14:23:58 +0000</pubDate> <dc:creator>Davy Brion</dc:creator> <category><![CDATA[Architecture]]></category> <category><![CDATA[Code Quality]]></category> <category><![CDATA[Silverlight]]></category><guid
isPermaLink="false">http://davybrion.com/blog/?p=2392</guid> <description><![CDATA[Update: check out my MVP In Silverlight/WPF series which discusses the MVP approach as an alternative to MVVM If you're doing Silverlight or WPF, you've no doubt come across the MVVM (Model-View-ViewModel) pattern. It seems to be the most popular client-side architecture pattern used among Silverlight/WPF developers. I find the pattern to be highly overrated, [...]]]></description> <content:encoded><![CDATA[<p>Update: check out my <a
href="http://davybrion.com/blog/2010/08/mvp-in-silverlightwpf-series/">MVP In Silverlight/WPF series</a> which discusses the MVP approach as an alternative to MVVM</p><p>If you're doing Silverlight or WPF, you've no doubt come across the MVVM (Model-View-ViewModel) pattern.  It seems to be the most popular client-side architecture pattern used among Silverlight/WPF developers.  I find the pattern to be highly overrated, and actually have some big issues with the whole thing.</p><p>First, let's briefly cover what MVVM is about for those of you who don't know yet.  MVVM virtually eliminates all of the code that would typically be placed in the code-behind file of your View (a user control, a screen, whatever) by putting all of that logic in the ViewModel.  The ViewModel itself is never tightly coupled to the View. If it does have a reference to it, it's typically through an interface that the View implements instead of a reference of the actual type of the View.  This increases, or better yet, introduces testability to a large part of your UI code that you normally wouldn't be able to cover with unit tests if you'd go with the traditional "put it all in the code-behind"-approach.</p><p>The ViewModel typically contains properties for the data that is to be shown in the View, and also raises notification events when the data in those properties changes.  The View uses the powerful data-binding capabilities of Silverlight/WPF to bind the properties of the ViewModel to other user controls that the View is composed of.  User-events that are captured by the View are sent to the ViewModel through Commands.  Typically, these commands execute a method in the ViewModel which contains some kind of logic... usually to either send the updated data in the ViewModel's properties to the Model (usually a Service Layer in Silverlight, in WPF it could be either a true Domain Model or also a Service Layer), to perform some business logic in the Model, or to retrieve data from the Model so it can be placed in the ViewModel's properties so the View can bind to it.</p><p>That is, in a nutshell, how the MVVM pattern works.  So why do i have issues with this? You can develop and test most of the application's logic without being dependent on a physical View and that is typically a Good Thing, no? It sure is!  However, my problem with this approach is that  too many responsibilities are concentrated within the ViewModel.  Its main responsibilities are to facilitate databinding <em>and</em> to interact with the Model.  And that, in my opinion, isn't very clean.  In some ways, you could actually think of the ViewModel as a glorified code-behind, with the only difference being that it's not tightly coupled to the (physical) View.</p><p>In most (if not all) MVVM implementations, a ViewModel has many possible reasons to be changed.  It might need to be changed because of different data-binding requirements.  Then again, it might also require changes when a part of the Model is modified.  Now, i'm sure many of you can agree with me when i say that two of the most important principles in software development are <a
href="http://en.wikipedia.org/wiki/Separation_of_concerns">Seperation of Concerns (SoC)</a> and the <a
href="http://en.wikipedia.org/wiki/Single_responsibility_principle">Single Responsibility Principle (SRP)</a>.  Obviously, the ViewModel doesn't fare well when it comes to both of these principles.</p><p>Lets forget about MVVM for a second and focus on the concerns and responsibilities that a user control can have... say, a user control that shows customer information and allows the user to edit that data so it can be persisted:</p><ul><li>visualization of the actual control (its own layout as well drawing other user controls that it is composed of)</li><li>communication/interaction with the Model</li><li>making data (from the Model) available so it can be displayed</li><li>outputting data in the correct user controls (for instance: various textboxes)</li><li>(simple validation) of modified/inputted data (for instance: no string values for numeric fields, etc...)</li></ul><p>Without MVVM, all of these would be taken care of in the View.  Obviously, not a good idea right?  After all, if it were a good idea, we'd never have had a reason to start using MVVM in the first place.</p><p>Now, with MVVM, a lot of people would divide these concerns and responsibilities like this:</p><p>View:</p><ul><li>visualization of the actual control (its own layout as well drawing other user controls that it is composed of)</li><li>outputting data in the correct user controls (for instance: various textboxes)</li><li>(simple validation) of modified/inputted data (for instance: no string values for numeric fields, etc...)</li></ul><p>ViewModel:</p><ul><li>communication/interaction with the Model</li><li>making data (from the Model) available so it can be displayed</li></ul><p>In this case, the View still has 3 responsibilities which is still too much according to 'the guidelines', but it's not that big of a deal (though plenty of people would argue that the simple validation would be better placed in the ViewModel).  You're highly unlikely to actually want to write automated tests for pure visualization anyway and the SRP is not something that you absolutely need to follow to the extreme in every single place.  For the View, this is really not a problem and very much acceptable.</p><p>The ViewModel however has 2 important responsibilities in this case, and i'd argue that these 2 things should not be done in the same place.  Making data available is done through data-binding.  To do this, you need a set of properties and you need to raise the necessary events.  In most cases, raising those events is very straightforward, but in more complex controls you might need a bit of additional logic to determine which event should be raised at what point.  The other important responsibility is the communication/interaction with the Model.  In most Silverlight applications, the Model will be a Service Layer.  To communicate with this Service Layer, you need Service Proxies.  That means that your ViewModel is essentially responsible for communicating with the Service Layer, dealing with business exceptions that might be thrown by some service calls, and dealing with technical exceptions that can occur simply because of network-related problems.  Group all of those together and i don't think i'm going out on a limb here by saying that that is a lot of logic to put in <em>one</em> class, no?</p><p>(Sidenote: what i don't really understand is that many people who vigorously advocate adherence to SRP and SoC in their domain and business code don't seem to hold their UI code to the same standards. I do.)</p><p>At work, we do <em>a lot</em> of Silverlight development.  We typically have around 5 Silverlight projects in active development at the same time.  And it's been that way for over a year now.  That equals a lot of Silverlight code that we've written and experience and knowledge that we've built up.  And we haven't used MVVM for any of it.  All this time, we've been using the MVP pattern (Supervising Controller variant) with a slight twist.  That twist being a slimmed down version of a <a
href="http://www.martinfowler.com/eaaDev/PresentationModel.html">Presentation Model</a>.  Our Presentation Model's sole responsibility is to facilitate data-binding, and in some cases, a touch of validation is added as well.</p><p>If we go back to our previous example of the customer screen, the responsibilities and concerns would be divided like this in our MVP-PMlight approach:</p><p>View:</p><ul><li>visualization of the actual control (its own layout as well drawing other user controls that it is composed of)</li><li>outputting data in the correct user controls (for instance: various textboxes)</li><li>(simple validation) of modified/inputted data (for instance: no string values for numeric fields, etc...)</li></ul><p>Presenter:</p><ul><li>communication/interaction with the Model based on the contents of the Presentation Model</li></ul><p>Presentation Model:</p><ul><li>making data (from the Model) available so it can be displayed</li></ul><p>Which leads to classes which are more focused on their task instead of trying to focus on too many things at the same time.  In my opinion, this approach is much better/cleaner than MVVM.  Not only is there a noticeable benefit in code quality (classes are more focused), there is also increased potential to reuse our 'light Presentation Models' in multiple controls.  Testability is increased over MVVM as well since it's always easier to test classes which are focused versus testing classes which have too many responsibilities.  All in all, a couple of important benefits and we still haven't thought of a real drawback compared to MVVM.</p><div
class="bottomcontainerBox" style=""><div
style="float:left; width:85px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;"> <iframe
src="http://www.facebook.com/plugins/like.php?href=http%3A%2F%2Fdavybrion.com%2Fblog%2F2010%2F07%2Fthe-mvvm-pattern-is-highly-overrated%2F&amp;layout=button_count&amp;show_faces=false&amp;width=85&amp;action=like&amp;font=verdana&amp;colorscheme=light&amp;height=21" scrolling="no" frameborder="0" allowTransparency="true" style="border:none; overflow:hidden; width:85px; height:21px;"></iframe></div><div
style="float:left; width:80px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;"> <g:plusone size="medium" href="http://davybrion.com/blog/2010/07/the-mvvm-pattern-is-highly-overrated/"></g:plusone></div><div
style="float:left; width:95px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;"> <a
href="http://twitter.com/share" class="twitter-share-button" data-url="http://davybrion.com/blog/2010/07/the-mvvm-pattern-is-highly-overrated/"  data-text="The MVVM Pattern Is Highly Overrated" data-count="horizontal" data-via="davybrion"></a></div><div
style="float:left; width:105px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;"><script type="in/share" data-url="http://davybrion.com/blog/2010/07/the-mvvm-pattern-is-highly-overrated/" data-counter="right"></script></div><div
style="float:left; width:85px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;"><script src="http://www.stumbleupon.com/hostedbadge.php?s=1&amp;r=http://davybrion.com/blog/2010/07/the-mvvm-pattern-is-highly-overrated/"></script></div></div><div
style="clear:both"></div><div
style="padding-bottom:4px;"></div>]]></content:encoded> <wfw:commentRss>http://davybrion.com/blog/2010/07/the-mvvm-pattern-is-highly-overrated/feed/</wfw:commentRss> <slash:comments>102</slash:comments> </item> <item><title>Which Language Do You Code In?</title><link>http://davybrion.com/blog/2010/07/which-language-do-you-code-in/</link> <comments>http://davybrion.com/blog/2010/07/which-language-do-you-code-in/#comments</comments> <pubDate>Sun, 18 Jul 2010 12:21:13 +0000</pubDate> <dc:creator>Davy Brion</dc:creator> <category><![CDATA[Code Quality]]></category><guid
isPermaLink="false">http://davybrion.com/blog/?p=2384</guid> <description><![CDATA[I got into an interesting discussion on twitter today on what language you use when coding. We weren't talking about programming languages, but the actual real world language that is used for class names, method names, variable names, comments, etc... My take on the matter is to just always do it in English. And for [...]]]></description> <content:encoded><![CDATA[<p>I got into an interesting discussion on twitter today on what language you use when coding.  We weren't talking about programming languages, but the actual real world language that is used for class names, method names, variable names, comments, etc...  My take on the matter is to just always do it in English.  And for the record, i'm a native Dutch speaker and i work in Belgium.  Our official languages are Dutch and French, not English.</p><p>A few years ago, i worked at a large financial institution in Belgium where we developed software for internal use in the main offices.  The UI was pretty much always done in Dutch, but most of the time we wrote all of our code in English.  There were a few projects where the developers had used Dutch in their code though.  At first, this wasn't an issue and seemed to be more of a personal preference thing (though mixing within a project is just horrible).  After a while, the company got involved in the outsourcing game and suddenly, they were sending a lot of the projects that were in maintenance to a group of Indian developers.  It's hard enough to get developers who use a different language and are part of a different culture on the same page when working on software, but it's obviously even harder if the code they are supposed to read, maintain and extend is in a language <em>they don't even know</em>.</p><p>At my current job, we also have a branch in Hungary.  We often mix teams so naturally, we all write our code in English.  We not only write our code in English, but we also use English as our language in any kind of documentation.  Now, we do have one customer who insists that the functional designs are all done in Dutch.  Maintaining 2 sets of documents is something that we won't do, and since <a
href="http://davybrion.com/blog/2008/11/genesis-bridging-the-gap-between-requirement-and-code/">our development process requires developers to link our code to our functional designs</a>, we'll never be able to use our Hungarian developers on the projects that we do for this customer.  To me, that is a huge downside to having to write the documents in Dutch.  And it's the exact same problem we'd have if we would write our code in Dutch.</p><p>Both those examples should tell you why i'm so much in favor of just writing code in English all the time.  Generally speaking, if you pick a non-English language to code in, you are limiting the pool of possible future developers to those developers who know the language you've chosen.  It's that simple.  The more people who know the language, the bigger the pool of future developers.  And when it comes to languages that aren't used by a lot of people... well, that's a pretty big restriction on your future options.</p><p>Another downside to using non-English in your code, is that you're effectively already mixing multiple languages in the code base.  Your programming language <em>already is in English</em>, and using non-English in your code leads to something that just sounds (or reads, i guess) wrong.</p><p>The biggest problem that people bring up with always using English, is that you obviously need to translate business concepts.  Especially for people who are doing DDD and who want to leverage the Ubiquitous Language, this isn't always an easy decision to make.  For one, your domain experts might not be willing to take on the translation burden.  If they are unwilling to do so, you can still use a translated version of the Ubiquitous Language but then the entire team (except for the domain experts) has to deal with that burden on a daily basis.</p><p>Now, i'm not sure if that's really that big of a problem.  For starters, English terms are becoming more pervasive in 'business language' every day.  I'm not saying that everyone is already using English for their business concepts/terms, but i would argue that it is increasing, that it's only going to increase more and more and most importantly, that more and more business people don't really have a problem with using English terms anymore.</p><p>And lets not forget that the percentage of teams that is truly doing DDD and leveraging the Ubiquitous Language is probably still small.  After all, most true DDD experts will say that DDD is only a good idea for 10% of all projects <img
src='http://d18sni7re4ly7f.cloudfront.net/blog/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> , so i can't help but wonder how big of an issue the translation burden <em>really</em> is.</p><p>Thoughts?</p><div
class="bottomcontainerBox" style=""><div
style="float:left; width:85px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;"> <iframe
src="http://www.facebook.com/plugins/like.php?href=http%3A%2F%2Fdavybrion.com%2Fblog%2F2010%2F07%2Fwhich-language-do-you-code-in%2F&amp;layout=button_count&amp;show_faces=false&amp;width=85&amp;action=like&amp;font=verdana&amp;colorscheme=light&amp;height=21" scrolling="no" frameborder="0" allowTransparency="true" style="border:none; overflow:hidden; width:85px; height:21px;"></iframe></div><div
style="float:left; width:80px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;"> <g:plusone size="medium" href="http://davybrion.com/blog/2010/07/which-language-do-you-code-in/"></g:plusone></div><div
style="float:left; width:95px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;"> <a
href="http://twitter.com/share" class="twitter-share-button" data-url="http://davybrion.com/blog/2010/07/which-language-do-you-code-in/"  data-text="Which Language Do You Code In?" data-count="horizontal" data-via="davybrion"></a></div><div
style="float:left; width:105px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;"><script type="in/share" data-url="http://davybrion.com/blog/2010/07/which-language-do-you-code-in/" data-counter="right"></script></div><div
style="float:left; width:85px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;"><script src="http://www.stumbleupon.com/hostedbadge.php?s=1&amp;r=http://davybrion.com/blog/2010/07/which-language-do-you-code-in/"></script></div></div><div
style="clear:both"></div><div
style="padding-bottom:4px;"></div>]]></content:encoded> <wfw:commentRss>http://davybrion.com/blog/2010/07/which-language-do-you-code-in/feed/</wfw:commentRss> <slash:comments>12</slash:comments> </item> <item><title>Using The Dynamic Keyword To Avoid Difficulties With Generics</title><link>http://davybrion.com/blog/2010/07/using-the-dynamic-keyword-to-avoid-difficulties-with-generics/</link> <comments>http://davybrion.com/blog/2010/07/using-the-dynamic-keyword-to-avoid-difficulties-with-generics/#comments</comments> <pubDate>Fri, 16 Jul 2010 14:15:41 +0000</pubDate> <dc:creator>Davy Brion</dc:creator> <category><![CDATA[C#]]></category> <category><![CDATA[Code Quality]]></category><guid
isPermaLink="false">http://davybrion.com/blog/2010/07/using-the-dynamic-keyword-to-avoid-difficulties-with-generics/</guid> <description><![CDATA[A coworker was working on some kind of base EntityBuilder class to use in his tests.&#160; One of the requirements of the EntityBuilder class was that it would need to automatically set the ID of an entity to a ‘real’ value (as in: not the default value of the type).&#160; The EntityBuilder would use some [...]]]></description> <content:encoded><![CDATA[<p>A coworker was working on some kind of base EntityBuilder class to use in his tests.&#160; One of the requirements of the EntityBuilder class was that it would need to automatically set the ID of an entity to a ‘real’ value (as in: not the default value of the type).&#160; The EntityBuilder would use some kind of IdGenerator based on the type of the ID of the entity.&#160;&#160; First of all, the example i’m gonna show is highly simplified and might not look like it makes much sense, but it’s only to illustrate some C# stuff with regards to generics and the dynamic keyword.&#160; So bear with me, and just focus on the language details <img
src='http://d18sni7re4ly7f.cloudfront.net/blog/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /></p><p>Suppose you’ve got something like this:</p><div
style="font-family: consolas; background: white; color: black; font-size: 10pt"><p
style="margin: 0px">&#160;&#160;&#160; <span
style="color: blue">public</span> <span
style="color: blue">abstract</span> <span
style="color: blue">class</span> <span
style="color: #00008b">Entity</span>&lt;<span
style="color: #00008b">TId</span>&gt;</p><p
style="margin: 0px">&#160;&#160;&#160; {</p><p
style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span
style="color: blue">public</span> <span
style="color: blue">virtual</span> <span
style="color: #00008b">TId</span> <span
style="color: purple">Id</span> { <span
style="color: #008b8b">get</span>; <span
style="color: #008b8b">set</span>; }</p><p
style="margin: 0px">&#160;&#160;&#160; }</p><p
style="margin: 0px">&#160;</p><p
style="margin: 0px">&#160;&#160;&#160; <span
style="color: blue">public</span> <span
style="color: blue">interface</span> <span
style="color: #00008b">IIdGenerator</span>&lt;<span
style="color: #00008b">TId</span>&gt;</p><p
style="margin: 0px">&#160;&#160;&#160; {</p><p
style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span
style="color: #00008b">TId</span> <span
style="color: #008b8b">GenerateId</span>();</p><p
style="margin: 0px">&#160;&#160;&#160; }</p><p
style="margin: 0px">&#160;</p><p
style="margin: 0px">&#160;&#160;&#160; <span
style="color: blue">public</span> <span
style="color: blue">class</span> <span
style="color: #00008b">IntIdGenerator</span> : <span
style="color: #00008b">IIdGenerator</span>&lt;<span
style="color: blue">int</span>&gt;</p><p
style="margin: 0px">&#160;&#160;&#160; {</p><p
style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span
style="color: blue">private</span> <span
style="color: blue">static</span> <span
style="color: blue">int</span> <span
style="color: purple">lastIssuedId</span>;</p><p
style="margin: 0px">&#160;</p><p
style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span
style="color: blue">public</span> <span
style="color: blue">int</span> <span
style="color: #008b8b">GenerateId</span>()</p><p
style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; {</p><p
style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span
style="color: blue">return</span> ++<span
style="color: purple">lastIssuedId</span>;</p><p
style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; }</p><p
style="margin: 0px">&#160;&#160;&#160; }</p><p
style="margin: 0px">&#160;</p><p
style="margin: 0px">&#160;&#160;&#160; <span
style="color: blue">public</span> <span
style="color: blue">class</span> <span
style="color: #00008b">GuidIdGenerator</span> : <span
style="color: #00008b">IIdGenerator</span>&lt;<span
style="color: #00008b">Guid</span>&gt;</p><p
style="margin: 0px">&#160;&#160;&#160; {</p><p
style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span
style="color: blue">public</span> <span
style="color: #00008b">Guid</span> <span
style="color: #008b8b">GenerateId</span>()</p><p
style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; {</p><p
style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span
style="color: blue">return</span> <span
style="color: #00008b">Guid</span>.<span
style="color: #008b8b">NewGuid</span>();</p><p
style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; }</p><p
style="margin: 0px">&#160;&#160;&#160; }</p><p
style="margin: 0px">&#160;</p></div><p>The idea was to write the EntityBuilder somewhat along these lines:</p><div
style="font-family: consolas; background: white; color: black; font-size: 10pt"><p
style="margin: 0px">&#160;&#160;&#160; <span
style="color: blue">public</span> <span
style="color: blue">abstract</span> <span
style="color: blue">class</span> <span
style="color: #00008b">TestEntityBuilder</span>&lt;<span
style="color: #00008b">TEntity</span>, <span
style="color: #00008b">TId</span>&gt; <span
style="color: blue">where</span> <span
style="color: #00008b">TEntity</span> : <span
style="color: #00008b">Entity</span>&lt;<span
style="color: #00008b">TId</span>&gt;</p><p
style="margin: 0px">&#160;&#160;&#160; {</p><p
style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span
style="color: blue">public</span> <span
style="color: #00008b">TEntity</span> <span
style="color: #008b8b">Build</span>()</p><p
style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; {</p><p
style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span
style="color: blue">var</span> entity = <span
style="color: #008b8b">CreateEntityWithDefaultProperties</span>();</p><p
style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; entity.<span
style="color: purple">Id</span> = <span
style="color: #008b8b">GetIdGeneratorFor</span>(<span
style="color: blue">typeof</span>(<span
style="color: #00008b">TId</span>)).<span
style="color: #008b8b">GenerateId</span>();</p><p
style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span
style="color: blue">return</span> entity;</p><p
style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; }</p><p
style="margin: 0px">&#160;</p><p
style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span
style="color: blue">protected</span> <span
style="color: blue">abstract</span> <span
style="color: #00008b">TEntity</span> <span
style="color: #008b8b">CreateEntityWithDefaultProperties</span>();</p><p
style="margin: 0px">&#160;</p><p
style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span
style="color: blue">private</span> <span
style="color: #00008b">IIdGenerator</span>&lt;<span
style="color: #00008b">TId</span>&gt; <span
style="color: #008b8b">GetIdGeneratorFor</span>(<span
style="color: #00008b">Type</span> type)</p><p
style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; {</p><p
style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span
style="color: blue">if</span> (type <span
style="color: #008b8b">==</span> <span
style="color: blue">typeof</span>(<span
style="color: blue">int</span>))</p><p
style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; {</p><p
style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span
style="color: blue">return</span> <span
style="color: blue">new</span> <span
style="color: #00008b">IntIdGenerator</span>();</p><p
style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; }</p><p
style="margin: 0px">&#160;</p><p
style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span
style="color: blue">return</span> <span
style="color: blue">new</span> <span
style="color: #00008b">GuidIdGenerator</span>();</p><p
style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; }</p><p
style="margin: 0px">&#160;&#160;&#160; }</p><p
style="margin: 0px">&#160;</p></div><p>Of course, that doesn’t even compile… you’ll get the following compiler errors:</p><p>error CS0266: Cannot implicitly convert type 'MyProject.IntIdGenerator' to 'MyProject.IIdGenerator&lt;TId&gt;'. An explicit conversion exists (are you missing a cast?) <br
/>error CS0266: Cannot implicitly convert type 'MyProject.GuidIdGenerator' to 'MyProject.IIdGenerator&lt;TId&gt;'. An explicit conversion exists (are you missing a cast?)</p><p>So, how exactly do you get this working with generics? That’s when he asked for my help, and i didn’t know the answer either… i’ve struggled with this exact problem in a few previous situations and i never really got a clean solution either.&#160; But then i thought “wait, can’t we just avoid the problems with generics through the dynamic keyword?”</p><p>We changed the code to look like this:</p><div
style="font-family: consolas; background: white; color: black; font-size: 10pt"><p
style="margin: 0px">&#160;&#160;&#160; <span
style="color: blue">public</span> <span
style="color: blue">abstract</span> <span
style="color: blue">class</span> <span
style="color: #00008b">TestEntityBuilder</span>&lt;<span
style="color: #00008b">TEntity</span>, <span
style="color: #00008b">TId</span>&gt; <span
style="color: blue">where</span> <span
style="color: #00008b">TEntity</span> : <span
style="color: #00008b">Entity</span>&lt;<span
style="color: #00008b">TId</span>&gt;</p><p
style="margin: 0px">&#160;&#160;&#160; {</p><p
style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span
style="color: blue">public</span> <span
style="color: #00008b">TEntity</span> <span
style="color: #008b8b">Build</span>()</p><p
style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; {</p><p
style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span
style="color: blue">var</span> entity = <span
style="color: #008b8b">CreateEntityWithDefaultProperties</span>();</p><p
style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; entity.<span
style="color: purple">Id</span> = <span
style="color: #008b8b">GetIdGeneratorFor</span>(<span
style="color: blue">typeof</span>(<span
style="color: #00008b">TId</span>)).<span
style="color: #00008b">GenerateId</span>();</p><p
style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span
style="color: blue">return</span> entity;</p><p
style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; }</p><p
style="margin: 0px">&#160;</p><p
style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span
style="color: blue">protected</span> <span
style="color: blue">abstract</span> <span
style="color: #00008b">TEntity</span> <span
style="color: #008b8b">CreateEntityWithDefaultProperties</span>();</p><p
style="margin: 0px">&#160;</p><p
style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span
style="color: blue">private</span> <span
style="color: blue">dynamic</span> <span
style="color: #008b8b">GetIdGeneratorFor</span>(<span
style="color: #00008b">Type</span> type)</p><p
style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; {</p><p
style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span
style="color: blue">if</span> (type <span
style="color: #008b8b">==</span> <span
style="color: blue">typeof</span>(<span
style="color: blue">int</span>))</p><p
style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; {</p><p
style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span
style="color: blue">return</span> <span
style="color: blue">new</span> <span
style="color: #00008b">IntIdGenerator</span>();</p><p
style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; }</p><p
style="margin: 0px">&#160;</p><p
style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span
style="color: blue">return</span> <span
style="color: blue">new</span> <span
style="color: #00008b">GuidIdGenerator</span>();</p><p
style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; }</p><p
style="margin: 0px">&#160;&#160;&#160; }</p><p
style="margin: 0px">&#160;</p></div><p>We just changed the return type of the GetIdGeneratorFor method to ‘dynamic’, and the call to the GenerateId method is now a dynamic call instead of a normal method call.&#160; And it works.&#160; No messing around with generics voodoo, no (direct) usage of reflection either.&#160; Just clean code.</p><p>I’ll probably use this trick a lot more times in the future when i run into the limitations of generics <img
src='http://d18sni7re4ly7f.cloudfront.net/blog/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /></p><div
class="bottomcontainerBox" style=""><div
style="float:left; width:85px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;"> <iframe
src="http://www.facebook.com/plugins/like.php?href=http%3A%2F%2Fdavybrion.com%2Fblog%2F2010%2F07%2Fusing-the-dynamic-keyword-to-avoid-difficulties-with-generics%2F&amp;layout=button_count&amp;show_faces=false&amp;width=85&amp;action=like&amp;font=verdana&amp;colorscheme=light&amp;height=21" scrolling="no" frameborder="0" allowTransparency="true" style="border:none; overflow:hidden; width:85px; height:21px;"></iframe></div><div
style="float:left; width:80px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;"> <g:plusone size="medium" href="http://davybrion.com/blog/2010/07/using-the-dynamic-keyword-to-avoid-difficulties-with-generics/"></g:plusone></div><div
style="float:left; width:95px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;"> <a
href="http://twitter.com/share" class="twitter-share-button" data-url="http://davybrion.com/blog/2010/07/using-the-dynamic-keyword-to-avoid-difficulties-with-generics/"  data-text="Using The Dynamic Keyword To Avoid Difficulties With Generics" data-count="horizontal" data-via="davybrion"></a></div><div
style="float:left; width:105px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;"><script type="in/share" data-url="http://davybrion.com/blog/2010/07/using-the-dynamic-keyword-to-avoid-difficulties-with-generics/" data-counter="right"></script></div><div
style="float:left; width:85px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;"><script src="http://www.stumbleupon.com/hostedbadge.php?s=1&amp;r=http://davybrion.com/blog/2010/07/using-the-dynamic-keyword-to-avoid-difficulties-with-generics/"></script></div></div><div
style="clear:both"></div><div
style="padding-bottom:4px;"></div>]]></content:encoded> <wfw:commentRss>http://davybrion.com/blog/2010/07/using-the-dynamic-keyword-to-avoid-difficulties-with-generics/feed/</wfw:commentRss> <slash:comments>15</slash:comments> </item> <item><title>Check Out QuickGenerate</title><link>http://davybrion.com/blog/2010/06/check-out-quickgenerate/</link> <comments>http://davybrion.com/blog/2010/06/check-out-quickgenerate/#comments</comments> <pubDate>Wed, 30 Jun 2010 07:05:38 +0000</pubDate> <dc:creator>Davy Brion</dc:creator> <category><![CDATA[C#]]></category> <category><![CDATA[Code Quality]]></category> <category><![CDATA[Software Development]]></category> <category><![CDATA[testing]]></category><guid
isPermaLink="false">http://davybrion.com/blog/2010/06/check-out-quickgenerate/</guid> <description><![CDATA[One of several interesting things in Mark Meyers’ QuickNet project is the whole input generation thing that you need for property-based testing.&#160; It turns out that those input generators are very usable for far more purposes than just property-based testing, so it’s evolved into its own library.&#160; It can generate object instances of almost any [...]]]></description> <content:encoded><![CDATA[<p>One of several interesting things in Mark Meyers’ <a
href="http://code.google.com/p/quicknet/" target="_blank">QuickNet</a> project is the whole input generation thing that you need for property-based testing.&#160; It turns out that those input generators are very usable for far more purposes than just property-based testing, so it’s evolved into its own library.&#160; It can generate object instances of almost any kind, while you can still have fine-grained control over the generation if you want to.&#160; You can use it for simple types, complex objects or even entire object graphs. I wish i had time to write a more in-depth post about this, but for now i’m just gonna point you guys in the right direction, and i hope that you’ll see the value in this <img
src='http://d18sni7re4ly7f.cloudfront.net/blog/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /></p><p>The announcement of the first release can be found <a
href="http://kilfour.wordpress.com/2010/06/29/quickgenerate-0-1-released/" target="_blank">here</a>, and an example can be found <a
href="http://kilfour.wordpress.com/2010/06/29/quickgenerate-example/" target="_blank">here</a>.&#160; Here’s a little glimpse at the code of one the examples:</p><p><a
href="http://davybrion.com/pictures/CheckOutQuickGenerate_7FE6/quickgenerate.png" rel="prettyPhoto[2363]"><img
style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="quickgenerate" border="0" alt="quickgenerate" src="http://davybrion.com/pictures/CheckOutQuickGenerate_7FE6/quickgenerate_thumb.png" width="653" height="500" /></a></p><p>I think that piece of code is a nice illustration of how powerful and flexible this is <img
src='http://d18sni7re4ly7f.cloudfront.net/blog/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /></p><div
class="bottomcontainerBox" style=""><div
style="float:left; width:85px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;"> <iframe
src="http://www.facebook.com/plugins/like.php?href=http%3A%2F%2Fdavybrion.com%2Fblog%2F2010%2F06%2Fcheck-out-quickgenerate%2F&amp;layout=button_count&amp;show_faces=false&amp;width=85&amp;action=like&amp;font=verdana&amp;colorscheme=light&amp;height=21" scrolling="no" frameborder="0" allowTransparency="true" style="border:none; overflow:hidden; width:85px; height:21px;"></iframe></div><div
style="float:left; width:80px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;"> <g:plusone size="medium" href="http://davybrion.com/blog/2010/06/check-out-quickgenerate/"></g:plusone></div><div
style="float:left; width:95px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;"> <a
href="http://twitter.com/share" class="twitter-share-button" data-url="http://davybrion.com/blog/2010/06/check-out-quickgenerate/"  data-text="Check Out QuickGenerate" data-count="horizontal" data-via="davybrion"></a></div><div
style="float:left; width:105px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;"><script type="in/share" data-url="http://davybrion.com/blog/2010/06/check-out-quickgenerate/" data-counter="right"></script></div><div
style="float:left; width:85px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;"><script src="http://www.stumbleupon.com/hostedbadge.php?s=1&amp;r=http://davybrion.com/blog/2010/06/check-out-quickgenerate/"></script></div></div><div
style="clear:both"></div><div
style="padding-bottom:4px;"></div>]]></content:encoded> <wfw:commentRss>http://davybrion.com/blog/2010/06/check-out-quickgenerate/feed/</wfw:commentRss> <slash:comments>1</slash:comments> </item> </channel> </rss>
<!-- Performance optimized by W3 Total Cache. Learn more: http://www.w3-edge.com/wordpress-plugins/

Minified using disk: basic
Page Caching using disk: enhanced
Database Caching 2/74 queries in 0.041 seconds using disk: basic
Object Caching 1557/1708 objects using disk: basic
Content Delivery Network via Amazon Web Services: CloudFront: d18sni7re4ly7f.cloudfront.net

Served from: davybrion.com @ 2012-05-23 13:46:29 -->
