Monday, November 15, 2010

[Tutorial] S.O.L.I.D. quality code in C#
Part6: Dependency Inversion Principle (DIP)

In most of the applications high level modules are directly linked to low level modules (in other words are dependent on them). High level modules contain most of the time complex logic whereas low level modules serve for basic and primary operations. It is evident that this may lead to dependency problems between those modules.

An application that shows this problem could be structured like this: the Presentation Layer is dependent on the Business Layer which itself is dependant on the Data Layer.

Fig8_DIP_Before

In this layer design, modifications to low level modules force modifications to high level modules that are dependant on them. This leads to high level modules which can not be reused in different technical contexts.

The Dependency Inversion Principle (DIP) therefore explains that high level modules must not depend on low level modules. Both of them have to depend on abstractions. Furthermore abstractions must not depend on details but instead details have to depend on abstractions.

The underlying concept is that abstractions serve as links between high level and low level modules. Abstraction are most of the time expressed via interfaces but the Factory Design Pattern may also be used.

After having applied the principle, the class in the following example is completely independent from other classes, all references being expressed via interfaces.

DIP_After

In the next example, which is based on the Factory Pattern, the class ValidationManagerFactory is used to resolve all dependencies. It associates an object that is implementing the IValidatable interface with an object of type ValidationManager.

DIP_After2

The introduction of interfaces allows the inversion of dependencies, which leads in the layers example to layers that are completely independent from each other.

Fig9_DIP_After

To sum it up, the Dependency Inversion Principle (DIP) provides a high level of flexibility because modules really get reusable easily. All rigid links that may exist between modules are broken up. But by adding a higher level of abstraction, the code gets more complex to understand and to maintain. So this principle must be applied with caution.


Share/Save/Bookmark

Sunday, November 14, 2010

[Tutorial] S.O.L.I.D. quality code in C#
Part5: Interface Segregation Principle (ISP)

This principle demands that clients should not be forced to depend on interfaces they do not use. An entity (class, service, …) is client of an interface, if it uses a class that implements the interface.

Applying this principle is fairly easy. A similar methodology to the one already used in the Single Responsibility Principle (SRP) must be applied. When developing services, it is often necessary to have classes with multiple responsibilities. The Interface Segregation Principle (ISP) permits to limit class coupling between the different classes in this case.

In the following example the class BusinessObject has multiple responsibilities (implements multiple functional groups) like creation, update, validation and deletion.

Fig6_ISP_Before

ValidationManager_Before

PersistManager_Before

Please note the usage of the interface IBusinessObject instead of the class BusinessObject. This approach is called Interface-Based Programming. It allows programming against interfaces instead of concrete classes. Thus, all classes implementing the interfaces required by those functions can be passed as parameters to them. This already provides some degree of independency, but there are still flaws in this class design.

Each client only uses some aspects of the defined interface:

  • The ValidationManager class only uses methods concerning validation
  • The PersistManager class only uses methods concerning persistence

Modifications of methods concerning the validation imply modifications to the whole interface IBusinessObject and indirectly to the PersistManager class. Even though the PersistManager class does not even use those methods !!

We need to find a solution to achieve that different clients only depend on functionality and access methods that they really use.

The first step consists of regrouping all methods that belong to the same functional group in specialized interfaces. Similar to what we already did for the Single Responsibility Principle (SRP) only this time with specialized interfaces as output.

The interface IBusinessObject is separated into two more specialized interfaces IPersistable and IValidatable. It then inherits from those newly created interfaces.

Fig7_ISP_After

Now it is possible to use the different functionalities Persistence and Validation separately as well as using both at the same time. Modifications can be done without any impact between those two functional groups, they evolve independently from each other.

The next step is to replace the current usage of the interface IBusinessObject  with the specialized interfaces IPersistable and IValidatable where applicable.

ValidationManager_After

PersistManager_After

To conclude I would like to underline that in terms of decoupling multiple specialized interfaces are better that one big global interface that contains everything. This approach can also be applied to abstract classes since they might somewhat be considered as interfaces.


Share/Save/Bookmark

Wednesday, November 10, 2010

[Tutorial] S.O.L.I.D. quality code in C#
Part4: Liskov Substitution Principle (LSP)

This principle is complementary to the Open Closed Principle (OCP). It suggests that methods which use a certain class must be able to use its derived classes without even knowing them - a base class must be substitutable by its derived classes, without the necessity of changing any code in the method using it.

There are two violations of this principle: one more conceptual and the other more functional.

The conceptual violation is most of the time easy to detect because it violates the Open Closed Principle (OCP) at the same time. It consists of determining the concrete types of objects to do the adapted treatment in methods. Verifying concrete types or using casts may indicate this violation.

The following code example shows such a case :

LSP_Code_Before

In this example the PrintShapeArea(…) method needs to know the concrete type of the passed object for being able to call the adapted method which returns the correct shape area.

When a new shape type needs to be added, the PrintShapeArea(…) method needs to be modified (violation of OCP). Furthermore object that are used in this context get tightly coupled to the class that contains the PrintShapeArea(…) method.

To prevent this kind of violation the usage of cast, is, as and GetType (working with object types) must be avoided at a maximum.

A good solution is to apply the Open Closed Principle (OCP) as already explained. If we take the same class design from last time, we need to add a GetArea(…) method to the abstract base class Shape. The derived classes need to override this method with the correct shape area calculation.

Fig5_LSP_After

The PrintShapeArea(…) method can now be simplified and is now able to handle all derived classes transparently without knowing them. The base class and its derived classes get substitutable.

LSP_Code_After

The functional violation is much harder to find because it is not due to an error in class design but a modification of internal behavior. Methods may expect certain behaviors of classes they use. Derived classes may change this behavior and the results of operations may differ from the expected results.

The solution to this problem is the Design By Contract approach. This approach assures that functional constraints are respected all the time. It assures that the initial behavior stays the same and that objects always have the correct states.

There are three types of contracts:

  • pre-conditions: constraints and state before treatment
  • post-conditions: constraints and state after treatment
  • invariants: concerned objects must not change during treatment

The necessary classes and methods for the Design By Contract approach are already integrated in .NET Framework 4.0 in the CodeContracts namespace System.Diagnostics.Contracts. But they can easily be added in older versions of.NET.


Share/Save/Bookmark

Monday, November 8, 2010

[Tutorial] S.O.L.I.D. quality code in C#
Part3: Open Closed Principle (OCP)

The Open Closed Principle says that all software entities (like classes and methods) must be open for extension but closed for modification. This sounds odd, because those two rules seem to be contradictory. This article shows how to combine them and how to make your source code even more extensible and maintainable.

So how can a class or method at the same time be open for extension but closed for modification ?

A quick answer is : leave existing code unchanged and allow for extensions only by adding new code. This minimizes at the same time the possibility of regressions, behavior changes and bugs. The application gets more robust and provides a higher level of maintainability. Extension can be done without worrying about the overall stability of the application. All very good things !!!

But the code needs to be correctly structured to achieve this goal. Lets look an example, which shows the principle in action. In this example we start from an implementation that does not respect the Open Closed Principle. Then I apply the principle and you will see how the quality of the code will be ameliorated.

The current implementation contains a single class Shape with a property called ShapeType (possible values Square and Circle).

Fig3_OCP_Before

Furthermore, the application contains the method DrawAllShapes(…), that displays the different shapes on the screen.

Code_OCP

This approach has a major flaw: if new shapes are added, then existing code needs to be changed (ShapeType, DrawAllShapes, etc..). This makes the code hard to understand, to extend and to maintain over time.

So what could be the solution in this case ? In object oriented programming we know the concept of inheritance, which should be applied to avoid the necessity to change existing code.

The complete class design must be changed !

A new abstract class Shape with an abstract method Draw(…) should be created. Then different classes for each shape type, that inherit from the abstract Shape class, need to be defined. They contain the specific code that serves for the display on the screen.

Fig4_OCP_After

The DrawAllShapes(…) method must now be adapted and simplified in the last step. It should only contain the call to the Draw(…) method of objects that are treated.

Code_OCP_After

If you now get the business need to add a new shape type, you only need to create a new class that inherits from the abstract class and implement the special Draw behavior. So extensions become very easy to do. And you do not touch the existing structure anymore (or at least only in very rare cases).

When respecting this principle, your code gets correctly encapsulated, easily reusable and much simpler to maintain.


Share/Save/Bookmark

Sunday, November 7, 2010

[Tutorial] S.O.L.I.D. quality code in C#
Part2: Single Responsibility Principle (SRP)

This is the first principle that I want to show you that will help you to create code that is much less coupled. Code based on this principle becomes much easier to maintain, to evolve and to understand.

Most developers have the tendency to put too much functionality into a single class. Sometimes this is due to bad design, sometimes this is due to the extension of existing code.

Behaviors that should be independent are put together. Those behaviors get tightly coupled and dependant on each other. Changes to a single behavior might impact the other parts of the class (other behaviors).

This may lead to regressions and problems when code needs to be maintained or extended.

The Single Responsibility Principles explains that a class should only have one and a single responsibility. It should serve for only one purpose. Behaviors that belong together must be encapsulated in a single class. But behaviors that are independent from each other must be located in different classes.

When developing new code (or when extending existing code) there needs to be a first phase of conception and design. Within this phase an unordered list of all behaviors and methods is generated, necessary to fulfill the needs of the application (or describing the extensions).

Based on this list the developer creates the class model. Each class generated has a single responsibility. He takes each of the entries in the list and either affects them to existing classes or creates new classes (if the responsibility is not yet covered).

When looking at the following (very simple) example it becomes clear what needs to be done.

Fig1_SRP_Before

The class Modem has more than one responsibility:

  • Connection Handling (Dial and HangUp)
  • Data Transfer (Receive and Send)

To avoid this tight coupling 3 different class must be created that may then be used together in aggregation or composition.

Fig2_SRP_After

Thus each class class has now only one responsibility:

  • Connection : Connection Handling (Dial and HangUp)
  • Data Channel : Data Transfer (Receive and Send)
  • Modem : Regroups the necessary functionality

Modifications to Connection Handling and Data Transfer can now be done independently in each corresponding class without any impact.


Share/Save/Bookmark

Tuesday, November 2, 2010

[Publication] Article in French Programmez Magazine on Visual Studio 2010 and UML Modeling

You can find an article of 4 pages concerning Visual Studio 2010 and UML Modeling in the French Programmez magazine No.135 written by me, Guillaume Rouchon and Loic Baumann.

cover

First Page (low resolution)

Second and Third Page (low resolution)

Fourth Page (low resolution)

The article is written in French but as always I will write some English articles on my Blog in the next weeks. So stay tuned if you are interested in knowing how to use Visual Studio 2010 for UML Modeling.


Share/Save/Bookmark

Friday, October 29, 2010

[PDC – Visual C# 5.0] Asynchronous Programming (async / await)

Anders Heijlsberg presented the future features and extensions of the next release of Visual C# 5.0 during his PDC talk.

The most interesting feature is the new approach to asynchronous programming. Today it is possible but not always very easy to go fully asynchronous. Developers have to write complex code that gets quickly very ugly and incomprehensional.

This is going to change in the future. The next version of Visual C# will get new keywords (async / await) that greatly help to simplify asynchronous programming.

Developers will write their code in a synchronous approach (nothing will change at all). And they will be able to make the code asynchronous just by using the “async” and “await” keywords in the right places.The rest in abstracted out from the programmer.

As it was already done in the Parallel Programming approach, the goal of Microsoft is to keep Asynchronous Programming as simple as possible. Developers may concentrate on added business value and not the environment. These new language features will make C# and .NET even more beginner friendly and will help developers to be much more productive.

You can download the CTP version that you can use for R&D and testing here.

MSDN page that fully explains the new async features :

http://msdn.microsoft.com/fr-fr/vstudio/async%28en-us%29.aspx


Share/Save/Bookmark

[Information] Free Ebook on Windows Phone 7 Programming

Get this free eBook on Windows Phone 7 programming written by Charles Petzold and published by Microsoft Press. It contains 24 chapters and around 1000 pages that will help you build Windows Phone 7 application fast. This is an exclusive possibility to learn how to program for the new version of Windows Phone.

ProgWinPhone7

Get the PDF here. And the code samples here.


Share/Save/Bookmark

Tuesday, October 19, 2010

[Tutorial] S.O.L.I.D. quality code in C#
Part1: Principles of coding

After multiple years of experience in the software development sector it becomes clear that the principles of object oriented programming are often misused, not correctly applied or simply just ignored by many developers.

Even if the basics seem to be easy, there are often big problems in their realization which may lead to:

  • Bugs
  • Bad code structure
  • Unmaintainable code
  • Bad performance
  • Code that is just not understandable

The S.O.L.I.D. design principles that help to prevent all of these problems and allow the writing of high quality code are:

  • Single Responsibility Principle
  • Open-Closed Principle
  • Liskov Substitution Principle
  • Interface Segregation Principle
  • Dependency Inversion Principle

I am going to present and explain each of these principles in detail. I am also going to show examples in C# that will help you to understand how to apply them in your code.


Share/Save/Bookmark

Monday, September 6, 2010

[Publication] Article in French Programmez Magazine on S.O.L.I.D. Software Design Principles

You can find an article of 5 pages concerning S.O.L.I.D. Software Design Principles (applied in C#) in the French Programmez magazine No.133 written by me and a colleague.

cover 

First Page (low resolution)

Second and Third Page (low resolution)

Fourth and Fifth Page (low resolution)

The article is written in French but as always I will write some English articles on my Blog in the next weeks. So stay tuned if you are interested in knowing how to write clean and robust code using the S.O.L.I.D. Principles.


Share/Save/Bookmark

Thursday, June 10, 2010

[VS 2010] Visualization & Modeling Feature Pack for VS 2010

Microsoft has released its first Visualization & Modeling Feature Pack for Visual Studio 2010 Ultimate. It adds new functionality to Visual Studio 2010 and is completely free for MSDN Subscribers. The new UML features really help and are indispensible in your daily work when modeling and working with code at the same time.

Feature Pack Content

Increased Visualization Support

  • Visualization of native C++ code
  • Visualization of WAP / Web Sites / ASP.NET MVC code

Increased UML support

  • Source Code Generation from UML Class diagrams
  • UML Class Diagram Generation from Source Code
  • Architecture Explorer can finally be used to populate the Modeling Store in Modeling Projects (we waited for that!)
  • XMI 2.1 Import of UML Class / Sequence / Use Case elements
  • Create and view links from Work Items to model elements

Increased support for Layer Diagram Extensibility

  • Creation and validation of Layer Diagrams for C and C++ native code
  • Possibility to write custom code to create, modify, and validate Layer Diagrams.

MSDN Download Link

You can download it from here (MSDN Subscribers only):
http://msdn.microsoft.com/en-gb/vstudio/ff655021.aspx


Share/Save/Bookmark

Monday, May 31, 2010

[Tutorial] Migration to Framework .NET 4.0 & Visual Studio 2010
Part4: Obsolete Types and Members

The last article concerned migration issues and their possible solutions. This part of the series talks about obsolete functionality in the latest version of the .NET Framework and what happens if you still need to use those functionalities.

Usage of obsolete types and members

Each new .NET Framework version adds new types and members that provide new functionality. Existing types and members change. Sometimes types are replaced because the technology that they where used for was deprecated. In other cases new types and members are more complete and easier to use.

To assure the highest possible compatibility with preceding versions, those obsolete types and members are not directly deleted. Instead they are marked as obsolete using the attribute “ObsoleteAttribute”. They still work even in the latest .NET Framework versions.

If code that is using obsolete types or members is recompiled, the compiler might raise warnings or in some cases even errors (which must be modified). Code that was compiled with an old version of the compiler and that uses obsolete types and members will however always execute correctly, even after the migration to the .NET 4.0 Framework.

Obsolete Types

  • All types that reside in the System.Data.OracleClient namespace are deprecated. You should use the Oracle specific provider within ODP.NET.

  • Passport authentification is not supported anymore, you should use the LiveID instead. All associated types are obsolete.

  • All types in System.Web.Mail should not be used anymore, instead you should use those within the System.Net.Mail namespace.

  • The System.Web.Mobile.dll assembly that was used for mobile development is deprecated.

  • XmlDataDocument and XslTransform are deprecated, you should use XslCompiledTransform instead.

Obsolete Members

  • Some methods in LINQ needed to be modified for the implementation of PLINQ (parallel processing within LINQ)

  • Concerning the Entity Framework, the ApplyPropertyChanges function is replaced by the ApplyCurrentValues function and the SaveChanges function expects an enumeration as parameter instead of a Boolean value

  • Multiple methods within System.Diagnostics.Process are replaced by their equivalents in 64 bits

  • Members that were already obsolete since .NET Framework 2.0 still exist. They were not yet deleted (but should should not use them anymore in your developments).

Additional Information in MSDN

For further information on this subject and much more obsolete types and members, please visit Microsofts MSDN site: 
http://msdn.microsoft.com/en-us/library/ee461503%28v=VS.100%29.aspx
http://msdn.microsoft.com/en-us/library/ee471421%28v=VS.100%29.aspx


Share/Save/Bookmark

Sunday, May 30, 2010

[Tutorial] Migration to Framework .NET 4.0 & Visual Studio 2010
Part3: Migration Issues and their Solutions

The last part of the series showed the Visual Studio 2010 Conversion Wizard. This part explains what needs to be done in case of migration issues.

Most of the changes in .NET 4.0 do not require any code modifications. But sometimes you will encounter problems and that is where you will need to apply some workaround solutions. I am going to show you some examples of these solutions in this article.

Core

Access to configuration files was modified. If your configuration file is named “MyApplication.config” you will have to rename it to “MyApplication.exe.config”.

ASP.NET

When using the Conversion Wizard within Visual Studio 2010 to convert your ASP.NET 3.5 applications to ASP.NET 4.0, the Web.config file is also modified in the process. It contains new parameters that might not be exactly configured as you like it.

  • The display mode of some controls was modified. To deactivate this new display mode change the following parameter:
    <pages controlRenderingCompatibilityVersion="3.5" />

  • The validation mode of HTTP requests was ameliorated (cross-site scripting protection). To reestablish the preceding behavior add the following parameter:
    <httpRuntime requestValidationMode="2.0" />

  • The UrlEncode and HtmlEncode methods were modified. Please verify that they work as expected.

  • The page parser for ASPX and ASCX is stricter than before. You should fix any invalid markup.

Windows Presentation Foundation (WPF)

The XAML parsing was modified. XAML attributes cannot contain more than one period anymore.

The following are valid examples after the migration:
<button Background="Red"/>
<button Button.Background="Red"/>

The following is not accepted anymore after the migration:
<button Control.Button.Background="Red"/>

Additional Information in MSDN

For further information on this subject and much more workaround solutions, please visit Microsofts MSDN site:  http://msdn.microsoft.com/en-us/library/ee941656%28v=VS.100%29.aspx


Share/Save/Bookmark

Wednesday, May 26, 2010

[Tutorial] Migration to Framework .NET 4.0 & Visual Studio 2010
Part2: Conversion Wizard Visual Studio 2010

The last article showed basics on how to migrate to Framework .NET 4.0. This article shows the Conversion Wizard of Visual Studio 2010.

Conversion Wizard Visual Studio 2010

Visual Studio 2010 provides a Conversion Wizard that helps converting old projects and solutions to the new Visual Studio 2010 format (similar to the conversion wizard within Visual Studio 2008 ).

VS_Conversion_Wizard1VS_Conversion_Wizard2 VS_Conversion_Wizard3 VS_Conversion_Wizard4

The converted projects and solutions replace the existing ones so take care to do some backups before the migration.

If projects cannot be converted, they are marked as unavailable in the Solution Explorer until the problems are resolved and they are correctly converted.

To migrate multiple projects or solutions it is possible to create batch files and execute the migrations in batch mode.


Share/Save/Bookmark

[Tutorial] Migration to Framework .NET 4.0 & Visual Studio 2010
Part1: Version Compatibility and Simple Migration

The new version of .NET Framework 4.0 was released last month together with Visual Studio 2010. An important question is how to migrate existing applications. This series of articles provides information on how to proceed and what you can expect when doing the migration.

Version Compatibility

In most cases the .NET 4.0 Framework is fully compatible with applications that were developed using past versions of the .NET Framework (1.1, 2.0, 3.0, 3.5).

Version Compatibility assures that an application that was developed using a past version of .NET should also work on a more current version. Moreover, source code that was written using an old version should also compile on the current version.

Simple migration

After installing the new Framework version, the old assemblies do not need to be  recompiled. Instead you may execute old and new assemblies Side-By-Side (SxS). It is now possible to to have different versions of the CLR running in the same application and they can even communicate with each other.

If you need to force the usage of CLR 4.0, you only need to add an application configuration file that contains the version specifications. You do this by specifying one or multiple  <supportedRuntime version="vX.X" /> elements (the first being your preferred version).

The following values are currently possible:

Framework .NET Version

Version String

4

v4.0

3.5

v2.0.50727

2.0

v2.0.50727

1.1

v1.1.4322

1.0

v1.0.3705

Example of a configuration file for .NET 4.0:

examplefile

If you need to migrate a large amount of applications it makes more sense to do the migration on machine level. There is the registry key “OnlyUseLatestCLR” that serves for this purpose.

  • Open a registry editor (example: regedit.exe)
  • Go to [HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\
    .NETFramework]
  • Set the value of OnlyUseLatestCLR=dword:00000001
  • For 64 bit systems you also need to set the key within [HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\.NET Framework]

To deactivate la functionality, you only need to reset the value of the key to OnlyUseLatestCLR=dword:00000000.


Share/Save/Bookmark

Tuesday, May 4, 2010

[Publication] Article in French Programmez Magazine on .NET Framework 4.0 migration

You can find an article of 3 pages concerning .NET Framework 4.0 migration in the French Programmez magazine No.130 written by me and a colleague.

cover

First Page (low resolution)

Second and third page (low resolution)

The article is written in French but I plan to write some English articles on my Blog in the next weeks. So stay tuned if you are interested in knowing how to proceed when migrating your .NET applications (1.1, 2.0, 3.5) to the latest .NET Framework version!


Share/Save/Bookmark

Friday, April 9, 2010

[Methodology] The Rise And Fall Of Waterfall

Please take a look at this video about the rise and fall of the waterfall process and its evolution into the RUP process.

I am a big practitioner and fan of UML and the RUP process, which I still think is one of the best processes on the market, so I found it quite amusing.

 


Share/Save/Bookmark

Wednesday, March 24, 2010

[Event] MCT & Educator Virtual Summit

A quite interesting event for all Microsoft Certified Trainers is coming this year in April (and it’s for free !!!).

This is the place to connect to other MCTs and get information on the latest technologies and training techniques. Don’t hesitate and inscribe yourself.

You can find the agenda here:
http://www.mctvirtualsummit.com/Uploads/MCTEducatorVirtualSummitDownloadAgenda.pdf

 

MCT Virtual Summit


Share/Save/Bookmark

Wednesday, November 25, 2009

[Architecture] Microsoft Application Architecture Guide 2nd Edition now available

The second edition of Microsoft’s Guide on Architecture by “patterns & practices”, that was also presented during TechED 2009, is now available for download as PDF and online as HTML version. There is even a printed version that you can buy at Amazon.

MSArchitectureGuide

The guide covers all current architecture styles and serves as “Map” to help us in our architectural decisions from a Microsoft point of view. It has changed since the last versions that were available on CodePlex.  Meaning that a review is also interesting for people, that already know and use the guide in their daily work.

The guide helps you to:

  • Understand the underlying architecture and design principles and patterns for developing successful solutions on the Microsoft platform and the .NET Framework.
  • Identify appropriate strategies and design patterns that will help you design your solution's layers, components, and services.
  • Identify and address the key engineering decision points for your solution.
  • Identify and address the key quality attributes and crosscutting concerns for your solution.
  • Create a candidate baseline architecture for your solution.
  • Choose the right technologies for your solution.
  • Identify patterns & practices solution assets and further guidance that will help you to implement your solution.

In my opinion it is a useful guide that does a good job in presentation all the rich possibilities of today's architecture and project solutions to customer problems. The first chapters also serve as an introduction to software architecture.

If you are interested in architecture and working in the Microsoft environment I highly advise you to take a look and integrate it into your architectural decision making.

Here are the links to the different versions of the guide: 


Share/Save/Bookmark

Monday, November 23, 2009

[Tutorial] How to use Layer Diagrams in Visual Studio 2010 for Architecture Validation Part 4

Last time we defined layers in our Layer Diagram and added projects and folders. We validated the architecture and saw that there were errors. You might already have guessed it but the explanation is, that the Layer Diagram just does not reflect the real architecture inside the source code of our example project.

Two Choices: Change Source or Diagram

We now have two choices: either we have carefully designed our layers and the errors show that the source code is not compliant, in which case we would have to change the source code, or we decide to change the layer definitions (what we will be doing for our example).

One of the really strong parts of Layer Diagrams is that they help to understand source code from a very high point of view. Imagine trying to understand the source code structure without having any documentation and just the source code. This was a time consuming task without the help of Layer Diagrams but will completely change as of today with Visual Studio 2010.

Change the Layer Diagram

Ok lets change the Layer Diagram and see what the real code structure looks like in terms of layers.

  • Open the Source Code and the Layer Diagram and validate the Architecture
  • Double click on the first error and you see that there are references to Business Objects (ex: ExpenseCategory) in the Presentation Layer projects

Archi_Layer_Validation18

  • Add a new dependency between the Presentation Layer and the Business Layer

Archi_Layer_Validation19

  • Re-validate the architecture and you see that there are still 29 errors, this time there seems to be dependencies inside the Data Layer that are causing the problem

Archi_Layer_Validation20

  • Since the Data Layer also uses Business Objects from the Business Layer we need to change the dependency from a one-way to a bidirectional dependency

Archi_Layer_Validation21

  • Re-validate the architecture and you see that there are still 2 errors, this time there seems to be dependencies inside the Business Layer that are causing the problem

Archi_Layer_Validation22

  • Since the Business Layer also uses interfaces and declarations from the Service Layer we need to change the dependency from a one-way to a bidirectional dependency

Archi_Layer_Validation23

  • Re-validate the architecture and you see that there are no more errors, we finally have a Layer Diagram that perfectly reflects the code structure of the source code

Archi_Layer_Validation24

Summary

We saw how to use the Architecture Explorer and the Layer Diagram to build a layer structure that matches existing code or that may serve to assure, that new projects start and stay with a healthy design. We saw how to validate manually if the layer constraints are fulfilled or broken and how to fix problems.

You may even add the Architecture Validation to your build and check-in scripts in TFS. Thus automating the verification and assuring that your projects retain the initial design that your architects designed carefully.


Share/Save/Bookmark