C:\Fakepath\Combating Software Entropy 2

Post on 15-May-2015

505 views 1 download

Tags:

Transcript of C:\Fakepath\Combating Software Entropy 2

ARC202 - Combating Software Entropy with Design Patterns and Principles

Hammad RajjoubSolutions Architect @ InfusionMicrosoft MVP

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

Agenda

Why is Software Complex?

What is bad design?

How to Fix it?

Summary

References

QnA

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

What is bad design?

Bad design is...

Rigid

Fragile

Immobile

Hard to change!

A single change break lots of other

code

Can’t be ‘extended’

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

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

The Single responsibility principal

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

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

BusinessPartnerValidtor ModuleExample:

BusinessPartnerValidator

BusinessPartnerValidator

TradeDB

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

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.

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

Refactored BusinessPartnerValidator

BusinessPartnerValidator

Trade

DB

BusinessPartnerSource

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

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

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

The Liskov substitution principal

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

Using Inheritance for OCP?

RateCalculatorTrade

OptionFee

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

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

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

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

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.

BusinessParty Validator

BusinessPartyValidator

TradeDB

BusinessPartySource

High Level (Less Stable)

Low Level(More Stable)

Introduce stability with abstraction

Better BusinessPartner Validator

BusinessPartnerValidator

Trade

DB

BusinessPartySource

<Interface>IBusinessPartnerSource

Extensible BusinessParty Validator

BusinessPartyValidator

Trade

DB

DbBusinessPartySource

<Interface>IBusinessPartnerSource

WSBusinessPartnerSource

Cloud

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

Software Design Metrics

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

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

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.

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

Further reading

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.

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

Summary

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

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

Agile Principles, Patterns and Practices in C#

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

question & answer

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

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

© 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.