Friday, May 23, 2014

SafeSubstring Extension Method

Extension methods are a great way to keep you’re view code tight and readable.  I always include a UIExtensionMethods class in my projects that contains extensions for the HtmlHelper and for my View Model classes.

The Problem

I often want to restrict the max number of characters that will display in the UI.  If a field has 2000 characters, I just want to show the first 100.  Easily done right?  Just use a substring like so:

<div> @Model.JobSummary.Substring(0, 300) <a href="#" class="empub_feed_readmore_link">read more...</a> </div>

The problem is that there are a number of things that will make Substring throw errors.  If JobSummary is null, error.  If JobSummary has less than 300 characters, error.  I can check for these things in my view code, but that’s going to make my view look messy and I’ll have to copy and paste that code every time I do a substring in a view.

A Quick Solution

Anytime I have view code that needs to be used more than once, or even hurts the readability of my view, I extract that code into an extension method.  Since I want a version of Substring that I can run in a view without throwing an error, I call the method SafeSubstring.

// SafeSubstring public static MvcHtmlString SafeSubstring(this HtmlHelper htmlHelper, string text, int start, int stop) { if (string.IsNullOrEmpty(text) || text.Length < (start + stop)) { return new MvcHtmlString(text); } return new MvcHtmlString(text.Substring(start, stop)); }

Now my view code looks clean, and I have another tool in my toolbox that can be used next time

<div> @Html.SafeSubstring(Model.JobSummary, 0, 300) <a href="#" class="empub_feed_readmore_link">read more...</a> </div>

Sunday, March 30, 2014

Smart Guy Disease

nerd_dog1

As a consultant I’ve had the opportunity to see first-hand how software development works at some of the most cutting-edge .Net shops in the Denver area.  One of the things I’ve seen over and over is a phenomenon I call “Smart Guy Disease”.

The basic concept is this.  The biggest, most destructive mistakes are always made by the “smart” programmers, not the “dumb” programmers.   The smarter the programmer, the greater the capacity for catastrophe.

It seems counter-intuitive, but it’s true.  Think about it for a minute.  “Dumb” programmers…. actually I have to stop a moment because I don’t really like the term dumb programmers.  One of the reasons I like software development is that I consistently get to work with smart people.  Even programmers who aren’t up on the latest technologies and are just showing up to do their job every day tend to be very intelligent people.   However, I think we all have worked with people who just weren’t up to the task.  They consistently ship code rife with bugs, you have to code review every line they commit with a fine tooth comb, they just aren’t very good at programming and they consistently produce bad code.  Bad programmers might be a better term, but I’ll keep using “dumb” because it contrasts well with smart.

Anyway, “dumb” programmers do produce crappy code, but they almost never make the kind of massive mistakes that cripple an entire organization’s ability to ship software.  They may implement features that perform poorly, but they don’t deploy code that destroys performance on a global scale.   Nope, when you want to cause that kind of damage, you need a smart guy. 

I’ve seen it.  It happens.  The smartest guys in an organization are the ones that make the truly big mistakes.

Shipping architecture instead of software

The first mistake I’ve seen is shipping architecture instead of software.  Companies take the smartest guys in the organization and tell them that they’re architects now and they are no longer responsible for shipping an actual application. Instead they will create a company-wide enterprise architecture, or Core Framework,  that other app development teams, who do ship production applications, will be required to build on top of.

I’ll go into more detail on why this is a bad idea in a later post, but for now just know that in this situation the incentives of the architects and the app developers are not aligned.  The architects’ priority is to create architecture, something that implements cutting edge technologies, looks great in diagrams, is impressive when presented to C level executives, and if it’s overly complex… well that just demonstrates how smart they are.   The app development team’s priority is to produce code that performs well, is easy to maintain, and ships on time.  The architects really have no idea if their designs are easy to implement or perform well until they are implemented by the app team.  Not a good way to ship code.

Overly complex solutions

Another common problem, that I alluded to above, is overly complex solutions.  You might be tempted to dismiss this one as no big deal.  Don’t.  This is probably the most common and most damaging mistake that I’ve seen in the real world.  Smart programmers usually like to show how smart they are.  You can’t really do that if you produce code that is easy to understand and maintain.  Why implement a simple solution when you can do something clever instead? 

So what’s the cost of extra complexity? If you look only at the first 9 months of an application’s lifecycle then the answer is “not much”.  However, if your application is successful and has a lifecycle that extends beyond the first year then that extra complexity becomes a tax that you pay over and over, every time someone touches that code base.  That’s the real problem.  The price for additional complexity isn’t just paid by that initial developer, it’s paid again and again by every developer who touches that code for the entire lifetime of the application.  It’s far too common for smart developers to ship a new product with needlessly complex architectures, then declare the project a success and move on, leaving a maintenance nightmare for the “average” developers who come after them.  

Complexity also leads to brittle code.  We all understand intuitively that the more complex something is, the more likely something will go wrong and it will break. That’s bad enough by itself. Now think a year down the road when that complex system is being modified by a developer who doesn’t necessarily understand the intent of the original “smart” programmer. Now you’ve got a high probability that something will get broken.  

The crazy thing is that teams sometimes look at the complexity of their code as a badge of honor.  If you ever catch yourself saying something like “We are so cutting edge that we can only hire the best developers, and even then it takes them a good 4 months before they’re productive with our architecture”…. maybe you should ask yourself if that’s really a good thing.  

Smart on paper, disaster in reality

One last mistake, solutions that look great on paper but are a complete disaster when implemented in the real world.  The best example I’ve seen of this was when a company decided that they wanted to rewrite their ASP.Net WebForms applications so that they could be managed with a 3rd party CMS.  The idea was that the WebForms pages were mostly made up of .ascx controls anyway, so it should be possible to make every .ascx responsible for loading and saving it’s own data, then publish that data to and coordinate with the other controls on the page at runtime.  These individual controls could then be composited together in any combination by designers or business people using the CMS. There was some kind of limitation with the CMS that required all of the heavy lifting to be done in the browser with JavaScript and Ajax.  Did I mention this was WebForms code with update panels and all that nonsense. Remember how fun it was to do real JavaScript and manage DOM Ids browser-side with update panels?

To be fair, it’s been a while and I don’t really remember the details.  I just remember that the big brains decided this made sense, and I’m sure it did make sense in a high-level planning meeting.  But, every hands-on-keyboard developer who worked with those apps immediately recognized that this was a terrible idea.  Every developer who actually shipped code could see that even if a miracle happened and this idea worked, it would make the code much, much harder to maintain and it would slow development to a crawl.  It did by the way.

How to avoid smart guy disease

So what’s the point?  Is this just a rant because I hate smart people?  No of course not.  I like smart people and I like working with smart people.   The point is that it’s possible, even common, for the smartest developers, who should be our greatest asset, to instead create massive problems.  But it doesn’t have to be that way.

I have 2 simple rules that can help prevent smart guy disease from crippling your organization.

Rule 1.  Make sure your smartest developers are always in a role where they are shipping production code. 

Most of the problems mentioned above happened when the smartest developers became disconnected from the reality of building and maintaining production software.  That disconnect messes up the incentives and puts your smartest programmers at odds with the programmers who actually ship code.

Instead, keep your best and brightest developers embedded in teams that are shipping production applications.  Let them be a team leader or a team member.  Give each application team their own architect. Or, if they can’t be a permanent team member, at least let them be a temporary resource embedded inside the team. They can work hands-on-keyboard with the other developers to actually implement their architectural designs.  That kind of hands on experience will help everyone involved and will keep those incentives aligned.

Rule 2. Value simplicity. 

Make simplicity a cultural value, a goal that every developer strives to attain.  Make it clear that simple solutions are valued and needlessly complex solutions won’t be tolerated.  Keep a close eye on any developers who want to use multiple layers of base classes, Unity Interceptors, or other techniques that are used to make things happen automagically.  

Never, ever boast that your architecture is so complex that only the very best developers can work on it.  Instead your boast should be that your architecture is so well designed that any junior developer can come in off the street, understand the basics in a day or two, and be productive within the week.

Wednesday, December 19, 2012

NHibernate WCF Error: HTTP request context being aborted by the server??

I’ve been ambivalent toward ORMs for quite some time now, but I’m really starting to dislike NHibernate in a special way.  My experience has been that ORMs lead to a lot of wasted time troubleshooting code problems that are really ORM problems.  Here’s one example.

I recently got this mysterious and unhelpful error message on an ASP.Net MVC3 web app that was pulling data via a WCF web service, which in turn was using NHibernate for persistence.

An error occurred while receiving the HTTP response to http://localhost:8080/JobsService/ws. This could be due to the service endpoint binding not using the HTTP protocol. This could also be due to an HTTP request context being aborted by the server (possibly due to the service shutting down). See server logs for more details.

Ok, my service endpoint was definitely using HTTP and none of that other stuff was happening either.  So what was the problem?  NHibernate lazy load proxies.

Let’s say I have a Company entity that contains a child collection of type List<Job> as shown in the diagram below.  So if we look at the Company entity, all of the fields (Name, State, City) exist in my data table, except for the Jobs.  Jobs represents a relation between my Company and Job tables and to get Job data NHibernate has to query the Job table.

image

At this point it’s important to note that I’m using NHibernate, all of my entity properties are virtual, and I have lazy loading enabled.  So what happens when I run a query to get a Company? What data does NHibernate populate?  It’s going to populate all of the data that’s in the Company table (Name, State, City) , but it’s not going to populate the Jobs collection.  It’s going replace that virtual property with a proxy that will execute a query to get Jobs only when that property is accessed. 

I actually think this lazy loading proxy technique is pretty neat and it’s technically impressive.  Unfortunately it’s also the root cause of a lot of application errors.

So the lazy loading proxy works great when we’re accessing an entity directly in our web app while it’s still has the context of the NHibernate session, but what happens when we try to return our Company over WCF and WCF tries to serialize that Jobs property that hasn’t been lazy loaded yet?  That’s right, you get the ambiguous error message above. 

The fix is simple.  You just need to eager load the Jobs. You can do this any number of ways.  Here’s how to do it in a criteria query.

return session.CreateCriteria<Company>()
            .Add(Restrictions.Eq("Id", _Id))
            .SetFetchMode("Jobs", FetchMode.Eager);

Now that we’re eager loading the Jobs there’s real data there instead of the lazy load proxy, WCF has no problem serializing the Jobs, and our mysterious ambiguous error goes away. 

So, I hope this saves someone a little time, and please remember, friends don’t let friends use ORMs.

Wednesday, July 18, 2012

The problem with ORMs

pigdogOver the last 8 years I’ve done a lot of thinking and experimenting with different persistence models. If you’d asked me 6 years ago what a persistence layer should look like I would have whole heartedly suggested an ORM like nHibernate.  Linq to SQL came along and initially looked promising but I quickly soured on it in favor of Entity Framework.  Then I actually tried to use Entity Framework in a production app and quickly found that in spite of the initial query writing efficiencies, it caused problems in other areas and the net result was that it didn’t save me any time at all but did add limitations and complexity to my app. 

So what was the problem?  As I spoke with more developers I started to hear the same complaints, even though some were using EF, some were using nHibernate, others were using LinqToSql.  I heard the problem stated best by a guy I met at the speaker’s dinner for the Rocky Mountain Tech Trifecta.  I can’t remember the guy’s name but his words stuck with me. I was telling him that I would never use EF again if the choice was up to me.  He said it’s not that he has a problem with Entity Framework, it’s that he’s done with ORMs.  I think that’s really the heart of it.  There’s a fundamental problem with ORM as a pattern.  It just doesn’t adequately solve the problem and it ads significant complexity and inefficiency to an application.

I recently ran across a couple of old blog posts that make for interesting reading, Is OR/M an anti pattern? by Ayende, and ORM is an anti-pattern by Laurie.  I’m hearing this line of thought more often as more developers use EF and other ORMs in production apps and then have a couple of years of living with the consequences.

So it’s easy to knock something, but what’s the alternative? For me it’s been moving to a simpler data mapper instead of a full on ORM.  I first wrote my own simple data mapper, but since then I’ve discovered Dapper.net by Sam Saffron and Marc Gravel.  On the surface Dapper works almost identically to the mapper I wrote, but under the covers it’s way better and much more efficient. So I’ve been porting all of my old code over to use Dapper. 

The results so far have been fantastic.  Sometimes I have to write more code that I would have to write with a full-on ORM, but I find that I can make major application changes (relatively) quickly and easily and I have never once spent hours struggling with my persistence architecture trying to understand why I’m erroring out on an update for an object graph, or troubleshooting lazy load issues, or select N+1 issues, or thinking to myself “If only this was SQL I would know exactly how to do this”.  Instead it just works, exactly the way I expect it to, and in the end that saves a lot of time and effort.

Monday, June 4, 2012

Great Backbone.js Tutorial

I definitely think that JavaScript is the future (at least the near term future) of app development, and I recently converted HireFlo to a single page JavaScript app.   You know the type, where you only have 1 real HTML page and it defines the main content areas of your site.  Then the rest of the app is all JavaScript that is used to load content into those areas mostly through AJAX and client side templates (check out jsrender). 

After doing the HireFlo rework, and seeing the rats nest of JavaScript that I created, I can definitely see the value of using a JavaScript MVC or MVVM framework to manage my JavaScript UI code.  One framework that I’ve been looking into is Backbone.js.  It’s a full-on MVC framework for JavaScript.  How cool is that?  The more I learn the more I like, and I think I might be refactoring HireFlo in the near future to use Backbone. 

If you want to take a look at Backbone, check out the Backbone.js Wine Cellar Tutorial by Christophe Coenraets.  It’s the best intro I’ve seen so far.

Sunday, May 13, 2012

Awesome Startup Architecture List

 

I wanted to put together my short list of awesome stuff you must have if you’re building a new web application on .Net. Each of these libraries is free, open source, and takes the simple, no-nonsense approach to getting things done that is essential in a startup.

Before I get into the list just let me say that jQuery isn’t on the list because I just assume that you’re already using it, and because it’s already included by default when you create a new .Net web app.

Dapper
You really can’t make the claim that there is any one right way to do data access... but this is the one right way to do data access.  It was written by two of the guys at StackOverflow and it gives you reflection like functionality without reflection.  They actually emit IL.  It’s cool.
http://code.google.com/p/dapper-dot-net/

Automapper
When you find yourself writing that mapping code between your DTOs (or entities) and your ViewModels, save yourself some time and just use this incredibly useful convention based mapping library by Jimmy Bogard
https://github.com/AutoMapper/AutoMapper

NLog
It’s a good idea to bake logging into your app from the beginning. I have no idea why people still use Log4Net (confusing) when NLog (simple and awesome) is out there.
http://nlog-project.org/

Quartz.Net
Surprisingly powerful scheduler.  Ideal for writing processors, console apps, and windows services that do things on a schedule.
http://quartznet.sourceforge.net/

Twitter Bootstrap
CSS and Javascript that gives you a whole UI framework and a bunch of themed widgets to build a modern webapp on top of.  Before you write any UI code, spend a day experimenting with Bootstrap. It’s amazingly useful and it gives your app a super polished look.
http://twitter.github.com/bootstrap/

JsRender
Javascript templating done right.  Indispensable if you’re  writing a single page javascript app using Bootstrap, BackboneJs, or KnockoutJs.
https://github.com/BorisMoore/jsrender

dotLess
A .Net port of the Less CSS library. In the style of FakeGrimlock: IT MAKE CSS MORE AWESOME!! 
http://www.dotlesscss.org/

jqModal
Simple jQuery based dialog boxes and modal popups.
http://dev.iceburg.net/jquery/jqModal/