Feeds:
Posts
Comments

Archive for the ‘Professional ASP.NET Design Patterns’ Category

Chapter 2 of Professional ASP.NET Design Patterns by Scott Millet

How to Read Design Patterns – Each design pattern is presented in a template to help us decipher the pattern and learn what problems to solve with each design pattern.

GoF Template

  • Pattern Name and Classification – helps to form the vocabulary and define the job
  • Intent – what problems will the pattern solve
  • Also Known As – other Names used
  • Motivation – example scenario showing how the pattern is used to solve the problem
  • Applicability – what situations does the pattern apply to
  • Structure – graphical representation such as a UML diagram
  • Participants – all objects involved
  • Collaborations – how the objects work together
  • Consequences – benefits and liabilities
  • Implementations – gotchas and best practices
  • Sample Code – example implementation
  • Known Uses – real-life examples
  • Related Patterns – other patterns that work well or collaborate together

The author decided to use a more simplified template to describe the patterns in this book.

  • Name and Intent – purpose, uses, benefits, and motivation
  • UML diagram – graphical representation of generic template and implementation
  • Code Example – real-world implementation example

Creational

These patterns deal with constructing and referencing objects. Instantiating objects are abstracted away from the client creating loosely coupled code and adheres to the design principles (Single Responsibility and Separation of Concerns).

  • Abstract Factory – interface for families of related objects
  • Factory – class delegating responsibility of an object
  • Builder – separate object construction to enable various versions of an object
  • Prototype – classes can be cloned or copied using a prototype instance
  • Singleton – single instantiation of a class

Structural

These patterns deal with object composition and relationships.

  • Adapter – brings classes of incompatible interfaces together
  • Bridge – abstraction separated from its implementation
  • Composite – hierarchical objects grouped together and treated like a singleton
  • Decorator – dynamically surrounds and extends the behavior of a class
  • Facade – simple interface to control access of complicated interfaces and subsystems
  • Flyweight – efficiently share data between many small classes
  • Proxy – placeholder for complex classes that are costly to instantiate

Behavioral

These patterns deal with object communication – responsibility and algorithms. Complex behavior is encapsulated and abstracted from system control making for a more easily understood and maintainable complex system.

  • Chain of Responsibility – dynamically chain commands together
  • Command – encapsulate methods as objects to separate invoker from the command
  • Interpreter – evaluates sentences
  • Iterator – formalized navigation of a collection
  • Mediator – object between two other objects that do not know about each other allowing communication between them
  • Memento – restore previous state of an object
  • Observer – how classes find out other classes have changed
  • State – used by an object to alter its behavior
  • Strategy – alter behavior of an object at run time by encapsulating algorithms within a class
  • Template Method – control flow of algorithms and allow overrides by subclasses
  • Visitor – new class functionality without structure changes

How to Choose…

The first step in choosing the right pattern is knowing what patterns to choose from. Reading this book is a step in the right direction for expanding our knowledge on design patterns and principles.

Remember KISS…we don’t need to apply a pattern to everything we do. Will the solution benefit from the complexities of a particular pattern?

What is the intent of the pattern? Does it fit our problem? We should think about our issues at a high-level…abstract not details.

Many patterns are similar and we should look at each and every one to ensure we choose the best possible solution.

Can we encapsulate pieces of our solution that we know will change? We need to find the right pattern that will allow us to do this.

Let’s not forget to use pattern language once we decide which pattern to use.

Even after we learn about a pattern, we should strive to learn more…the more you know the better.

Some examples of patterns used in the .NET Framework:

  • ASP.NET Cache -> Singleton Pattern
  • New GUID Creation -> Factory Pattern
  • .NET 2 XML Classes -> Factory Pattern (1.0 did not)

At this point the book takes you into a coding sample…a piece of code that retrieves all products in a specified category.  We create a new project with 3 classes (Product, ProductRepository, and ProductService).

We start out learning that this piece of code has 3 problems for us to solve.

  1. Dependent class
  2. Untestable
  3. HTTP Context caching

This code breaks both the separation of concerns principle and the single responsibility principle.

The Dependency Inversion Principle

Depend on abstractions, not on concretions.

We need to decouple the ProductService class from the ProductRepository class by adding an interface. This will ensure that our ProductService class is less fragile, depends on an abstraction, and ignorant of implementation.

The Dependency Injection Principle

We still need to fix our ProductService class so that it is no longer responsible for the implementation and can focus on coordinating the retrieval of the product data. We do this by using Dependency Injection…injecting the implementation into the class constructor (Constructor Injection). Our ProductService class is now testable.

Other forms of DI are Method Injection and Property Injection.

Adapter Pattern

Converts the interface of a class into another interface clients expect.

We cannot create an Interface for the HTTP Context class, so we need to create a compatible interface that we can inject into our ProductService class.

Now we need to build the Adapter class that wraps the HTTP Context class and implements the operation the client expects. (The book provides the UML diagram that helps in understanding this pattern.)

By building the Adapter class to wrap the HTTP Context class, we can now switch out the cache method anytime we want without affecting the client.

Null Object Pattern

Now our constructor contains the ICacheStorage implementation…but what if we don’t want to cache our product data? We can create a NULL Object instead of passing a NULL reference all over the place. We simply pass the NULL Object to the constructor of our ProductService class.

I’m looking forward to the next chapter where we get to learn the Anatomy of an ASP.NET Application and the benefits of layering our application instead of the traditional approach.

Read Full Post »

Chapter 1 of Professional ASP.NET Design Patterns by Scott Millet

“There are no problems, only solutions.” –John Lennon

And We, Developers, provide these solutions. If we encounter something that other developers have already solved, we are sure to find a pattern involved in their solution.

Design patterns are simply blueprints for our solutions.

The original book Design Patterns: Elements of Reusable Object-Oriented Software known as the Design Patterns Bible is a collection of 23 patterns organized into 3 groups…written by the Gang of Four (Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides). Millet’s book promises to cover the practical knowledge necessary for us to use these design patterns.

The 3 Design Groups:

  • Creational – object construction and referencing
  • Structural – object relationships
  • Behavioral – object communications

Design patterns are necessary in expressing the intent of our solutions and promote good object-oriented design. By using and understanding design patterns, we can effectively communicate with our peers so that they can quickly decipher our solutions. Explaining the structure of our solution can be as little as saying the name of the design pattern used.

We must first thoroughly understand our problem before we can apply a pattern. We don’t always need to use a pattern. In some situations, the use of patterns can over-complicate the solution. We don’t need to apply patterns to everything we do. Each of the GoF patterns were designed to solve a particular problem.

The foundation for design patterns are the fundamental design principles. When we follow these principles, our code becomes more adaptable, flexible, and maintainable.

Common Design Principles:

  • Keep It Simple Stupid [KISS] – As the name implies, we must remember to keep our code simple and not over-complicate.
  • Don’t Repeat Yourself [DRY] – We should avoid repetition and not duplicate logic in the system. Abstraction
  • Tell, Don’t Ask – We should be telling our objects what to do instead of asking about them and deciding for ourselves what they should do. Loose coupling and encapsulation
  • You Ain’t Gonna Need It [YAGNI] – We should code only the functionality we need and nothing we think we might need in the future. TDD
  • Separation of Concerns [SoC] – We should try to dissect our code into distinct features or behaviors so that we can easily reuse and maintain these features or behaviors.

S.O.L.I.D. Design Principles (from the book Agile Principles, Patterns, and Practices in C# by Robert Martin [Uncle Bob]):

  • Single Responsibility Principle [SRP] – Objects should each have a single responsibility and a single reason to change.
  • Open-Closed Principle [OCP] – The internal behavior of a class should not be changed when adding new features or extending the class.
  • Liskov Substitution Principle [LSP] – A derived class should behave as its parent class.
  • Interface Segregation Principle [ISP] – Interfaces contain only the methods needed by the client.
  • Dependency Inversion Principle [DIP] – Code to an interface or abstract class rather than an implementation.

Dependency Injection [DI] – linked to DIP. Dependent classes (constructor, method, or property) are inverted to abstract classes or interfaces.

Inversion of Control [IoC] – linked to DIP. Control is inverted…the service is injected into the client instead of the client obtaining the service.

Fowler’s Enterprise Design Patterns (Patterns of Enterprise Application Architecture by Martin Fowler)

Fowler has categorized the patterns and provided a common language. We will see implementations of his patterns later.

(At this point in Chapter 1, I get a bit confused by the purpose of Chapter 1. We are supposed to be learning about the high-level basics of design patterns and principles, and yet at this point in the chapter we learn that in Chapter 3 we will learn about layering and using the traditional approach to separating the presentation, business logic, and data access layers. And since I’ve not read Fowler’s book, I’m not entirely sure if this and the next few sections relate to his patterns, but I’m guessing they are related. The next few pages introduce us to what we will learn later in the book.)

Domain Logic Patterns – Organizing Business Logic (learn more in Ch 4)

  • Transaction Script – Linear, procedural fashion…business use cases mapped to methods
  • Active Record – Matches closely to underlying structure
  • Domain Model – Abstraction of real objects

Object Relational Mapping – entity persistence and data retrieval (learn more in Ch 7)

  • Unit of Work – Maintains and coordinates transactional changes to objects as one action, and will roll back the entire transaction if a problem occurs.
  • Repository – Abstract, logical collection of objects (or aggregates) representing business entities.
  • Data Mapper – Hydrate objects from raw data and transfer info from objects back to database.
  • Identity Map – Ensures every database object is loaded only once.
  • Lazy Loading – Only load the database object when needed.
  • Query Object – GoF interpreter design pattern. OO query abstracted from database…properties and classes not tables and columns…with a translator to generate the SQL.

Web Presentation Patterns – separate presentation logic from business logic (learn more in Ch 8 )

  • Model-View-Presenter
  • Model-View-Controller
  • Front Controller
  • Page Controller

Base, Behavioral, and Structural Patterns – other patterns found in Fowler’s book

  • Null Object Pattern [aka Special Case] – Alleviates the need to check for NULL.
  • Separated Interface – Keeps interfaces in separate namespace or assembly to ensure concrete implementations hidden from the client.
  • Gateway – Access complex resources (API) via simple interfaces.

Design Methodologies

Test-driven Development [TDD] – Our tests shape the design of our solutions by writing tests first, then writing enough code to make our tests pass, and finally refactor to clean up our code. We end up with tests confirming the behavior of our code as well as documentation on what our code should or should not be doing.

Books on TDD:
Test Driven Development: By Example by Kent Beck
The Art of Unit Testing: With Examples in .NET by Roy Osherove
Professional Enterprise .NET by Jon Arking and Scott Millett

Domain-driven Design [DDD] – We first develop a full understanding of our business requirements, and then incorporate all the rules, logic, and business terminology into an abstract representation called a domain model.

Books on DDD:
Domain-Driven Design: Tackling Complexity in the Heart of Software by Eric Evans
Applying Domain-Driven Design and Patterns: With Examples in C# and .Net by Jimmy Nilsson
.Net Domain-Driven Design with C#: Problem – Design – Solution by Tim McCarthy

Behavior-driven Design [BDD] – TDD and DDD rolled up into a process that focuses on the system’s behavior…how it should behave not just that it works.

The next chapter promises to teach us how to read the GoF patterns and understand how to choose a pattern to use.

I’m realizing now that I’ve been applying many of these patterns to my code without actually understanding the reasoning behind it.

Read Full Post »

%d bloggers like this: