Framework EngineeringArchitecting, Designing, and Developing Reusable Libraries http://www.arload.net
손영수 arload@live.com동완이 아빠, 인옥이 남편!!EVA팀 리더PLoP패턴 저자AsianPLoP공동의장Blog http://www.arload.net
Framework is ..
Framework is…
Douglas C. Schmidt Says..Frameworks define “semi-complete” application that embody domain-specific object structures and functionality.
Libraries is..Application BlockDATABASEADTsMATHNETWORKINGApp SpecificLogicOO DesignInvocationsGRAPHICSGUIEventLoopSingletonStrategySelectionsReactorAdapterStateActive ObjectDesign PatternClass Library Component  Architecture
But Framework is ..Active ObjectStateNETWORKINGGUIControl – Flow (IoC)MATHReactorEventLoopApp SpecificLogicInvocationsCallbacksADTsSingletonAdapterDATABASEGRAPHICSApplication FrameworkComponent Architecture
Why Do You Need Framework?ProductivityAvoid Duplication
Why Do You Need Framework?De Facto War
Welcome toMy FrameworkJourney!
Seed References“Framework Engineering”, TechED 2007 Europe“Framework Design Guidelines” , Addison WesleyKrzysztof CwalinaProgram Manager on .NET Framework Team
5 Topics..DOPAV
OrganizationThe most powerful design toolO
Project Management TriangleScopeTimeCostO
OrganizationProject Management Triangle + 1O
Do understand how organizational structure, culture, and decision making processes impact your product. O
Conway's lawIf you have 4 groups working on a compiler,you’ll get a 4-pass compiler.O
Conway's lawO
Conway's Clean State ApproachO
Your Company Culture Is ..Voluntary ??O
Your Company Culture Is ..Familial ??O
Remember Your Company Culture ..OPeremptory
Organizational InfluencesSize of OrganizationSimple DesignConsistency DesignFocus on 80/20 RulesSmall TeamO
Organizational InfluencesSize of OrganizationPowerful DesignLack ConsistencyRemove RequirementsLarge TeamO
Organizational InfluencesOrganization’s Culture/BiasesCustomer-FocusedEnd-2-End ScenariosO
Organizational InfluencesOrganization’s Culture/BiasesTechnology-FocusedLong Lasting ArchitectureO
Decision Making Process is..呼兄呼弟O
Solution ??Give this book your boss..
Planning Ensuring we are building the right thing P
P
P
SkyscrapersPeanut ButterFocus: featuresResults: stability, incremental improvements, not great end-to-end scenariosFocus: scenarios Results: Excitement, breakthroughs, but beware of leaving existing customers behind P
Moderation (中庸)MileStone  = Scenarios + FeatureVision statementRTMFeature completeReleaseTestingPlanningM1M2Technology PreviewBeta 1Beta 2RC1P
ArchitectureEnsuring the long term health of the frameworkA
Right Way??Choose right types.A
Taxonomy of TypesLibraries , Primitives, AbstractionsA
PrimitivesVery little policy (behavior design decisions)Stable designCommonly appear in publicly accessible APIsAlmost impossible to evolve/change design;        any design changes have huge breaking change impact on other APIsExample: Int32, StringA
LibrariesDefinition:Libraries are types that are not passed 		between componentsExamplesEventLog, Debug. Easy to EvolveLeave old in, add new oneBeware of duplication!A
AbstractionsDefinition:Abstractions are interfaces or classes with unsealed members that are passed between components.ExamplesStream, IComponentHard to EvolveUnfortunately, pressure to evolveA
Primitive Oriented DesignA.K.A. “Handle based design” (functional)Great evolvability, poor usability (sometimes)Low level stable primitives + high level reusable components with limited dependencies other than to the primitivesE.g. Type.GetType(object) – works, but not as convenient as Object.GetTypeA
Extension Method for primitive.. C# 3.0 New Featurenamespace MyCompany.StringManipulation {     public static class StringExtensions{public static bool IsNullOrEmpty(this string s){ 		return String.IsNullOrEmpty(s);		  }     }}…using MyCompany.StringManipulation;string message= “hello world”;if(message.IsNullOrEmpty()){ 	Console.WriteLine(“EMPTY”);}
Component Oriented DesignRich APIs with lots of features, thus with lots of dependenciesGreat usability, poor evolvabilityGood for higher level components, not for the core of a platformA
Do Manage Dependencies..AA
Component is ..Lego, Plug ??A
Component is .... a set of types that ship and evolve as a unit.A
Types of DependenciesA
API DependencyComponent A has an API dependency on component B, 	if a type in B shows in the publicly accessible API surface of a type in A. This includes:Base types and implemented interfacesGeneric parameter constraintsReturn types and parameters of membersApplied attributesNested typesA
Implemenatin DependencyIf a type in A uses a type in B in its implementation.Hard Dependencies (required to run)Soft Dependencies (optional)A
Circular DependencyComponent A depends on component B  andComponent B depends on component A (even indirectly).A
Solution is Layering..A
Solution is Layering..A
WPFXMLBCLReflectionADependency Management
상황을 파악하는 좋은 방법DSM (Dependency Structure Matrix)
간단한 DSM
잘 계층화된 DSM
엄격한 계층화를 유지한 시스템의 DSM
불완전한 계층구조를 가진 시스템Circular Dependency 발생.
또 하나의 도구– Code Metrics
xDepend(Ndepend, Xdepend, CDepend)NDepend - http://www.xdepend.com
Solution is..Create a new package.A
circular dependencyGUICommAnalysisProtocolModem ControlComm ErrorDatabaseMessageManagerA
Indirect circular dependencyAXBYA
Use Interface.AXY<<interface>>BYBA
Heavy Depedency..A
Solution is IoCA
Heavy Dependency.// your APIpublic class Tracer {MessageQueue mq = new MessageQueue(…);	public void Trace(string message){ 	mq.Send(message);	}} // your customer’s program that is hard to testTracer tracer = new Tracer();public void ProcessOrder(Order order){	tracer.Trace(order.Id);	…}A
Inversion of Control// your better APIpublic abstract class TraceListener {	public abstract void Trace(string message);} public class Tracer {TraceListener listener;	public Tracer(TraceListener listener){		this.listener = listener; 	}	public void Trace(string message){ 			listener.Trace(message);	}} A
Dependency Injection// your customer’s program that is easier to testTracer tracer = new Tracer(new FileListener());public void ProcessOrder(Order order){	tracer.Trace(order.Id);	…}A
Dependency Injection Containers// customer’s program that is even easier to testTracer tracer = container.Resolve<Tracer>();public void ProcessOrder(Order order){	tracer.Trace(order.Id);	…}Check outDI Containers (a.k.a. IoC Containers):autofac, Castle Windsor, PicoContainer.NET, Spring.NET, StructureMap, Unity, nInject and others.http://www.nInject.orgA
Packaging PrinciplePackage Cohesion PrincipleREP (Release Reuse Equivalency)CCP (Common Closure Principle)CRP (Common Reuse Principle)Package Coupling PrincipleADP (Acyclic Dependencies Principle)SDP (Stable Dependencies Principle)SAP (Stable Abstraction Principle)ARobert C. Martin, Principle of Package Architecturehttp://www.objectmentor.com/resources/articles/Principles_and_Patterns.pdf
Do balance advances with compatibility.A
Types of “Compatibility” BackwardCross-VersionForwardA
Cross-Redist.A
A
Establishing Compatibility BarDefine what’s a “breaking change”This definition depends on the objectiveE.g. Enable portable code between Silverlight and .NET FrameworkE.g. Enable cross-version portability?A
Avoid duplication and overlap.A
Team SpaceShow and TellProblem SpacePLoP – Capable, Productive and Satisfied Patterns for Productivityhttp://hillside.net/plop/plop98/final_submissions/P54.pdfA
When to Replace Existing APIsWhen the new technology is “10x better”Make sure you understand the impact on the ecosystemWhat would happen if the BCL team added a new String?What’s the migration path for code using the old API?Support Automatic Migration Tool.  (VB -> VB.NET, .NET 1.0 -> .NET 2.0)Provide Code Based Migration Manual. COM+ -> WCF , ASP.NET Web Service -> WCFA
DesignThis is where quality happensD
Is using your framework correctly like…Running across a desert?D
You need Feedback.D
Do design APIs by     first writing code samples for the main scenarios       and then defining the object model to support the code samples.D
Code SamplesD
Read Filestatic void Main(string[] args){StreamReadersr = File.OpenText("MyFile.txt");            string s = sr.ReadLine();            while (s != null){                s = sr.ReadLine();Console.WriteLine(s);}}D
Feedback (Read File)static void Main(string[] args){foreach (string s in File.ReadAllLines("MyFiles.text"))   {Console.WriteLine(s);}}D
Object Model ListingD
Framework Design Studio Assembly ExploerProject -> Add -> AssemblyDDownload here - http://code.msdn.microsoft.com/fds
Framework Design Studio Assembly Review CommentD
Framework Design StudioCompare API VersionsD
Framework Design StudioCompare API VersionsRed is removed, Green is added,Grey means inherited.D
Framework Design StudioExporting to Microsoft WordTools -> Export to DocumentD
Do treat simplicity as a feature.D
KISS (Keep It Simple! Stupid!)Remove Requirements (ATAM).Reuse Existing Concepts or APIsAdjust Abstraction Level Consider framework users(experience, knowledge)Three ExampleD
Domeasure, measure, and measure!D
Specification Document: QualitiesPerformance Goals (XML Parser..)Baseline: What do is the best my API could do?Measure delta from the baselineThreat Models (Security ..)Threat: What is the worst that my component could do?Mitigate the threatsKeep a balance between many other qualities      you want your framework to have (ATAM)D
 The POWER oFSamenessD
 Read the manual??When you pick up your rental car….Push the seat all the way backFind an NPR stationFind the exitD
Oh, down to lock…D
How to use a key…D
Oh, you push the PRESS button…D
Who actually needs this data?D
Why you don’t read manuals ???You know how to drive your carAll cars work basically the same wayYour rental car is a carTherefore, you can drive your rental carThat is…The power of samenessD
Static Analysis Tool http://en.wikipedia.org/wiki/List_of_tools_for_static_code_analysisD
DevelopmentThe bits customers get, … or notV
Branches and Integrations- Feature Crewhttp://www.codeplex.com/BranchingGuidance/Wiki/View.aspx?title=Feature%20Crews%3a%20How%20Microsoft%20Does%20ItV
Avoid integrating unfinished features.V
Feature Complete & Quality GatesFunctional SpecificationDeveloper Design SpecificationTest PlanThreat ModelAPI reviewArchitectural ReviewDependency ManagementStatic AnalysisCode CoverageTesting (Unit and Integration Tests)0 BugsPerformance V
Do pay your debt.V
Milestone QualityVision statementRTMFeature completeReleaseTestingPlanningM1M2Technology PreviewBeta 1Beta 2RC1Milestone QualityV
Milestone Quality (MQ)Initiatives that are hard to do in regular milestonesLarge productivity and efficiency improvementsInfrastructure changesFor example, a new source control system Refactoring of fragile subsystemsInternal implementation documentationBugs backlogV
SummaryDounderstand how organizational structure, culture, and decision making processes impact your product. Avoidpeanut-butter in Scenario Based Application.Domanage your dependencies.Dobalance advances with compatibility.Avoidduplication and overlap.Do design APIs by first writing code samples for the main scenarios and then defining the object model to support the code samples.Do treat simplicity as a feature.Domeasure, measure, and measure!Avoidintegrating unfinished features.Do pay your debt.
ResourcesKrzysztof Cwalina, Brad AbramsFramework Design Guidelines:Conventions, Idioms, and Patterns for Reusable .NET Librarieshttp://channel9.msdn.com/pdc2008/PC58/http://www.gotdotnet.com/team/fxcop
ResourcesDouglas C. Schmidt (PLoP Editor, POSA 2, 4 Writter)JAWS: An Application Framework for High Performance Web Systemhttp://citeseer.ist.psu.edu/81775.html  (En)http://www.devpia.com/net2/EvaCast/Lecture/?cu=view&r=11  (Kr)Ralph Johnson (GoF , Design Patterns)Evolving Frameworkshttp://st-www.cs.uiuc.edu/users/droberts/evolve.html  (En)http://arload.wordpress.com/2008/09/15/evolvingframeworks/  (Kr)
ResourcesRobert C. MartinPrinciples of Package Architecture (Design Principles and Design Patterns)http://www.objectmentor.com/resources/articles/Principles_and_Patterns.pdf (En)  http://www.devpia.com/net2/EvaCast/Lecture/?cu=view&r=108 (Kr)For Korean People..Load to Architecthttp://www.arload.netEvaCast  (Online Free Lecture)http://www.evacast.net
최근 저서 및 곧 나올 저서..
곧 나올 저서..
Question?이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-동일조건변경허락 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.  This work is licensed under Creative Commons Korea Attribution 2.0 License.

Framework engineering JCO 2011