Thursday, February 26, 2009

Continuous Refactoring vs Refactor Mercilessly

Good ideas need to have a name. Uncle Bob refers to the boy scouts' rule, "Leave the campground cleaner than you found it". The "Pragmatic Programmer" authours say "Fix the problem, not the blame". Fowler's advise is to refactor any time the code smells.

Google shows that there are
3 660 hits for "Refactor Mercilessly"
2 040 hits for "Continuous Refactoring"

So even if I like "Continuous Refactoring" best, I guess "Refactor Mercilessly" won.

More important, I will try to make this a part of my autopilot programming: Whenever I stumble upon something that smells like crap, I will go ahead and fix it right away. Instead of blaming, commenting or apathetically ignoring the code.


The S5 principles from japanese car industry in the 50s are interesting for software development:

Seiri: Organization; Know where things are, use proper naming
Seiton: Systematization; Put things where you expect to find them
Seiso: Cleanliness; the absense of dirt
Seiketsu: Standardization; Define rules and policies;
Shutsuke: Discipline, in the japanese way

We have a lot to learn from the car industry. A car can't have errors. Neither should our programs So let's pretent we're building cars!

The Rise and Fall of a Software Company

I'm reading Robert C. Martin's "Clean Code", and this little anecdote really struck me. Many businesses go down this slope, since management and even developers do not understand the need for refactoring and redesign until it's too late.
I know of one company that, in the late 80s, wrote a killer app. It was very popular, and lots of professionals bought and used it. But then the release cycles began to stretch. Bugs were not repaired from one release to the next. Load times grew and crashes increased. I remember the day I shut the product down in frustration and never used it again. The company went out of business a short time after that.

Two decades later I met one of the early employees of that company and asked him what had happened. The answer confirmed my fears. They had rushed the product to market and had made a huge mess in the code. As they added more and more features, the code got worse and worse until they simply could not manage it any longer. It was the bad code that brought the company down.

Later in the book, Martin (aka "Uncle Bob") compares the development of software with the development of a city. You won't build a 6 lane superhighway in a little village. You don't have the resources, and noone even wants it there. When the town is growing, you will need to build a new infrastructure. You might need to tear down some houses to build a new highway that can handle the new reality.
It's a good metaphore. My lesson learned is: Know the danger of not redesigning. If you keep building on old infrastructure that should be replaced, your city might break down.

Tuesday, February 24, 2009

OO Design Principles

S.O.L.I.D. Class Design Principles
  • S ingle Responsibility Principle (SRP) - Each responsibility should be a class
  • O pen/Closed Principle (OCP) - Inherit from abstract base classes
  • L iskov substitution principle (LSP) - Subtypes should be substitutable for their supertypes
  • I nterface Segregation Principle (ISP) - Use many small interfaces, not one big
  • D ependency Inversion Principle (DIP) - Let details depend upon abstractions, not the other way around
More Principles
  • Law of Demeter: Only interact with yourself and your neighbours
  • Hollywood Principle: Don't call us, we'll call you - Reduce coupling using events, IoC, DI etc
  • Don’t Repeat Yourself (DRY): Remove duplication, not only in code but also in your model
  • Program to an interface, not an implementation: Decouple implementation from interfaces
  • You Ain’t Gonna Need It (YAGNI): Wait until you need it
  • Keep It Simple, Stupid (KISS): Make everything as simple as possible, but not simpler
  • Encapsulation and Information Hiding: Protect yourself, be shy, don't reveal your inner mechanisms
  • Separation of Concerns (SoC): Separate stuff using encapsulation, subsystems, modules, layers etc
  • High Cohesion:
  • Low/Loose coupling: Let your components be independent of each other
  • Command-query separation (CQS)
  • Design by Contract (DbC)
  • Dependency Injection (DI)
  • Inversion of Control (IoC)

Monday, February 23, 2009

Tell, Don't Ask

Procedural code gets information then makes decisions. Object-oriented code tells objects to do things.
— Alec Sharp
That is, you should endeavor to tell objects what you want them to do; do not ask them questions about their state, make a decision, and then tell them what to do.

The problem is that, as the caller, you should not be making decisions based on the state of the called object that result in you then changing the state of the object. The logic you are implementing is probably the called object’s responsibility, not yours. For you to make decisions outside the object violates its encapsulation.

Application Layer [Service Layer]: Defines the jobs the software is supposed to do and directs the expressive domain objects to work out problems. The tasks this layer is responsible for are meaningful to the business or necessary for interaction with the application layers of other systems. This layer is kept thin. It does not contain business rules or knowledge, but only coordinates tasks and delegates work to collaborations of domain objects in the next layer down. It does not have state reflecting the business situation, but it can have state that reflects the progress of a task for the user or the program.

Domain Layer (Model Layer): Responsible for representing concepts of the business, information about the business situation, and business rules. State that reflects the business situation is controlled and used here, even though the technical details of storing it are delegated to the infrastructure. This layer is the heart of business software.

From Eric Evans' Doman Driven Design, via Fowler's Anemic Domain Model

Law of Demeter: Only talk to your immediate friends


should really be:


..and let the implementation of the dog decide what this means.

Peter Van Rooijen posted the following description of the Law Of Demeter to Usenet:
  • You can play with yourself.
  • You can play with your own toys (but you can't take them apart),
  • You can play with toys that were given to you.
  • And you can play with toys you've made yourself.

The Law of Demeter (LoD), or Principle of Least Knowledge, is a design guideline for developing software, particularly object-oriented programs. The guideline was invented at Northeastern University towards the end of 1987, and can be succinctly summarized as “Only talk to your immediate friends.” The fundamental notion is that a given object should assume as little as possible about the structure or properties of anything else (including its subcomponents).
C2 Wiki:
The LawOfDemeter makes UnitTests easier.

Miško Hevery:
Most applications tend to have some sort of Context object which is the kitchen sink and which can get you just about any other object in the system aka the service locator. [-] Writing tests for such code base sucks!
Always ask for things
-Abandon the new operator in 99% of your domain classes
-Move object creation to factories (or a DI container)

Haacked: TDD and Dependency Injection with ASP.NET MVC

Great article on TDD, DI and MVC by Phil Haack:

Read article

Resharper Keyboard Shortcuts

When watching the "Become a Resharper Samurai" screencast series from DimeCasts, I learned some useful Resharper shortcuts that I wasn't aware of. Using more Resharper features will make my day-to-day coding a lot more productive, so I'll really try to get to the point were I don't have to think - just use them, like using TOUCH.

Alt + Enter: Show available Resharper actions if resharper icon is present on line
Ctrl + P: Show parameter information

Alt + Ins: Show generate menu
Ctrl + Shift + R: Refactor menu
F2: Refactor rename
Move interface to another file: Cursor in interace line => Alt + Enter to show menu
Method parameter to auto property: Cursor on param => Alt + Enter to show menu
Extract class from paramters Cursor in signature => Alt + Enter to show menu

Ctrl + Shift + N: Find file
Ctrl + N: Find type
Ctrl + F12: Find member
Ctrl + B: Go to definition
Ctrl + Alt + B: Find classes implementing an interface
Alt + F7: Find usages
Ctrl + Alt + F7: Find usages but show in Resharper popup list
Alt + Up: Jump to next method
Alt + down: Jump to next method

Sunday, February 22, 2009 - Screencasts

I've already written about Kigg and in another blog article.

DotNetShoutout has a really nice collection of screencasts, have a look!

Kigg -

DotNetShoutout is a Digg clone for programming topics, created by a group of developers from Bangladesh. This site is built on Kigg, an open source web application hosted by CodePlex.

Kigg is using the ASP.NET MVC Framework, and the author Kazi Manzur Rashid gives a really great walkthrough of the app in this article at . Learn how to use LINQ to SQL, MVC routing and unit testing

Direct link to sample code:

Saturday, February 21, 2009

How to find a great presentation

Not all presentations are great. But if they are, people tend to tell - in comments. And fortunately, most sites allow comments -- and fortunately, a lot of people tend to use the phrase "great presentation" if they think a presentation was just great.

I realized this when I read a comment about a really great presentation from Mr Jason on MVC. So I tested some Google searches, and the SERPs were ... great. Here are some examples of queries to use:

You get the picture. Add the keyword(s) representing what you're looking for, and hopefully you'll find stuff much better than your college programming class courses.

Huge collection of videos, covering unit testing, mocking, Linq, NHibernate and serveral other aspects of software development:

Wednesday, February 18, 2009

Sql Server Reporting Videos

Sql Server Reporting Videos

StackOverflow: Unit testing videos and podcasts

Google Clean Code Talks

Unit testing etc:

YouTube playlist:

Hanselman: What Great .NET Developers Ought To Know

Everyone who writes code


* Describe the difference between a Thread and a Process?

* What is a Windows Service and how does its lifecycle differ from
a "standard" EXE?

* What is the maximum amount of memory any single process on Windows
can address? Is this different than the maximum virtual memory for the
system? How would this affect a system design?

* What is the difference between an EXE and a DLL?

* What is strong-typing versus weak-typing? Which is preferred? Why?

* Corillian's product is a "Component Container." Name at
least 3 component containers that ship now with the Windows Server Family.

* What is a PID? How is it useful when troubleshooting a system?

* How many processes can listen on a single TCP/IP port?

* What is the GAC? What problem does it solve?

Mid-Level .NET Developer


* Describe the difference between Interface-oriented, Object-oriented
and Aspect-oriented programming.

* Describe what an Interface is and how it's different from a Class.

* What is Reflection?

* What is the difference between XML Web Services using ASMX and .NET
Remoting using SOAP?

* Are the type system represented by XmlSchema and the CLS isomorphic?

* Conceptually, what is the difference between early-binding and late-binding?

* Is using Assembly.Load a static reference or dynamic reference?

* When would using Assembly.LoadFrom or Assembly.LoadFile be appropriate?

* What is an Asssembly Qualified Name? Is it a filename? How is it

* Is this valid? Assembly.Load("foo.dll");

* How is a strongly-named assembly different from one that isn't strongly-named?

* Can DateTimes be null?

* What is the JIT? What is NGEN? What are limitations and benefits
of each?

* How does the generational garbage collector in the .NET CLR manage
object lifetime? What is non-deterministic finalization?

* What is the difference between Finalize() and Dispose()?

* How is the using() pattern useful? What is IDisposable? How does
it support deterministic finalization?

* What does this useful command line do? tasklist /m "mscor*"

* What is the difference between in-proc and out-of-proc?

* What technology enables out-of-proc communication in .NET?

* When you're running a component within
ASP.NET, what process is it running within on Windows
XP? Windows 2000? Windows 2003?

Senior Developers/Architects


* What's wrong with a line like this? DateTime.Parse(myString);

* What are PDBs? Where must they be located for debugging to work?

* What is cyclomatic complexity and why is it important?

* Write a standard lock() plus "double check" to create a
critical section around a variable access.

* What is FullTrust? Do GAC'ed assemblies have FullTrust?

* What benefit does your code receive if you decorate it with attributes
demanding specific Security permissions?

* What does this do? gacutil /l | find /i "Corillian"

* What does this do? sn -t foo.dll

* What ports must be open for DCOM over a firewall? What is the purpose
of Port 135?

* Contrast OOP and SOA. What are tenets of each?

* How does the XmlSerializer work? What ACL permissions does a process
using it require?

* Why is catch(Exception) almost always a bad idea?

* What is the difference between Debug.Write and Trace.Write? When
should each be used?

* What is the difference between a Debug and Release build? Is there
a significant speed difference? Why or why not?

* Does JITting occur per-assembly or per-method? How does this affect
the working set?

* Contrast the use of an abstract base class against an interface?

* What is the difference between a.Equals(b) and a == b?

* In the context of a comparison, what is object identity versus object

* How would one do a deep copy in .NET?

* Explain current thinking around IClonable.

* What is boxing?

* Is string a value type or a reference type?

* What is the significance of the "PropertySpecified" pattern
used by the XmlSerializer? What problem does it attempt to solve?

* Why are out parameters a bad idea in .NET? Are they?

* Can attributes be placed on specific parameters to a method? Why
is this useful?

C# Component Developers


* Juxtapose the use of override with new. What is shadowing?

* Explain the use of virtual, sealed, override, and abstract.

* Explain the importance and use of each component of this string:
Foo.Bar, Version=, Culture=neutral, PublicKeyToken=593777ae2d274679d

* Explain the differences between public, protected, private and internal.

* What benefit do you get from using a Primary Interop Assembly (PIA)?

* By what mechanism does NUnit know what methods to test?

* What is the difference between: catch(Exception e){throw e;} and
catch(Exception e){throw;}

* What is the difference between typeof(foo) and myFoo.GetType()?

* Explain what's happening in the first constructor: public class c{
public c(string a) : this() {;}; public c() {;} } How is this construct

* What is this? Can this be used within a static method?

ASP.NET (UI) Developers

* Describe how a browser-based Form POST becomes a Server-Side event
like Button1_OnClick.

* What is a PostBack?

* What is ViewState? How is it encoded? Is it encrypted? Who uses ViewState?

* What is the <machinekey> element and what two
ASP.NET technologies is it used for?

* What three Session State providers are available in
ASP.NET 1.1? What are the pros and cons of each?

* What is Web Gardening? How would using it affect a design?

* Given one
ASP.NET application, how many application objects does
it have on a single proc box? A dual? A dual with Web Gardening enabled?
How would this affect a design?

* Are threads reused in
ASP.NET between reqeusts? Does every HttpRequest get
its own thread? Should you use Thread Local storage with

* Is the [ThreadStatic] attribute useful in
ASP.NET? Are there side effects? Good or bad?

* Give an example of how using an HttpHandler could simplify an existing
design that serves Check Images from an .aspx page.

* What kinds of events can an HttpModule subscribe to? What influence
can they have on an implementation? What can be done without recompiling
ASP.NET Application?

* Describe ways to present an arbitrary endpoint (URL) and route requests
to that endpoint to

* Explain how cookies work. Give an example of Cookie abuse.

* Explain the importance of HttpRequest.ValidateInput()?

* What kind of data is passed via HTTP Headers?

* Juxtapose the HTTP verbs GET and POST. What is HEAD?

* Name and describe at least a half dozen HTTP Status Codes and what
they express to the requesting client.

* How does if-not-modified-since work? How can it be programmatically
implemented with

Explain <@OutputCache%> and the usage of VaryByParam, VaryByHeader.

* How does VaryByCustom work?

* How would one implement
ASP.NET HTML output caching, caching outgoing versions
of pages generated via all values of q= except where q=5 (as in


Saturday, February 14, 2009

SSW: Rules and standards

This is a great guide to follow when doing software (and specifically .NET) development. Very useful stuff!
Scott Guthrie

Using AOP to Implement Functional Requirements

Using AOP to Implement Functional Requirements - Closing Dirty Forms

Inversion of Control - Dependency Inversion Principle - Castle's Windsor/MicroKernel

First, is the Dependency-Inversion Principle. Rather than the application being dependent on the blog services and the blog services dependent on the database, we have inverted the relationship. The details are no longer in control of the application. The database is dependent on the blog services and the blog services is dependent on the application, allowing us to plug-in various databases and blog services at will without touching the application.

Designing Data Tier Components and Passing Data Through Tiers

Building Distributed Applications - Designing Data Tier Components and Passing Data Through Tiers

CSS Dock Menu

Pretty cool Mac-ish dock menu, made with JS and CSS.

SearchMe: A Visual Search Engine

Scrum resources

Nice English site:

YouTube videos:

H. Kniberg Video (the swedish guy):

Jeremy's First Law of Continuous Integration

If you check in very often and/or first, you can make merge conflicts be someone else's problem

Visual Studio Tips

Always code in full screen - use F11
Transpose word / character: ctrl + t
Transpose paragraph: Alt shift + t
Copy line: ctrl + c (no selection necessary)
Cut line: ctrl + x (i no selection necessary)
Intellisense: Ctrl + J
Intellisense parameter: ctrl + shitf + space
Rectangular selection: alt + drag

View code: F7
View deisgner: shift F7
Split to see different parts of same code file: Use splitter widget top right)
Drag file to code to show full path
Full screen: ctrl + shitf + enter
Class view: ctrl + shift + c
Macro for MVC solution
#error Not correct logic here <== compile error
#warning Code sucks <== compile warning

AJAX Videos

Another extremely nice collection of videos from Microsoft. More than 70 video tutorials on AJAX.

Asp.NET Videos

Extremely nice collection of videos from Microsoft. Hours of tutorials.

Thursday, February 12, 2009

Quotes from real-life Dilbert-type managers

A magazine recently ran a "Dilbert Quotes" contest. They were looking for people to submit quotes from their real-life Dilbert-type managers. These were voted the top ten quotes from the Dilbert’s we work for in corporate America , circa 2004:
  1. "As of tomorrow, employees will only be able to access the building using individual security cards. Pictures will be taken next Wednesday, and employees will receive their cards in two weeks." (This was the winning quote from Fred Dales, Microsoft Corp. in Redmond WA)
  2. "What I need is an exact list of specific unknown problems we might encounter." (Lykes Lines Shipping)
  3. " E-mail is not to be used to pass on information or data. It should be used only for company business." (Accounting manager, Electric Boat Company)
  4. " This project is so important we can't let things that are more important interfere with it." (Advertising/Marketing manager, United Parcel Service)
  5. " Doing it right is no excuse for not meeting the schedule." (Plant Manager, Delco Corporation) [Perhaps that's why they're in bankruptcy.]
  6. " No one will believe you solved this problem in one day! We've been working on it for months. Now go act busy for a few weeks and I'll let you know when it's time to tell them." (R&D supervisor, Minnesota Mining and Manufacturing/3M Corp.)
  7. Quote from the Boss: "Teamwork is a lot of people doing what I say." (Marketing executive, Citrix Corporation)
  8. My sister passed away and her funeral was scheduled for Monday. When I told my Boss, he said she died on purpose so that I would have to miss work on the busiest day of the year. He then asked if we could change her burial to Friday. He said, "That would be better for me." (Shipping executive, FTD Florists)
  9. "We know that communication is a problem, but the company is not going to discuss it with the employees." (Switching supervisor, AT&T Long Lines Division)
  10. One day my Boss asked me to submit a status report to him concerning a project I was working on. I asked him if tomorrow would be soon enough. He said, "If I wanted it tomorrow, I would have waited until tomorrow to ask for it!" (Hallmark Cards Executive)

ElegantCode Codecasts

Erich Gamma on Design Patterns and more

Joshua Bloch on API Design

Video: How To Design A Good API and Why it Matters

By Joshua Bloch, Principal Software Engineer @ Google

Guidelines for Test-Driven Development

Benefits of Test-Driven Development
  • The suite of unit tests provides constant feedback that each component is still working.
  • The unit tests act as documentation that cannot go out-of-date, unlike separate documentation, which can and frequently does.
  • When the test passes and the production code is refactored to remove duplication, it is clear that the code is finished, and the developer can move on to a new test.
  • Test-driven development forces critical analysis and design because the developer cannot create the production code without truly understanding what the desired result should be and how to test it.
  • The software tends to be better designed, that is, loosely coupled and easily maintainable, because the developer is free to make design decisions and refactor at any time with confidence that the software is still working. This confidence is gained by running the tests. The need for a design pattern may emerge, and the code can be changed at that time.
  • The test suite acts as a regression safety net on bugs: If a bug is found, the developer should create a test to reveal the bug and then modify the production code so that the bug goes away and all other tests still pass. On each successive test run, all previous bug fixes are verified.
  • Reduced debugging time!

Dotnetslackers - Castle Windsor IoC / DI Tutorial

Simple explaination of refactoring to IoC/DI, and how to use Castle Windsor Container:

Eric Evans - DDD Videos

Eric Evans on Domain Driven Design

Presentation by Eric Evans: Making Models Work First part

Presentation by Eric Evans: Strategic Design Second part

StartupSchool 08 Videos

Best Tech Videos

Wednesday, February 11, 2009

Pragmatic Programmer on DDD

Program Close to the Problem Domain
Design and code in your user’s language.

Pragmatic Programmer on DRY

Every piece of knowledge must have a single, unambiguous, authoritative representation within a system.

Steve Eichert on DDD: Factories and repositories

By separating the responsibilities of data retrieval into our Repositories, and object creation into our Factories we allow our domain objects to stay focused on representing the domain. We also allow our applications to become more de-coupled which allows us to more easily test our applications.

Eric Evans on DDD

Now I am focused on making sure my consulting clients get their money's worth from their software development efforts by focusing on their core domain, effectively expressing that model in their software [-]

A software project should be a voyage of discovery that a team of software experts, domain experts and business strategists all take together. A team like that can collaborate to chart a course to a very valuable destination that is not entirely known at the outset.

Billy McCafferty on DI (CodeProject)

Billy McCafferty:

"Dependency Injection" (DI), also more cryptically known as "Inversion of Control" (IoC), can be used as a technique for encouraging this loose coupling. There are two primary approaches to implementing DI: constructor injection and setter injection. Obviously, at some point, something must be responsible for creating the concrete objects that will be injected into another object. The injector can be a parent object, which I'll call the "DI controller", or can be externalized and handled by a "DI container" framework. What follows is a brief overview of the various approaches for using dependency injection techniques. / Dhanji R. Prasanna on DI

Dhanji R. Prasanna

In a traditional object-oriented application, a primary program controls secondary pieces of code, such as classes in a module, library, or framework. Dependency Injection (DI) is a technique that inverts this control, using an external mechanism to insert—or inject—a reference to an implementation of a service into an object. This allows you to build complex OO applications in a more testable, maintainable, and business-focused manner.

Dhananjay Nene on DI / Dhananjay Nene:

Wikipedia on DI

Dependency Injection (DI) in computer programming refers to the process of supplying an external dependency to a software component. It is a specific form of inversion of control where the concern being inverted is the process of obtaining the needed dependency.

Griffin Caprio on DI inject objects into a class, rather than relying on the class to create the object itself.

Domain Driven Design @ CodeBetter

Domain Driven Design @ CodeBetter

Dependency Injection, MSDN Magazine

What's wrong with tightly coupled architectures
Testing and dependency woes
Dependency inversion
Dependency injection

Tuesday, February 10, 2009

Initial structure

OO / OO Principles
-Object Orientation (OO)
-Domain Driven Design (DDD)
-Dependency Injection (DI)
-Dependency Inversion
-Test Driven Development (TDD)
-Inversion of Control (IOC)
-Continous Integration (CI)
-Service Oriented Architecture (SOA)
-Model View Controller (MVC)
-Model View Presenter (MVP)
-Open Closed Principle (OCP)
-Liskov Substitution Principle (LSP)
-Don't Repeat Yourself (DRY)

Object Orientation
-Composition and Aggregation
-Loose Coupling
-Smart Cells
-Cohesion: Single Responsibility
-No Global State

Design Patterns
-Abstract Factory
-Factory Method
-Chain of Responsibility
-Template Method
-Lazy initialization
-Null object

Architectural patterns:
* Layers
* Presentation-abstraction-control
* Three-tier
* Pipeline
* Implicit invocation
* Blackboard system
* Peer-to-peer
* Service-oriented architecture
* Naked objects
* Model-View-Controller

Guru books
-Code Complete
-Pragmatic Programmer
-Rapid Development
-Beautiful Code
-Software Estimation
-Test Driven Development
-Clean Code
-Software Requirements
-Patterns of Enterprise Application Architecture
-GoF Design Patterns
-Head FIrst Design Patterns
-Domain Driven Design