Transcript
Page 1: C:\Fakepath\Combating Software Entropy 2
Page 2: C:\Fakepath\Combating Software Entropy 2

ARC202 - Combating Software Entropy with Design Patterns and Principles

Hammad RajjoubSolutions Architect @ InfusionMicrosoft MVP

Page 3: C:\Fakepath\Combating Software Entropy 2

Cogito, Ergo , Sum

Microsoft MVP – Connected Systems (5+ yrs)Solutions Architect at Infusion

The coolest company in townDevelop. Design. Venture. Join us!

Speaker, Author & Community LeaderI do: Blog + Twitter + PodCastBing me http://www.bing.com/search?q=hammadrajjoub

Page 4: C:\Fakepath\Combating Software Entropy 2

Agenda

Why is Software Complex?

What is bad design?

How to Fix it?

Summary

References

QnA

Page 5: C:\Fakepath\Combating Software Entropy 2

Why is Software ComplexWriting new software

Mandated to develop new systemsGenerally from scratch But still mostly relying on existing libraries and frameworksReal-world problems are sometimes complex

Modifying Existing SoftwareFind that ‘bug’ and ‘fix’ itAdd a new exciting featureReview and refactor to a better design

Page 6: C:\Fakepath\Combating Software Entropy 2

What is bad design?

Page 7: C:\Fakepath\Combating Software Entropy 2

Bad design is...

Rigid

Fragile

Immobile

Hard to change!

A single change break lots of other

code

Can’t be ‘extended’

Page 8: C:\Fakepath\Combating Software Entropy 2

How to fix it?

Using design principles and practicesThe Single Responsibility PrincipleThe Open Closed PrincipleLiskov Substitution PrincipleDependency Inversion Principle

Using Software Design Metrics

And yes a whole lot of refactoring

Page 9: C:\Fakepath\Combating Software Entropy 2

Single Responsibility PrincipleNone but Buddha himself must take the responsibility of giving out occult secrets...

E. Cobham Brewer 1810–1897.Dictionary of Phrase and Fable. 1898.

SRP

Page 10: C:\Fakepath\Combating Software Entropy 2

The Single responsibility principal

"A responsibility is a reason to change, a class or module should have one, and only one, reason to change."

Page 11: C:\Fakepath\Combating Software Entropy 2

The Single Responsibility Principal

Responsibility is a ‘Reason for change’Each responsibility is an axis of changeThere should never be more than one reason for a class to changeDijkstra’s SoC: Separation of ConcernsThis helps us evaluate a class ‘s

exposure to change

Page 12: C:\Fakepath\Combating Software Entropy 2

BusinessPartnerValidtor ModuleExample:

Page 13: C:\Fakepath\Combating Software Entropy 2

BusinessPartnerValidator

BusinessPartnerValidator

TradeDB

What is wrong here: Changes if DB changes or Business Logic Changes

Page 14: C:\Fakepath\Combating Software Entropy 2

Counterparty Validator – Iter 1internal class BusinessPartnerValidator{ public void AssertValid(Trade t) { var sql = "SELECT COUNT(*) FROM BusinessPartner WHERE name=@Name"; using (var conn = CreateOpenConnection()) { var cmd = new SqlCommand(sql, conn); cmd.Parameters.Add("@Name", SqlDbType.VarChar); cmd.Parameters["@name"].Value = t.BusinessPartnerName; var count = (Int32) cmd.ExecuteScalar(); if (count != 1) throw new InvalidBusinessPartyException(t.BusinessPartyName); } }

...

Where is the business logic? Hidden by database code.

Page 15: C:\Fakepath\Combating Software Entropy 2

BusinessParty Validator – Iter 2 internal class BusinessPartnerValidator { private readonly BusinessPartnerValidator businessPartnersource;

public BusinessPartyValidator(BusinessPartnerSource BusinessPartySource) { this.businessPartnerSource = BusinessPartnerSource; }

public void AssertValid(Trade t) { if (BusinessPartnerSource.FindByName(t.BusinessPartnerSource) == null) throw new InvalidBusinessPartnerException(t.BusinessPartnerName); } }

BusinessPartyValidator now has a single responsibility

Page 16: C:\Fakepath\Combating Software Entropy 2

Refactored BusinessPartnerValidator

BusinessPartnerValidator

Trade

DB

BusinessPartnerSource

What's its job?Classes must have an identifiable single responsibility.

Page 18: C:\Fakepath\Combating Software Entropy 2

The Open Closed Principle

Realise that generally systems outlive their expected timelinesAll software entities should be closed for change and opened for extensionYour design modules should never changeYou should just extend the behaviour

Page 19: C:\Fakepath\Combating Software Entropy 2

There is a theory which states that if ever anybody discovers exactly what the Universe is for and why it is here, it will instantly disappear and be replaced by something even more bizarre and inexplicable. There is another theory which states that this has already happened. Douglas Adams (1952 - 2001)

Liskov Substitution Principle

Page 20: C:\Fakepath\Combating Software Entropy 2

The Liskov substitution principal

“Functions that reference a base class must be able to use objects of derived classes without knowing it."

Page 21: C:\Fakepath\Combating Software Entropy 2

Using Inheritance for OCP?

RateCalculatorTrade

OptionFee

Page 22: C:\Fakepath\Combating Software Entropy 2

Trade Rate Calculation

public decimal CalulateRate(Trade t){ if (t is Fee) { return 1.0m; }

return t.BaseAmount/t.QuotedAmount;}

-Use of convention rather than design-Fragile: sensitive to any change in Trade Fee Hierarchy

Page 23: C:\Fakepath\Combating Software Entropy 2

Better Trade Rate Calculation public abstract class Trade { ...

public abstract decimal Rate { get; } }

public class Fee : Trade { ...

public override decimal Rate { get { return 1.0m; } } }

- Open for extension- Design forces implementation

Page 24: C:\Fakepath\Combating Software Entropy 2

The Liskov substitution principal

Be vary of ‘is-a’ relationshipLSP is prime enabler of OCPImportant Pointers for LSP compliance:

Hollow methods (Degenerate Functions)Sub type = substitutable

Page 25: C:\Fakepath\Combating Software Entropy 2

It may be that the old astrologers had the truth exactly reversed, when they believed that the stars controlled the destinies of men. The time may come when men control the destinies of stars. Arthur C. Clarke (1917 - ), First on the Moon, 1970

Dependency Inversion

Page 26: C:\Fakepath\Combating Software Entropy 2

Dependency Inversion Principal

-High level modules should not depend upon low level modules. Both should depend upon abstractions.

-Abstractions should not depend upon details. Details should depend upon abstractions.

Page 27: C:\Fakepath\Combating Software Entropy 2

BusinessParty Validator

BusinessPartyValidator

TradeDB

BusinessPartySource

High Level (Less Stable)

Low Level(More Stable)

Introduce stability with abstraction

Page 28: C:\Fakepath\Combating Software Entropy 2

Better BusinessPartner Validator

BusinessPartnerValidator

Trade

DB

BusinessPartySource

<Interface>IBusinessPartnerSource

Page 29: C:\Fakepath\Combating Software Entropy 2

Extensible BusinessParty Validator

BusinessPartyValidator

Trade

DB

DbBusinessPartySource

<Interface>IBusinessPartnerSource

WSBusinessPartnerSource

Cloud

Page 30: C:\Fakepath\Combating Software Entropy 2

DI & IoCIoC is key part of FrameworksInterfaces, Closures & EventsHollywood Principal (Don’t call us, We will call you)IoC is a very general name and hence the Dependency Injection*Suits Test Driven DevelopmentNumber of dependencies indicate stability

*http://martinfowler.com/articles/injection.htm l

Page 31: C:\Fakepath\Combating Software Entropy 2

Software Design Metrics

Page 32: C:\Fakepath\Combating Software Entropy 2

Some Key Design Metrics - Ca

Afferent Couplings - CaThe number of other packages that depend upon classes within the package is an indicator of the package's responsibility.

BPackage

APackage

PackageClass

Page 33: C:\Fakepath\Combating Software Entropy 2

Some Key Design Metrics

Efferent Couplings – CeThe number of other packages that the classes in the package depend upon is an indicator of the package's independence.

BPackage

APackage

PackageClass

Page 34: C:\Fakepath\Combating Software Entropy 2

Some Key Design MetricsInstability – I = Ce / (Ce + Ca)

This metric is an indicator of the package's resilience to change. The range for this metric is 0 to 1, 0 indicating a completely stable package1 indicating a completely instable package.

Page 35: C:\Fakepath\Combating Software Entropy 2

Use Visual Studio Code MetricsMaintainability IndexCyclomatic ComplexityDepth of InheritanceClass CouplingLines of CodeCode Coverage

Page 36: C:\Fakepath\Combating Software Entropy 2

Further reading

Page 37: C:\Fakepath\Combating Software Entropy 2

What else can I do?ISP: Interface Segregation Principle Avoid fat interfacesREP: The Release Reuse Equivalency Principle The granule of reuse is the granule of release. CCP: The Common Closure Principle Classes that change together are packaged together.CRP: The Common Reuse Principle Classes that are used together are packaged together.SDP: The Stable Dependencies Principle Depend in the direction of stability.

Page 38: C:\Fakepath\Combating Software Entropy 2

Strategic Closure

No significant program can be 100% closedClosures cant be completeClosures must be ‘Strategic’Stability metrics can indicate hotpotsDesigner must choose the changes against which her design should be closed

Page 39: C:\Fakepath\Combating Software Entropy 2

Summary

Remember your application will outlive your expectationFollow these design principlesBe Agile!Refactor ++Use Code Metrics

Page 40: C:\Fakepath\Combating Software Entropy 2

ReferencesUncle Bob http://butunclebob.com/ArticleS.UncleBob.PrinciplesOfOod

Agile Principles, Patterns and Practices in C#

Martin Fowler’s Blog: http://martinfowler.com/bliki/

Page 41: C:\Fakepath\Combating Software Entropy 2

question & answer

Page 42: C:\Fakepath\Combating Software Entropy 2

www.microsoft.com/teched

Sessions On-Demand & Community

http://microsoft.com/technet

Resources for IT Professionals

http://microsoft.com/msdn

Resources for Developers

www.microsoft.com/learning

Microsoft Certification & Training Resources

Resources

Page 43: C:\Fakepath\Combating Software Entropy 2

Complete an evaluation on CommNet and enter to win an HTC HD2!

Page 44: C:\Fakepath\Combating Software Entropy 2

© 2010 Microsoft Corporation. All rights reserved. Microsoft, Windows, Windows Vista and other product names are or may be registered trademarks and/or trademarks in the U.S. and/or other countries.The information herein is for informational purposes only and represents the current view of Microsoft Corporation as of the date of this presentation. Because Microsoft must respond to changing market conditions, it should not be interpreted to be a commitment on the part of Microsoft, and Microsoft cannot guarantee the accuracy of any information provided after the date of this presentation. MICROSOFT MAKES NO WARRANTIES, EXPRESS,

IMPLIED OR STATUTORY, AS TO THE INFORMATION IN THIS PRESENTATION.