<?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>Sun, 29 Jan 2012 10:48:12 +0000</lastBuildDate> <language>en</language> <sy:updatePeriod>hourly</sy:updatePeriod> <sy:updateFrequency>1</sy:updateFrequency> <generator>http://wordpress.org/?v=3.3.1</generator> <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" style="border:none; overflow:hidden; width=85px; height:21px;" allowTransparency="true"></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">Tweet</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>17</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" style="border:none; overflow:hidden; width=85px; height:21px;" allowTransparency="true"></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">Tweet</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" style="border:none; overflow:hidden; width=85px; height:21px;" allowTransparency="true"></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">Tweet</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" style="border:none; overflow:hidden; width=85px; height:21px;" allowTransparency="true"></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">Tweet</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>23</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" style="border:none; overflow:hidden; width=85px; height:21px;" allowTransparency="true"></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">Tweet</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" style="border:none; overflow:hidden; width=85px; height:21px;" allowTransparency="true"></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">Tweet</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" style="border:none; overflow:hidden; width=85px; height:21px;" allowTransparency="true"></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">Tweet</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" style="border:none; overflow:hidden; width=85px; height:21px;" allowTransparency="true"></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">Tweet</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>24</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" style="border:none; overflow:hidden; width=85px; height:21px;" allowTransparency="true"></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">Tweet</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" style="border:none; overflow:hidden; width=85px; height:21px;" allowTransparency="true"></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">Tweet</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" style="border:none; overflow:hidden; width=85px; height:21px;" allowTransparency="true"></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">Tweet</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" style="border:none; overflow:hidden; width=85px; height:21px;" allowTransparency="true"></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">Tweet</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" style="border:none; overflow:hidden; width=85px; height:21px;" allowTransparency="true"></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">Tweet</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" style="border:none; overflow:hidden; width=85px; height:21px;" allowTransparency="true"></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">Tweet</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>93</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" style="border:none; overflow:hidden; width=85px; height:21px;" allowTransparency="true"></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">Tweet</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" style="border:none; overflow:hidden; width=85px; height:21px;" allowTransparency="true"></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">Tweet</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" style="border:none; overflow:hidden; width=85px; height:21px;" allowTransparency="true"></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">Tweet</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> <item><title>Why You Shouldn&#8217;t Expose Your Entities Through Your Services</title><link>http://davybrion.com/blog/2010/05/why-you-shouldnt-expose-your-entities-through-your-services/</link> <comments>http://davybrion.com/blog/2010/05/why-you-shouldnt-expose-your-entities-through-your-services/#comments</comments> <pubDate>Mon, 17 May 2010 15:18:43 +0000</pubDate> <dc:creator>Davy Brion</dc:creator> <category><![CDATA[Architecture]]></category> <category><![CDATA[Code Quality]]></category> <category><![CDATA[Opinions]]></category> <category><![CDATA[Performance]]></category> <category><![CDATA[WCF]]></category><guid
isPermaLink="false">http://davybrion.com/blog/?p=2318</guid> <description><![CDATA[I sometimes still get questions from people who want to expose their entities through their WCF Services.&#160; Regardless of whether these are entities that are populated through NHibernate or any other ORM, this is just not a good thing to do.&#160; Many people prefer to accept and return entities through their services because they believe [...]]]></description> <content:encoded><![CDATA[<p>I sometimes still get questions from people who want to expose their entities through their WCF Services.&#160; Regardless of whether these are entities that are populated through NHibernate or any other ORM, this is just not a good thing to do.&#160; Many people prefer to accept and return entities through their services because they believe this is an easier programming model.&#160; They believe that it takes less work than mapping to DTO’s and that as a whole, this solution is much more manageable.&#160; Rest assured that this is a fallacy.&#160; Any perceived benefit that you’ll get from exposing entities outside of your service layer will only last a <em>very short time</em> and will quickly be dwarfed by added complexity, increased maintenance overhead and a performance overhead which must not be ignored.&#160;</p><p>In this post, i’d like to take the chance to explain the downsides to exposing entities through services.&#160; Though i’ll probably miss quite a few of the downsides (feel free to add to the list through comments), the ones i will mention are IMO important enough to take note of.</p><p><strong>Exposing entities to clients means your clients are very tightly coupled to your service(s)</strong></p><p>Entities are a part of your domain.&#160; These entities in your domain can change for various reasons.&#160; Sometimes because functional changes are required, but quite often also for optimizations (whether they are for performance reasons or to improve the clarity and maintainability of your domain).&#160; Functional changes <em>can </em>impact your clients, though that is not necessarily the case.&#160; Optimizations hardly ever have an impact on your clients (other than possibly improved response times from your service calls obviously).&#160; If your service layer accepts and returns domain entities, each possible change is highly likely to have an impact on your clients.&#160; And this impact is not cheap.&#160; In the best case scenario, it means updating your service contracts, regenerating your service proxies and redeploying your clients.&#160; In the worst case scenario, it means making actual changes to the code of your clients.&#160; And for what? Because of changes that shouldn’t have impacted your clients in the first place?</p><p>Ideally, your clients are as dumb as they can be.&#160; They should know as little as possible about the actual <em>implementation</em> of the domain because that implementation is simply not relevant to them.&#160; They should present users with data and give them the option to modify that data, to trigger actions and to perform certain tasks.&#160; They should focus squarely on those tasks and pretty much everything else is typically better suited to be done behind your service layer.&#160; If you build your clients with no real knowledge of the actual domain model, but of DTO’s and possible actions to be performed then you can reduce the level of coupling between your clients and your services substantially.</p><p>Many of the people who prefer to expose entities often claim that going for the DTO approach introduces too much extra work and too many extra, seemingly unnecessary classes.&#160; For starters, they don’t want to write code that maps entities to DTO’s.&#160; First of all, the amount of code that this requires is in reality <em>very small</em>, not to mention <em>very easy</em>.&#160; Secondly, you can just as well use a library such as AutoMapper to take that pain away from you.&#160; And contrary to what you might think, there is a big performance gain to be had from returning DTO’s over entities, but i’ll get to that in the next section.</p><h5></h5><h5></h5><p><strong>Entities are hardly ever the most optimal representation of data</strong></p><p>I think we can safely say that most applications need to show data in the following 3 ways:</p><ul><li>In a grid view, either as a total listing of all instances of a certain type of data or the result of a search query or some kind of filtering action</li><li>In dropdown controls or anything else that lets users select pieces of data</li><li>In edit screens where a piece of data needs to be displayed in its entirety, perhaps even to be modified by the user</li></ul><p>There are undoubtedly more ways in which data can be presented to the user but i think it’s safe to say that most business applications will certainly rely on the following 3 ways quite heavily.</p><p>In the case of a grid view, you’re frequently showing data that is related to more than one entity.&#160; You’ll often need to include the name or the description of some associated entities.&#160; So what exactly is it that you want to do in this situation?&#160; Do you want to return a list of the main entities of the grid view, which all have their required association properties filled in so you can display the columns that you need in the grid view?&#160; Do you actually need all of the properties of these entities (for both the main entities and the associated entities)?&#160; Odds are high that you’re going to be returning a lot more data to the client than you actually need.&#160; And that is what is realistically going to hurt the performance of your system.&#160; Any piece of unnecessary data that you transmit to your clients has a cost associated with it.&#160; The unnecessary data is retrieved from the database.&#160; The entities are then serialized at the service end.&#160; Then they are transmitted to the client.&#160; Then they are deserialized by your client.&#160; All of this is pretty costly, so the more unnecessary data that is included in this operation, the more your performance and the responsiveness of your client (not to mention your database and your server) is impacted negatively.</p><p>In the case of dropdown controls or anything else that lets users select pieces of data, you typically only need very few of the properties of that piece of data.&#160; In many cases, the primary key and a name or a description are sufficient.&#160; Do you really need to transmit the entire entity every time for usages like this? Again, keep in mind that all of that extra data that will never be used by your client needs to be retrieved, serialized, transmitted and deserialized again.&#160; Surely, this is an awful waste, no?&#160;</p><p>And then there’s the case where a piece of data needs to be displayed in its entirety.&#160; In these cases, you will almost always need all of the properties of the entity that is displayed, but you’ll most often also need to show other data (things that can be selected, or linked to the main entity).&#160; This other data will in most cases fall into the previous category where you’ll only need very little information about the actual entity.&#160; If you’re smart, you’ve chosen the DTO approach to retrieve this data for the data that can be selected, and in that case, you already have all of the infrastructural code in place to project entities or data into DTO’s.&#160; So you might as well reuse it for the main entity as well since you already have the capability to do this.</p><p>Always keep in mind that your entities will frequently either contain <em>more data than needed</em>, or <em>less data than needed</em>.&#160; As such, it just doesn’t make much sense to expose entities to your clients since they are hardly ever optimal for client-side usage.&#160; If you really want to think about performance, stop worrying about the supposed cost of mapping to DTO’s (which is truly negligible) and start focusing on <em>what</em> your actually <em>sending</em> to and from your service because this is far more costly than any kind of DTO-mapping really is.</p><p><strong>Must your data really come from entities?</strong></p><p>If you are displaying data to your user, does that data really need to come from your domain model?&#160; Does it really need to be retrieved by populating a collection of entities to then return them to the client?&#160; Again, keep the <em>form</em> of the data in mind when thinking about this.&#160; In many cases, as i mentioned above, an entity is not the most optimal form of the data that your client needs.&#160; So why even retrieve it through entities? Sure, asking your ORM to retrieve a set of entities based on a set of criteria is often the easiest thing to do, but if the easiest path were the best path, the overall quality of software projects wouldn’t be in the sad state that it’s in today.&#160; If the form of the required data is not identical to the structure of an entity, it’s often far more optimal to simply populate a DTO <em>directly from the data.</em>&#160; With NHibernate, you can easily do this by adding a list of projections to your query and then using a ResultTransformer to populate the DTO’s based on the direct output of the query.&#160; In this case, no entity instance ever needs to be created when you’re just retrieving data, and no extra mapping between the entity and the DTO’s needs to be performed.&#160; Your data access code simply retrieves the resulting data from a query, and puts that data directly in your DTO’s.&#160; There’s no reason why usage of an ORM should prevent you from doing this.&#160;&#160; Once again, this approach will offer far more performance benefits than avoiding DTO mapping at all costs ever can.</p><p><strong>What about the behavior of your entities?</strong></p><p>Do your entities have any behavior in them?&#160; If not, they are already more of a DTO than a true entity.&#160; In fact, if your entities have no behavior at all, you could even wonder why you’re using an ORM in the first place.&#160; Now, behavior can mean many things.&#160; It could mean lazy loading of associations.&#160; It could mean actual business logic.&#160; Obviously, lazy-loading doesn’t (and shouldn’t!) work client-side, but what about your business logic? Do you have business logic that <em>can </em>be executed client-side? Or is it business logic that should only be executed behind the service layer? If so, how do you make the distinction between this to prevent client-side usage from these entities? Whatever you do, you’re pretty much opening up a can of worms that really is better avoided in the first place.</p><p><strong>How are you going to deal with technical issues?</strong></p><p>Accepting and returning entities from services introduces a host of technical issues that can be quite substantial.&#160; Serialization and deserialization specifically are issues that you need to be worried about.&#160; If you’re using an ORM which does lazy-loading of associations, this will certainly cause serialization issues that you need to work around.&#160; You can either disable lazy loading, or you can make sure that your entities are always fully initialized (as in: always have their associations fully loaded) before they are sent back to the client.&#160; Disabling lazy-loading <em>will </em>cause performance problems in your service layer, either in places where you don’t expect them to be or in places that you haven’t thought of before it’s too late.&#160; Fully loading your entities and their associates before returning them is another performance nightmare waiting to happen so that’s really not an ideal solution either.&#160; You can try to hook into the serialization process or even the lazy-loading features of your ORM but whatever you do in that case will be a hack that <em>will</em> cause issues sooner or later.&#160; And again, all of these problems can very easily be avoided with a solution which, i hope you realize by now, offers plenty more benefits than any solution where you accept/return entities in your service.</p><p><strong>Conclusion</strong></p><p>Every single downside to exposing entities through services are issues that i have myself encountered in past projects, either ones i’ve worked on myself, or ones that i’ve seen other people work on.&#160; If that’s not enough for you, then maybe you’ll find it interesting to know that some of the brightest and most respected people (like Udi Dahan and Ayende for instance) in the .NET community also actively recommend against exposing entities through services because of the same downsides that i mentioned, though they could probably give you even more downsides that i forgot to cover in this post.&#160; These downsides are not figments of anyone’s imagination.&#160; They are very real, and you really, really ought to think twice before dismissing this advice.&#160;</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%2F05%2Fwhy-you-shouldnt-expose-your-entities-through-your-services%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" style="border:none; overflow:hidden; width=85px; height:21px;" allowTransparency="true"></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/05/why-you-shouldnt-expose-your-entities-through-your-services/"></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/05/why-you-shouldnt-expose-your-entities-through-your-services/"  data-text="Why You Shouldn&rsquo;t Expose Your Entities Through Your Services" data-count="horizontal" data-via="davybrion">Tweet</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/05/why-you-shouldnt-expose-your-entities-through-your-services/" 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/05/why-you-shouldnt-expose-your-entities-through-your-services/"></script></div></div><div
style="clear:both"></div><div
style="padding-bottom:4px;"></div>]]></content:encoded> <wfw:commentRss>http://davybrion.com/blog/2010/05/why-you-shouldnt-expose-your-entities-through-your-services/feed/</wfw:commentRss> <slash:comments>26</slash:comments> </item> <item><title>What Does This Show?</title><link>http://davybrion.com/blog/2010/01/what-does-this-show/</link> <comments>http://davybrion.com/blog/2010/01/what-does-this-show/#comments</comments> <pubDate>Wed, 06 Jan 2010 13:27:15 +0000</pubDate> <dc:creator>Davy Brion</dc:creator> <category><![CDATA[Code Quality]]></category><guid
isPermaLink="false">http://davybrion.com/blog/2010/01/what-does-this-show/</guid> <description><![CDATA[This (partial) screenshot shows some interesting data.&#160; The full screenshot would make things more clear, but where’s the fun in that? Who can tell me what data is being shown here? Tweet]]></description> <content:encoded><![CDATA[<p><a
href="http://davybrion.com/blog/wp-content/uploads/2010/01/Capture.png" rel="prettyPhoto[2161]"><img
style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="Capture" border="0" alt="Capture" src="http://davybrion.com/blog/wp-content/uploads/2010/01/Capture_thumb.png" width="644" height="409" /></a></p><p>This (partial) screenshot shows some interesting data.&#160; The full screenshot would make things more clear, but where’s the fun in that? Who can tell me what data is being shown here?</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%2F01%2Fwhat-does-this-show%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" style="border:none; overflow:hidden; width=85px; height:21px;" allowTransparency="true"></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/01/what-does-this-show/"></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/01/what-does-this-show/"  data-text="What Does This Show?" data-count="horizontal" data-via="davybrion">Tweet</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/01/what-does-this-show/" 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/01/what-does-this-show/"></script></div></div><div
style="clear:both"></div><div
style="padding-bottom:4px;"></div>]]></content:encoded> <wfw:commentRss>http://davybrion.com/blog/2010/01/what-does-this-show/feed/</wfw:commentRss> <slash:comments>10</slash:comments> </item> <item><title>Don&#8217;t Strive For Perfection</title><link>http://davybrion.com/blog/2010/01/dont-strive-for-perfection/</link> <comments>http://davybrion.com/blog/2010/01/dont-strive-for-perfection/#comments</comments> <pubDate>Mon, 04 Jan 2010 20:38:05 +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=2155</guid> <description><![CDATA[A mistake that you commonly see developers make (especially young ones) is to try to achieve perfection when they need to design something.&#160; Whether it’s just a reusable base class, a component, or even a small library or framework, a lot of people get too caught up in details that don’t really matter in most [...]]]></description> <content:encoded><![CDATA[<p>A mistake that you commonly see developers make (especially young ones) is to try to achieve perfection when they need to design something.&#160; Whether it’s just a reusable base class, a component, or even a small library or framework, a lot of people get too caught up in details that don’t really matter in most cases.</p><p>It is understandable though, and i think most developers have gone down that path quite a few times in their careers.&#160; Especially early on.&#160; You know how it goes… you need to create something that is going to be reused by others, and you want to make sure that it is just perfect.&#160; That nobody can say anything bad about it.&#160; That everyone will agree without discussion that that piece of code is simply great.</p><p>So a lot of people in that situation start thinking about things like:</p><ul><li>Shouldn’t i seal this class? Nobody’s ever going to need to derive from this because i’ve left plenty of other extensibility points</li><li>Shouldn’t i seal this method? After all, nobody should ever change the way this particular piece of code works</li><li>This class will never be used by anyone outside of this assembly, so i probably should make it internal, right?</li><li>This particular method will be a bottleneck so i should really make it as fast as i can</li><li>Whenever i can pull some common logic in a base class, or introduce more base classes i should do so!</li><li>Etc…</li></ul><p>The reality of the situation is that despite your best intentions, focusing too much on details like that will quite frequently lead to very inflexible code that a lot of people will find hard or annoying to use.&#160; Unless you are very experienced with this kind of stuff (and for the record, i’m not saying that i am) you’re very likely to get these decisions wrong if you think about them up front so it really isn’t worth spending so much time on ‘details’ like that.&#160; In fact, the best thing to do is often to keep things as simple as possible until you actually have a reason to make them more complicated.&#160; Making things more complicated than they need to be in advance never works, and you’re probably going to over-complicate things in places where it turns out not to matter.&#160; If you’re really unlucky, that will actually make it harder to modify or extend other parts that over time really do need to be modified or extended in some ways.</p><p>Generally speaking, i think you’re better off focusing on the following goals/principles:</p><ul><li>Avoid writing classes that are <a
href="http://davybrion.com/blog/2009/10/slutty-types/" target="_blank">slutty</a></li><li>Make sure that your consumers primarily communicate with your classes through interfaces.&#160; Though you don’t need to put everything behind an interface either… pretty much anything that people might need/want to change in some way typically are good candidates.</li><li>Use Dependency Injection so implementations can easily be switched with others</li><li>Use virtual methods unless you can think of a really good reason not to</li><li>Don’t make your classes internal unless you can think of a good reason to do so (and keep in mind that we can still do whatever we want with them through reflection, and will do so if that turns out to be the best way to get something working the way we need it to if you failed to provide proper extension points)</li><li>Do not seal classes unless you can think of a really good reason to do so</li><li>Do not worry about performance up front, unless for those places where you are going out-of-process (remote services, databases, file systems, etc…)</li><li>Keep your classes small and focused</li><li>Learn about the SOLID principles, and apply them. Keep in mind that going for 100% SOLID code is typically not worth it either.&#160; Go for the 80/20 rule here.</li></ul><p>If you keep those things in mind, you will typically end up with code that is flexible to use, and easy to change.</p><p>Obviously, all of this assumes that you are in a position where you can go back to the code and make changes.&#160; If you’re releasing frameworks/libraries/components that will be used by a lot of people and can’t afford to break backwards compatibility, then you probably need to be more strict about these things because then you can’t always just go back to change something.&#160; I don’t think it’s a stretch to claim that most developers are not in this situation however, so most of us often don’t need to waste time thinking about those things in advance <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%2F01%2Fdont-strive-for-perfection%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" style="border:none; overflow:hidden; width=85px; height:21px;" allowTransparency="true"></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/01/dont-strive-for-perfection/"></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/01/dont-strive-for-perfection/"  data-text="Don&rsquo;t Strive For Perfection" data-count="horizontal" data-via="davybrion">Tweet</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/01/dont-strive-for-perfection/" 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/01/dont-strive-for-perfection/"></script></div></div><div
style="clear:both"></div><div
style="padding-bottom:4px;"></div>]]></content:encoded> <wfw:commentRss>http://davybrion.com/blog/2010/01/dont-strive-for-perfection/feed/</wfw:commentRss> <slash:comments>9</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 3/79 queries in 0.042 seconds using disk: basic
Object Caching 1564/1731 objects using disk: basic
Content Delivery Network via Amazon Web Services: CloudFront: d18sni7re4ly7f.cloudfront.net

Served from: davybrion.com @ 2012-02-08 05:05:22 -->
