Showing posts with label Architecture. Show all posts
Showing posts with label Architecture. Show all posts

Friday, December 4, 2020

The Absence of Pattern Thinking for Web Client Code

With 20 years of experience as a software engineer moving through the stack and using a lot of different languages throughout the years, I've seen a lot of good and conversely poor development implementations. I've also had the privilege of being able to work with languages (like C#) that placed a heavy emphasis as a community in  enterprise development around the mindset of using patterns and practices to make code more readable, reusable, and easier to communicate redundant and repeatable ways of creating applications and services. This has helped me immensely and provided me with a mindset on how to think and truly engineer a well built solution.

The priority of pattern thinking is missing

The problem I've seen over the last 5-10 years as a primarily focused JavaScript web client developer is the absence of this type of thinking. So much of the code I see written is just jammed into a file as a means to an end to complete a needed goal. I think unfortunately the explosion in JavaScript development and rapidly created JS developers due to demand has been partly to blame. I also think there has been so much focus on, "which framework/library," that has had a byproduct of having to learn so much just to get code implemented, that pattern thinking is just not at the forefront. Plain and simple there hasn't been time to organize thoughts or thinking around a sound architectural implementation using known patterns when the web client developer is just trying to get their head above water learning the framework, array of JS libraries, state management, CSS, responsive design, offline capabilities, mobile-like features, new work, enhancements, etc.. This in contrast to more stable back end languages that have had similar implementations going on for decades (albeit with new ways to wrap code or deploy; i.e. cloud) where the tenured experience has helped provide an environment where pattern thinking is much more prominent. I know this to be true, because I've been on that side of the fence as well.

Has it always been this way?

This isn't to say there has never been a focus on pattern for front-end code. Industry leaders such as John Papa were advocating for the module and reveling module patterns with ES5 code years ago, and even today alongside Dan Wahlin to carry the flag for architecting Angular apps and having a mindset for patterns and practices. Therefore a voice does exist from advocates for sound and well written code, but overall I just don't see the concrete evidence as much as I did when working with server-side code in C#/.NET. 

It's time we as a web client community when building enterprise web application push harder to use some forethought into how we implement our code borrowing concepts from known patterns and practices. It's not enough just to cram thousands of lines of code into a monolithic style .js/.ts file. This as an aside is one reason I'm not a huge fan of CSS in JS because it adds to desegregation of code and cramming everything into a single file. I don't consider myself old school to like separation of concerns (SoC), as it's really about organization of thought and practice. Much like the UI web component code we like to implement today with a mindset around segregating code into smaller, cohesive pieces of functionality, we must too apply that same style of thinking to the imperative code we write in JavaScript/TypeScript.

A high-level use case

Let me cherry pick a scenario I see more often than not in Angular. At a high-level speaking broadly, most modern Angular code has a thin service code file that makes an API call, and immediately returns an Observable with the result. The real result is that data is consumed and subscribed to in the component, and all presentation logic, data massaging, and appropriate (or sometimes inappropriate because it's IP) business logic is all done in said component. The result? A massive multi-thousand line big-ball-of-mud that's out of control and really difficult to maintain. It didn't start that way, right? The original MVP implementation was just a simple return and binding of data. However like any software that evolves, so does the need for more code and the initial pattern set forth, is scaled good or bad. In this case bad, and the component is out of control.

What if though something like the Command Pattern (or ideas from it) had be used from the inception? The component only acts as an air-traffic controller of sorts; it doesn't really know how to do anything except direct the traffic. It assembles all needed information, builds up and executes the command on the service where the real work happens (in 1..n services). This pattern also lends itself to creating immutable models in the component and they are only ever changed in the service. The service streams the data from an Observable, and all the component does (with minor exceptions) is bind to the new data. This is a much cleaner approach and a highly repeatable pattern for any experience level. Even if this particular approach seems heavy as you're building a smaller application, knowing patterns and their purpose for use will still lend your design ideas about how to better implement and organize your code. 

In contrast to OO patterns and practices but still with critical and planned thinking at the forefront, we could also use a functional programming paradigm (and patterns specific to FP), and leverage things like pure functions to avoid side effects with a goal of consistency and having more readable and logical implementation. Any of these options are better than the absence of any plan, which results in a poor implementation that's prone to bugs and being difficult to maintain.

In the end we didn't complicate the code, we just implemented it differently for the major gain or readability, reusability, and testability. I liken it to these images I used over 10 years ago when talking about patterns and practices in C#. Both containers below have the same content, but which one would you rather grab to get what you need? The answer is simple; the one that is organized.


The plan forward

The question is how do we learn about these patterns and when to apply them in our code? Well the answer is a combination of getting educated on well known patterns and gaining experience using them. It is however an art, and there is a balance to be had on how to use them most effectively. The cynics hear 'patterns' and sometimes get scared off saying, "that will overcomplicate the code!" There are times I agree. How can I spot the difference? Experience. If you don't have any, learn from others. One of my favorite words in the industry is 'pragmatic.' The ability to know balance in code and when and how to use powerful patterns to aid not hinder code. If the two ends of the spectrum are anarchy and over-architecture we want to be somewhere close to the middle. The problem is in my experience, we're too often close to the anarchy-style of implementation on the web client. I think the crazy saving grace that we back into is that since web client frameworks and libraries have only a 2-4 year tenure on average before some major overhaul, all this bad code is made obsolete before it really begins to stink things up. However during that time period it would behoove us to write code that is implemented with better patterns and practices to help extend the life and make the journey a whole lot easier.




Sunday, March 25, 2018

Buyer Beware: the client has burned us before, put stock in code on the server

Have you ever played poker? Do you like a full house? A royal flush? Those are amazing but the hand you're dealt is two 3's, a 5, a jack, and a 9. Software development and its future, often has speculation laced in but sometimes we need to deal with the hand we're dealt. As primarily a web developer these days and on and off over the last 15+ years, there has always been that "next thing in the pipeline that will save the horrors of web development." Sounds kind of like a gambler that says, "if I can just play one more hand, I'll win it all back and more!"

This all builds up to be a bit cynical, but the reality is web development is and always has been an ever changing, volatile platform for which to develop. There probably is no better group of people accustomed to change than your savvy modern day web developer. I don't think anyone should label web developers as 'in love' with how modern web development is implemented in general. It's a kludge of open source libraries and techniques that defines the very word 'web.' That being a tangled web of various libraries and techniques all pointing back to that love-hate relationship with JavaScript. 

JavaScript in some respects is that mediocre poker hand we were dealt. However in the web world it's perceived weaknesses are at the same time it's strengths. Albeit a dynamic language that frustrates many, it's also flexible and powerful providing us with that "write once run anywhere" ability due to the fact of browsers all being able to interpret and run JavaScript.The language has IMO matured exponentially in the last 5-10 years, and with the addition of high level superset languages like TypeScript, working with JavaScript isn't the nightmare it once was.

However, you won't see any "I love JavaScript" bumper stickers on the back of my car. I spent years working in various languages like WinBatch, VB, VBA, VB.NET, and C# on the server or client. The reality is today those do us no good in web development on the client. Ah but you say, WebAssembly is here to save the day! Yeah I've heard this tune played before (cough, cough, Silverlight). C# running on the client, same business rules on the client and server, our woes are over, etc. etc.. Listen, I know Silverlight and WebAssembly are not the same at all. The only analogy I'm making is it's not the 1st time in history something has been deemed the "savior" to web development. Call WebAssembly 'x' for this purpose, and "project x will save the day!" In reality I'm actually quite optimistic about where WebAssembly is going to take us on the client. Imagine using C# for everything? That would be beautiful. For an optimistic view of WebAssembly and it's future with smart client development, check out Rocky Lhotka's post: A Bright Future for the Smart Client

Let's pump the brakes for a minute though. It's early 2018 and I'm expected to deliver today using the hand I'm dealt. In that case we are looking at a host of JS libraries and frameworks to help us build a responsive SPA when it comes to web development. I also have the option of using server-side heavy tech, but for the purpose of this post, I'll focus on the more mainstream approach these days using JS and building responsive JS apps. The bright side of all this is there isn't that "one way" to do development. I suppose that's a double edged sword, but the reality is it gives us options. Like ES6? Use it. Don't like JS? Use TypeScript? Like Angular? Nope. Use React or Vue. Like LESS? Nope. Use SASS. The options go on and on and on. I do agree in some ways this stinks. I often talk about the days early in my career where being really awesome at VB6 meant you could conquer the world, finish your job, and not have to worry about 1,000 surrounding technologies, languages, and libraries. I feel like times were a bit more straight forward. However back in 2002, it was accepted that everybody and their brother was using Windows + IE and that was it. Times have changed and so has the web. The expectation today is run anywhere. Thankfully, JavaScript has provided that flexible nature to allow use to be fluid and make our way to being platform and browser agnostic. Thus we can reach a lot of people with a single line of code.

So what does this all mean? Well I can say for one thing today: the web is a volatile space and likely to continue beings so in the near future. Even if WebAssembly or any other technology comes along and truly revolutionizes web development as promised, it will take a long time to wash out the gabillion lines of JS out there running the web today. That and the fact we'll probably be in a scenario where, "1/5th of the APIs are available with new tech 'x', and a roadmap is available for the remainder." Point being, set yourself up well to play this hand you're dealt today no matter how it plays out. Be smart and architect your application properly to be successful today and in the future no matter what technologies throw their hat in the ring to save web development. This includes the next best JS framework ever to be head and shoulders above them all!

Put stock in your code on the server

How do we play our hand to isolate ripple effects as much as possible as technology proves to be volatile? The answer might be in looking at statistics from the past, rather than looking into a crystal ball. 

Let's take a walk through history for a moment in web development starting 18 years ago in 2000. If you were to build say a banking or financial web application beginning at that time and continuing to keep current on a mix of .NET and client technologies, here is the journey you would might have taken:

Classic ASP -> ASP.NET Webforms -> ASP.NET Webforms + AJAX Control Toolkit -> ASP.NET Webforms + Silverlight -> ASP.NET MVC (aspx engine) -> ASP.NET MVC (razor engine) -> AngularJS -> Angular 2,3,4,5....

What does this all mean? The web layer is and always has been volatile. Maybe the buck stops with WebAssembly in the future, but that is still yet to be proven; that's another crystal ball moment. I want to use the history of the journey we've taken to help make sound decisions today. This leads me to the point that I'd take little stock in the front-end of our application, and put stock in the server-side code.

Here's an example. Back in 2002, you wrote that financial or banking application using C#. If you at the time had used sound OO techniques dating back to the 70's, unit tested the code, and wrapped it in abstractions to deliver the data, that code could be mostly intact today. I couldn't say that for probably a single line of code on the front-end. 

I'm not oblivious to the changes in both C# and .NET technologies, so odds are code was probably refactored. However the most volatile part on the server is that being the manner in accessing the data and the manner in delivering the data. Sure there is volatility there as well. Maybe those core classes and business logic were once deliver via .NET Remoting, then an ASMX Web Service, followed by WCF, than WebAPI. However those should be ultra-thin layers acting as a means to an end to deliver the data. Same applies to accessing the data. You started with ADO.NET, then to LINQ to SQL, then to Entity Framework and through all of its versions. Again, this didn't necessarily need to change all of your core code; this is another layer that should be understood as being volatile.

So back to the web, today. I want to view the front-end layer as a thin and volatile layer that as history has shown has about an average of a 1-3 year lifespan it seems. I want the meat and potatoes of my code that matters on the server. I won't even get into the intellectual property or security considerations of why code should be on the server as I think that should be obvious with today's tech stack. I want to leverage the front-end code for only front-end matters. I want a pristine viewmodel of sorts returned via a service, where the only logic happening in the presentation layer is that of view manipulation and presentation logic. I've been on enough projects where IP and rules heavy work was done on the client (why, because you can!), only to have year long projects to refactor that code back to the server behind services.

Using an oversimplified view of the layers, let's look at the following using physical size to demonstrate placement and emphasis of code. Instead of a heavy client-side implementation like shown below:


I believe the implementation should be more along the lines of this based on everything discussed:


Put stock in your code on the server. History shows that in the battle of volatility the server-side wins out and the web is just too dynamic. Add to this security, IP considerations, and the unbelievably volatile and ever-changing world that is the 'web' it really is the smart move to make. The cynics will bring up leveraging CPUs on the client vs the server, but the world has changed. Data is small and efficient. The server has oodles of horsepower and is a known entity; we control it. The client is a wildcard; we don't know what they have. Long gone are the days where we know the client is a Windows machine controlled by an organization with a spec machine.

When analyzing data, as opposed to fat SOAP payloads of the past, payloads now are concise and to the point leveraging HTTP standards to deliver data as lean as possible. One must also yield to the fact that the days of 4GLTE and blazing fast WiFi and networking speeds are becoming the norm and will only continue to get better. It's pointless to argue that all apps must work flawlessly offline because that isn't reality across the board. We're in a world where if we aren't connected, things just don't work. Don't plan on making any airline reservations or bank account transfers when your device has no connectivity. I'll also avoid edge cases at this point as I understand there could be web apps made for 3rd world countries or the like where bandwidth is a premium, so data across the wire must be under the microscope. I'm sticking with mainstream, modern day, web development here. I'll leave the door open for you to evaluate edge cases that don't fit the 80/20 rule and call for an exception.

I can always go to the server and scrape off the services layer and re-introduce a new tech to replace that abstraction if needed. There are architectural recommendations within the server as well to make sure to thin-out the services facade and keep lightweight as that too as mentioned is know to be volatile over time. On the front-end, I want this same flexibility. Odds are I'll be asked to rewrite my web app in a few years to 'project x' tech which is the best thing ever for the web! I need to be lean up top and be able to scrape that thin veneer or icing off the cake, and put a new layer on easily. This isn't so easy to do if I've put the majority of my code on the client. When the boss or architect comes to me and says, "we are redoing our financial app using new front-end tech" I'll be positioned to say, "no problem, we can mitigate the ripple affect because the key logic and inner-workings of our app are stable and on the server, so we'll just need to redo the thin veneer that is the web-client code."

Thursday, November 14, 2013

Layers Are Cheap, But Doing It Right Is Priceless

I've often pondered over, discussed, and lightly debated the process of designing small applications and the extent to their architecture and implementation. Usually the conversation surrounds doing it 'quick and dirty' vs. creating a 'well built and thought out' application.

Think of this old saying:

Why do we use that saying? The idea is if you do a job hastily, it will have to be thrown out and started all over again. On a larger scale maybe something like this could occur :P



This is not unlike the process of building software. Odds are if you build an app poorly to try and save time, or create a 'throw away' app not supposed to be used in production both situations will yield a front running Enterprise application. Well, not always but it happens more times tan one probably realizes when making these decisions.  If you create a poorly made application, there is a strong likelihood in the future that it will also be 'thrown out' and targeted for the old 're-write.'

I know in my years of experience I have opened many of applications of all types (web, desktop, services, etc.) that were a huge mess of code. No wonder the passionate in our industry scream from the mountaintops about things like code standards, design, architecture, OOP, unit testing and the like. Who in their right mind with any experience places 1000 lines of code behind a form with a mix of binding, rules, data access, service calls, etc. that cares about the craft of software engineering? All this does is create a pile of frustration for the next developer to jump in someone else's mind to figure out their goo of an application mess. And is there ever any commenting to help with the goo? Of course not, these same developers believe that code should be 'self-documenting.' Yes thank you, please leave me the manual to your brain so I can decipher the poop you wrote, thank you.

So why waste time with re-writing application, if we can do it right the 1st go around? Well typically this scares those concerned with timelines, as doing an application properly is perceived to take longer to create. 

"Ah this is just a little old app, do we really need that fancy design?"
Yes. Or at least closer to 'Yes' than 'No'. In the end the word 'fancy' or 'complex' is overrated and misused anyway. It's cheaper to do than you think. Let's make a real-world example to discuss. Say we are tasked with creating a small web app with a few pages pulling data from the database and in the midst we need to apply a few simple business rules. As usual, it needed to be done yesterday.

1st let's say we choose to use web forms because of it's plethora of server controls which lend themselves to RAD. You could just as easily say WinForms, WPF, or MVC here as well. MVC would naturally have a leg up here because of it's M-V-C architecture that helps start us on the proper path of separating our concerns. However we could still have fat Controllers in MVC and be in the same conversation, so the technology choice here is not the main focal point. We can screw up the implementation using any technology.

Using web forms though we might be tempted with our objective to use one of the more robust data binding controls offered that includes built in data access methods. On the other hand another quick approach would be to use basic server controls and fatten up the single code behind file to get all the requirements complete and done quickly.  All of this are poor decisions that are leading us down the path I described earlier.

I'm not advocating for a full blown Domain Model or Onion Architecture, but a simple 3-layer (UI-BLL-DAL) architecture is leaps and bounds better than a code behind file with 3000 lines of code. If you are an experienced developer or have experience designing apps, how much longer does it truly take to set up the additional logical layers?

Let's see:
  1. Right-click, 'Add New Project' (BLL)
  2. Right-click, 'Add New Project' (DAL)
  3. Add references to new layers, create a few classes for busniess rules and data access.
OK, so this is the super simplified steps but in reality how long does it really take to add a few layers and segregate the application code? Maybe 1/2 day to 1 day for a small application. Possibly a few minutes to hours is more the reality. If you have used this in other applications, there will be some copying and pasting of basic logic (if not already refactored into a common unit) and visually copying of solution structure to help speed things along.

What's the payoff for this small bit of work up front? A MUCH better and well understood application, as well as an application that can scale better and stand the test of time longer. Splash on some code standards and common best-practices and we are making giant strides toward a better application.

I think the reality and success to this is having engineers/leaders/etc. with some experience doing this to articulate how easy this process is. Inexperienced engineers combined with nervous management concerned with timelines will most likely 9 out of 10 times agree together that the 'quick and dirty' route is a great option, and sell themselves on this idea because it's a small, unimportant application. The term 'architecture astronaut' or 'over architechting' are common buzz words that kill a good design and make those in charge feel good about essentially creating sloppy applications.

The summary of my experience is dealing with these poorly written apps is frustrating, and 5x time consuming in the long run as opposed to working on a well laid out application, no matter the size of the application. Since the cost of doing it 'right' or 'better' is so cheap up front, why not just do it? The answer should be that there is no excuse or discussion around not building applications with a well thought out design. The thought process should be applications small to large will all be done well, to prevent the known and true pitfalls that exist when creating applications 'quickly' to save time (which is an oxymoron by nature).

Sunday, January 6, 2013

Separating Entity Framework POCO Classes Generated From T4 Template in VS.NET 2012

The Entity Framework has come a long way and has some really nice features out of the box when using EF5 with VS.NET 2012. Specifically, if you are using a Database First approach, the generated entities from your .edmx are already POCOs. No more are the classes auto generated and inheriting from ObjectContext as in past versions. You could achieve this affect either manually or via POCO generation extensions in VS.NET 2010, but it is done by default now in VS.NET 2012.

So the 1st thing you might want to do is separate the POCOs into their own layer, separate from the .edmx. You would want to do this to keep your entities free from being tightly coupled to it's persistence details. After all there is no reason the POCO classes can't be used independently and outside of EF all together, and is why POCO support was such a big deal back when EF4 arrived.

There are a few things you need to do to separate the POCOs generated under the .tt branch under the .edmx file in VS.NET. As a side note, remember that the .tt file is just to support deign time tooling and is not compiled with the project. You don't need to have any heartburn with having this file reside near the POCO classes as it is not an indication of the classes being only used with EF; it brings along with it no dependencies to EF.

You may have already tried to drag the .tt file and associated POCO classes in Solution Explorer into a different layer and noticed it did not work. There are (2) ways to solve this issue: delete the .tt file and recreate in a new layer using a new 'EF 5.x DbContext Generator' item, or remove the dependency in the project's metadata file and then move it. Both will work, and I'm going to show you how to remove the dependency in the metadata file and then drag the files to the new layer. I don't get nervous modifying the .csproj files and this is a 1 time change. If you are not comfortable, then just add a new 'EF 5.x DbContext Generator' item to the separate layer and then follow the same steps below. I personally want the ability to move items around and want to break this dependency.

First make sure to build the solution to have all the metadata generated in the .csproj file, and then close VS.NET. Navigate to the project containing the .edmx file, and open the .csproj file for the containing project using notepad. We need to remove the XML element that creates a dependency between the .edmx file and the .tt template file. Search for the line below and remove it:

Reopen the solution and we now have the ability to drag the .tt and associated POCO classes into another layer. Remember, the .tt file is a design time tool and adds no dependencies or references to EF, so when we move these POCO classes they really are independent of any persistence details. Go ahead and drag the object in solution explorer as shown below. Once finished, add a reference to the layer that contains the .edmx to the new layer that contains the POCO classes.


There are (3) more steps to complete the move. 1st, we must update the path to the .edmx in the .tt file. Look for the following line near the top of the project and update as shown below:


The next step is to update the namespace for which the .Context.tt file under the .edmx is using. Because we have now moved the POCO classes to another layer, we must provide the namespace of the new location. If you do not do this, your Model.Context.cs file will have errors upon building. You might be tempted to add a 'using' statement to the namespace to fix the issue, but remember that you are dealing with auto-generated code. Every time the model is updated this class will be overwritten, so we don't want to modify it if possible. The proper way is to update the Custom Tool Namespace property on the Context.tt properties within VS.NET as displayed below:


The final step is to delete the original .tt file containing the POCO classes from the layer containing the .edmx as shown below:


The one step we must remember now is to run the Model.tt file manually now when we want our POCO classes to reflect an updated model. This will not happen automatically anymore as we have moved the POCO classes away from the .edmx. However it is as simple as right-clicking on the .tt file where the POCO classes are located and select 'Run Custom Tool' as shown below. Test it out by making a change to the .edmx model (i.e. change a property name), and then running the T4 template to recreate the POCO classes. Inspect the class to make sure the changes were reflected. If they were, then everything has been updated correctly.


Rebuild the solution and run, and everything should work as before. However, we have separated out POCO entities from the layer containing any persistence mechanism which is a good practice and follows the guidelines of SoC along with aligning our application with many of the designs and architectures we are familiar with using.

Tuesday, March 22, 2011

ASP.NET Web Forms vs. ASP.NET MVC

So it has been a few years now since Microsoft introduced the ASP.NET MVC Framework which is Microsoft's implementation of the MVC Architecture for ASP.NET. No the MVC (Model-View-Controller) architecture is not a new concept; just Microsoft's implementation of it in the .NET Framework. There has been a lot of buzz around whether to continue to use ASP.NET web forms which have been around since 2001, or to go with this "hot" new technology in ASP.NET MVC... or something else! There is no 'Silver-Bullet' answer to this, and with most situations, 'it depends'.

Oh I know, you might have "Googled" the exact phrase of this blog post and were hoping to get some answer to exactly which one is better. Nope. I just want to highlight a few of the strengths and weaknesses of both from an abstract point of view, and briefly mention some other alternatives too.

To begin, I am going to repeat a stat that Andrew Duthie (Twitter handle: @devhammer) brought up on this topic at an ASP.NET Firestarter event in Orlando last December. He showed a stat that somewhere in the range of 80%+ dev shops were still using ASP.NET web forms for their bread and butter applications, and that ASP.NET web forms were not going away! Anyone trying to spread a rumor like that needs to check with the folks direct from Redmond 1st, because it simply isn't true. To this end, folks shouldn't feel like they missed the last train to MVC euphoria because everyone hasn't boarded yet. I am not building up an article against MVC; I just want to point out that it is a misnomer that ASP.NET MVC has completely replaced an outdated web forms architecture that some may speak convincingly of on forums and blogs.

So maybe you are leading a team of developers and are looking to decide the pros and cons of MVC, or maybe you are about to build a site for a friend/family member as fast as possible, or involved in a large scale enterprise application that will be web based. Whatever the scenario, you want to know the details of which architecture to choose. After all it will be quite difficult to change between the two once the code begins to flow. Making the right decision up front is important in any of these scenarios no matter how small or large the project.

Let's 1st speak to the advantages of the MVC framework. 1st and foremost in my book is the Architecture itself: M-V-C. It is going to be tough to break this model and rearrange how the application is built. Having your or your team's hand forced into a stable and mature architecture like MVC is a good thing. Raise your hand (like anyone can see...) if you have ever seen or maybe written one of those spaghetti sandwich ASP.NET web forms application that has raw SQL right behind "btnSave_Click()". Blah! Awful nasty, all code-behind the forms, non-scalable mess of an application. So 'point' to MVC for guiding developers to a decent architecture. You can adhere to several good architectures using ASP.NET, but it is up to the developer or team of developers to be disciplined enough to stick to the architecture and not lay back on a fat UI layer. Separation of concerns is a key Object Oriented Concept and a real winner for the MVC architecture. Each layer has its own responsibility, and placing the proper code in its responsible layer will make for a much better code base to scale, maintain, inherit, etc.

Next ASP.NET MVC allows the developer to have "Full Control" over the rendered HTML. For now I am going to leave this as an advantage for MVC, but caution that not everyone fully understands what this means, and it might not be advantageous for a vast majority of applications not needing this type of control. Let me elaborate a bit; that wonderful winter of 2001 when many of our lives took a turn for the better as Scott Guthrie (Twitter handle: @scottgu) came up with what is ASP.NET web forms, and decided while sipping hot cocoa that if you drug a label onto a web form, it would get rendered as a DIV tag. He made this decision (or Microsoft) and not you. You pick the ASP.NET server controls you want to drag onto a web form, but don't have control over what HTML elements actually get rendered on the client as a result. You just know that when a Gridview is dragged onto a form, it will be displayed on the client. You don't know (or need to in many situations) that it might be a series of DIVs and Input HTML controls. This abstraction is actually an advantage for ASP.NET web forms. For many web applications built, we have relied on this drag and drop capability, and trusted the final output that will be rendered to ASP.NET. However, if you have ever found the way the ASP.NET sever controls get rendered is not exactly how you want or need it, then MVC is a better choice as it will allow you to have control over the final rendering. If you do not have any main issues with how ASP.NET web form server controls get rendered in your applications, then this might not be an "advantage" that you can sell to your tech manager or team when trying to build the next project using MVC.

Another advantage of using ASP.NET MVC that ties back into the individual layers is testability, specifically unit testing. Because the application is loosely coupled with code in its separate layers, the ability to create unit tests increases greatly. The event based ASP.NET pages that rely on things like Session, Context, Response, etc are quite difficult to effectively test because of the inability to isolate specific page functionality due to its nature of being spread out and external dependencies as well. MVC improves on this greatly, and is architected to be testable. 'Point' MVC.

So let's examine ASP.NET web forms for a minute. As I mentioned they were born sometime in late 2001, so maturity and a rich tool set (both from Microsoft and 3rd party) is a big advantage. These "tools", or ASP.NET server controls make up a style of development referred to often when speaking of ASP.NET web forms called RAD or Rapid Application Development. "Hey I can drag a few ASP.NET text boxes, some labels, this Gridview thingy, press publish, and WHAT??!! I have a website!" Now that website might be junk, but hey its done already. On to the next project, right? Well not quite. 'Fast', especially in our field doesn't mean better. That site might be done, but as eluded to prior, its design is junk and it will not maintain or scale well. But what if you know the scope is a single, simple page? Well then a tool like web forms is probably perfect, and MVC might be overkill if speed of development is of the essence. Don't be fooled, web forms + data binding, etc. will be faster to generate just based on the drag-and-drop + wizardry capabilities. Just don't have a code review and everything will be fine! So the RAD capabilities of ASP.NET web forms can be a double edged sword. A quality ASP.NET web forms with a pre-determined architecture (3-layer, Domain Driven Design, MVP, etc.) that uses developers with discipline to adhere to it, is a much better choice when creating ASP.NET web form applications.

Along these lines is another advantage with web forms and that is 'Experience'; specifically in relation to a developer's experience with the technology. Again with web forms being a mature technology going on 10 years, there is a solid developer core with ample experience. If you are leading a team of 8-10 developers, you are the only one with MVC experience, and everyone else knows web forms, then this needs to play into your decision of which technology to use. Are you prepared to take the financial impact of formal MVC training through remote seminars, current books, or on-sight training? Can you afford the 1-3 month setback while the team gets up to speed on ASP.NET MVC to say a beginner/intermediate level? If these are not an issue, and the advantages of ASP.NET MVC mentioned previously are present, then it may be the better choice regardless of the upfront cost in time, money, etc. If however, you need to begin writing code immediately with a team of web form rich experience developers and are under a tight deadline, then maybe holding off on using MVC is the better decision. In the end you need to weigh the factors to make the best decision.

There are some other disadvantages to the web forms technology that I will mention briefly here as well. The web form's postback model uses client side generated '_doPostBack()' events for each server callback. If JavaScript is disabled this will cause several problems for the web forms application. It is also difficult to manipulate manually if writing your own client side scripts. MVC improves on this using REST based URLs. The next disadvantage with web forms is ViewState. Referring back to my comments about poorly designed web form applications, a bloated ViewState can cause pages to be larger and slower than they need to be. ViewState stores a base64 encoded string with information about controls state to persist postbacks and to help combat the stateless nature of the web. This however becomes a disadvantage for web forms when abused.

Now let's throw a cog into the wheel and add in another choice for web development in the .NET realm: Silverlight. Oh yeah, and honestly my favorite when it comes to rich UI content. However, you still need a hosting application and Silverlight can be integrated into either ASP.NET web forms or ASP.NET MVC applications. And I don't want to confuse anyone either because Silverlight is not an entire 'web' Framework onto its own and only works alone as individual controls. The Silverlight controls integrate into a web forms or MVC application as just another control and can co-exist with controls of either technology. However, since Silverlight can't invoke the controller class in MVC, or directly postback to the server when using web forms, you will need to use services (WCF) to accomplish this task. Anyone using Silverlight previously knows that WCF services can bridge the gap between the Silverlight control and the server.

Decisions, decisions, which technology to pick? There is a lot to weigh when it comes to these two technologies: ASP.NET web forms or ASP.NET MVC. Are you trying to draw a line in the sand and say, "Only MVC web apps from here on out!!" Personally I would not do that, because it wasn't like 10 years ago when we moved from classic ASP to ASP.NET and were able to be that bold. Now ASP.NET MVC has to be looked at as another tool (a very powerful and cool one) in the proverbial toolbox. There will be a time when MVC is the proper decision, and a time when web forms is the proper one. I strongly urge those picking web forms to at a minimum not fall into the trap of bad or poorly architected code, and be disciplined to use an architecture that is more scalable and maintainable (check my review of the book Professional ASP.NET Design Patterns). And lastly and maybe most importantly, be a 'realist' and not a 'purist' when making this decision. Do what is best and right, and not just which one theoretically is better in argument. This will help you decide. Either way its great to be a .NET developer with such a plethora of technologies to choose from.

Monday, November 22, 2010

Book Review: Professional ASP.NET Design Patterns By Scott Millett

Let me begin by stating that Professional ASP.NET Design Patterns is a fantastic book that was worth every minute I spent reading it. The author, Scott Millett, is a great community leader and extends himself in several ways including spending time on the forums contributing to others into his strong insight of Domain Driven Design, Architecture, and Design Patterns. He has extended that helpfulness by writing this book that takes a dive into Design Patterns and Architecture from an ASP.NET UI centric view. However I would not get too fixated on the 'ASP.NET' in the title as probably more than half of this book could just as well have been called "Professional .NET Design Patterns" as it provides design patterns that are truly useful to all types of .NET applications once moving below the topmost UI layer. There are several chapters devoted to ASP.NET patterns including MVC which makes this still focused mostly on ASP.NET, but I would still recommend this book to WinForms and other SmartClient developers as well.

This book's target audience is broad and could reach to several different types of software engineers. It is probably suited best for Senior Engineers, Architects, Leads, or generally seasoned developers. It is not really an introductory book (this is a good thing; there are plenty of those books out there already), so if you don't know what acronyms like OOP, OOD, UI, BLL, or DAL mean at a minimum already then you may want to read something along the lines of an introduction to Object Oriented Programming book 1st to gain some traction. This is however a terrific book for those that do have a lot of experience with a traditional 3-layer logical architectures, and are looking to bridge the gap to more sophisticated architectures using Domain Driven Design and other implementations of either Martin Fowler's or the GoF design patterns within.

Scott does a wonderful job of layering the book (chapters) as you would an application. Each chapter takes either a single layer or design pattern and goes into detail on its responsibilities, relationship to other layers, and implementation with easy to follow along code samples. In fact I highly recommend downloading the code samples from the WROX website (WROX Code Download) The entire set of code samples are in C#, but don't let this slow up any VB.NET devs out there. I am actually a VB.NET developer (C# in the past) but we all know that you don't get too far in this industry without reading both so this should not be any problem.

The 1st third of the book (roughly) concentrates mostly on individual logical layers of an application and how they work together to build an application. Within each layer, there are examples of Design Patterns (both Fowler and GoF) that are used and shown why they are useful within that particular layer. There is also a section on IoC and DI which I really enjoyed and are reoccurring patterns in the layers throughout the book. The 2nd third of the book concentrates mostly on ASP.NET architectures and techniques like MVC, MVP, and AJAX patterns. The last third is devoted to a case study example that uses the knowledge gained from the previous chapters. The book reads and flows extremely well and was one of the reasons I enjoyed reading it so much.

I will also note that this is a great book for those of you familiar or have read the GoF book Design Patterns Elements of Reusable Object Oriented Software. As we all know code examples used to conceptually explain design patterns are not always critical, but Scott's book puts a fresh '.NET' perspective on several of the GoF patterns which is really nice. This helps to see how these patterns apply directly in .NET instead of taking the SmallTalk or C++ examples from the GoF book and translating them into .NET.

The book wraps up with a full case study example putting all of the chapters together (Agath's e-commerce store). This again strengthens the flow of the book with an extended example using everything learned from the previous chapters, This solution is included in the 'Chapter 14' folder in the downloadable code and is a nice reference to show everything from the book.

Well I will wrap this review up by saying this book is one for the shelf of 'Top Reference' books that go right next to the development machine. This is one of those books that you think, "How do I do that in the Repository Layer...", and then pick up the book to get a refresher. I would definitely recommend this book and keep an eye out for future books from Scott Millett. Nice Job!

Tuesday, March 30, 2010

Domain Driven Design (DDD) Free Book Download

I have not yet ventured far into the world of Domain Driven Design, but if you are interested there is a book named, Domain Driven Design Quickly that is an overview of Eric Evans' DDD. It can be downloaded for free (after registration) from the following InfoQ link:
InfoQ: Domain Driven Design Quickly
From the above link: "This book is a short, quickly-readable summary and introduction to the fundamentals of DDD; it does not introduce any new concepts; it attempts to concisely summarize the essence of what DDD is, drawing mostly Eric Evans' book, as well other sources since published such as Jimmy Nilsson's Applying Domain Driven Design, and various DDD discussion forums"