Presentation is loading. Please wait.

Presentation is loading. Please wait.

1 public sealed class Environment { private Environment() { } public bool HasShutDownStarted public bool HasShutDownStarted { get {... } get {... } } }

Similar presentations


Presentation on theme: "1 public sealed class Environment { private Environment() { } public bool HasShutDownStarted public bool HasShutDownStarted { get {... } get {... } } }"— Presentation transcript:

1 1 public sealed class Environment { private Environment() { } public bool HasShutDownStarted public bool HasShutDownStarted { get {... } get {... } } } } } Best Practices In Framework Design Jelle Druyts – Compuware What's wrong with this code?

2 Best Practices In Framework Design The Art Of Building A Reusable Class Library Jelle Druyts Compuware.NET Consultant

3 3 Your Speaker Jelle Druyts.NET Consultant Compuware Professional Services Framework Design & Development Technical Architect Mentor & Trainer Team System Focus Group Microsoft Consultancy Services Framework Design & Development WeFly247 Community Bloghttp://jelle.druyts.net MSDN Articleshttp://www.msdn.be Visual Studio User Grouphttp://www.visug.be

4 4 public sealed class Environment { private Environment() { } public bool HasShutDownStarted public bool HasShutDownStarted { get {... } get {... } } } } }

5 5 public sealed class Environment { private Environment() { } public bool HasShutDownStarted public bool HasShutDownStarted { get {... } get {... } } } } } It's an uncallable property!

6 6 Goals Is your API Usable? Reusable? Versionable? You will Understand that API design matters Recognize good API design Learn the API design process

7 7 Four Keys Of Framework Design The Power Of Sameness Framework Design Matters Tools For Communication The Pit Of Success

8 8 The Power Of Sameness

9 9 Oh... down to lock! The Power Of Sameness

10 10 So that's what that "key" thingy is for... The Power Of Sameness

11 11 (Well, actually, some people could use a refresher on that signal lever...) The Power Of Sameness

12 12 General Principle All cars work basically the same way You don't read the Owner's Manual Why should software be any different? You don't read Windows "Help and Support" Framework usage should be obvious Across different parts of your API Between different versions of your API The Power Of Sameness

13 13 Naming Conventions Quiz Compile this in your head: A: Compiler error B: Class declaration C: Variable declaration D: Other Now mentally compile this: address Home; Address home; The Power Of Sameness

14 14 Naming Conventions All types and publicly exposed members: PascalCasing Parameters: camelCasing Don't use Hungarian notation public class CMemberDoc { public int CompareTo(object objValue); public string lpstrName { get; } } public class MemberDoc { public int CompareTo(object value); public string Name { get; } } The Power Of Sameness

15 15 Prefixes & Suffixes Compile this: Follow the pattern Interfaces start with 'I' Exceptions end with...Exception Same for Attributes, EventArgs, Permissions IFoo foo = new IFoo(); throw new PrinterProblem(); public interface IFormattable {} public class NameAttribute : Attribute {} public class PrinterOnFireException: Exception {} The Power Of Sameness

16 16 Optimize Globally Prefer global consistency over a local deviation public class ArgumentNullException : ArgumentException { public ArgumentNullException () {} public ArgumentNullException (string paramName) {} public ArgumentNullException (string paramName, string message) {} } throw new ArgumentNullException ("Must pass an employee name"); // System.ArgumentNullException: Value cannot be null. // Parameter name: Must pass an employee name The Power Of Sameness

17 17 The Power Of Sameness Meet the developer's expectations Make consumers of your API feel at home Be consistent With yourself With the.NET Framework

18 18 Framework Design Matters

19 19 Simple Focus on top scenarios Namespace factoring Naming Use exceptions A well-designed framework must be... new EventLog().WriteEntry("Hello World"); // ArgumentException: Source property was not set // before writing to the event log

20 20 Explicitly Designed Create an API specification Review scenario samples Review API design A well-designed framework must be...

21 21 Part Of An Ecosystem IntelliSense Properties Window CLS Compliance Debugger A well-designed framework must be... [DebuggerTypeProxy(typeof(HashtableDebugView))] [DebuggerDisplay("Count = {Count}")] public class Hashtable {... }

22 22 Integrated Use common abstractions Watch out for common type name conflicts A well-designed framework must be...

23 23 Designed To Evolve Favor abstract classes over interfaces Easier for versioning (e.g. adding members) Control extensibility Virtual members are difficult to version Test your abstractions Implement interfaces Consume interfaces A well-designed framework must be...

24 24 Consistent Naming Consistency Common patterns and idioms Attributes Collections Async Pattern Dispose Pattern... A well-designed framework must be... The Power Of Sameness

25 25 Framework Design Matters A well-designed framework must be Simple Explicitly designed Part of an ecosystem Integrated Designed to evolve Consistent...to be able to survive

26 26 Tools For Communication

27 27 Wouldn't it be great… Luckily, there are Tools for Communicating

28 28 Why Communicate Focus on developer, not yourself Your developers can't read your mind Documentation alone is not enough Will this operation block? How do I customize this type? How should I use this class? Tools For Communication

29 29 You Leave Artifacts Framework Design Artifacts: NamespacesTypesMethodsPropertiesEventsFieldsConstructors... Tools For Communication

30 30 Namespaces Organizational principle to allow consumers to Find relevant functionality quickly Exclude less relevant functionality Not about implementation issues Security, identity, size, performance Guideline: 1-to-1 link with assembly name Not required though Tools For Communication

31 31 Classes A conceptual model for a thing which can hold state, perform actions,... Common API design problems Grab bag types (lack of cohesion) System.Runtime.InteropServices.Marshal Modeling overly abstract StreamReader vs. File Tools For Communication

32 32 Exceptions Encapsulation of error details used in a structured exception handling system Thrown when code fails to perform what it was written to do Common API design problems Using error codes rather than exceptions Defining far too many exceptions Exposing privacy related information (e.g. file paths) Tools For Communication

33 33 Enums Container for named constants Singular for regular enums BorderStyle.Fixed3D Plural for combinable "Flags" AnchorStyles.Left | AnchorStyles.Right Common API design problems Not specifying the enum values Using "magic" constants instead Adding "Enum" to the name Contrary to Exception, Attribute, EventArgs,... Tools For Communication

34 34 Constructors Facility to capture state for an instance at time of instantiation Common API design problem Doing too much work in the constructor Be lazy, only capture state public class XmlFile { private string data; public XmlFile(string fileName) { this.data = DownloadData(fileName); } Tools For Communication

35 35 Methods Expose actions or operations Common API design problem Using properties where methods should be used Tools For Communication

36 36 Properties Logical backing fields that encapsulate access to state Property getters Should be simple and unlikely to throw exceptions Use read only properties where appropriate Property setters Setting one should not affect other properties Should be settable in any order Common API design problem Property vs. Method confusion Tools For Communication

37 37 Properties vs. Methods Use a Property if The member is a logical attribute Use a Method if The operation is a conversion, such as ToString() The getter has an observable side effect The order of execution is important The method might not return immediately The member returns an array Tools For Communication

38 38 Fields Represent variables associated with an object or class Useful for exposing implementation details, thereby constraining your ability to evolve the framework In other words Never expose fields Always use properties Tools For Communication public class XmlFile { private string data; public string Data { get { return data; } } } public class XmlFile { public string Data; }

39 39 Events Used to inform a subscriber that something happened Always follow the Event Pattern Naming guidelines for Delegate, Event, EventArgs, the method that raises the event,... Common API design problems Using bad terminology: raised, not fired or triggered Not using verbs, e.g.: Click, Paint, DrawItem Not using strongly typed EventArgs Tools For Communication

40 40 Generics (.NET 2.0) Perform the same functionality for a variety of data types Generic types are substituted at runtime Use descriptive names prefixed with T Unless a single letter is self-explanatory Common API design problems Misusing generics by casting back to e.g. object or to an interface Use constraints on generic type parameter Tools For Communication public class Comparer where T : IComparablepublic class Dictionary

41 41 Tools For Communication Developers can't read your mind Documentation alone is not enough You communicate by leaving artifacts Different artifacts have different meanings Follow the guidelines and patterns

42 42 The Pit Of Success

43 43 The Pit Of Success In stark contrast to a summit, a peak, or a journey across a desert to find victory through many trials and surprises, we want our customers to simply fall into winning practices by using our platform and frameworks. To the extent that if we make it easy to get into trouble, we fail. - Rico Mariani

44 44 How do I read all the lines from a file?

45 45 Visual Studio 2003 Era “IO” seems like a reasonable place to start

46 46 Why did they make it inaccessible Backup, and try again… Why did they make it inaccessible Backup, and try again…

47 47 Open.. Looks like a good first step…

48 48 Hmm… OK, what do I do with a FileStream ?

49 49 Ok good, synchronous and asynchronous operations.. What the heck is that?

50 50 I think I am in the wrong place..

51 51 Back up, let’s try a different type

52 52 Ahh, ReadLine(), this looks more promising..

53 53 OK, how do you find the end?

54 54 Thanks goodness there was a sample

55 55 The Pit Of Success Way Developers fall into doing things the right way

56 56 Just what I need… Visual Studio 2005 Era

57 57 Ah, a string[] I know just what to do with that…

58 58 How simple!

59 59 The Pit Of Success Make the simple things simple and the hard things possible Avoid leading consumers down the wrong path Guide them into just "doing the right thing" Add value by subtracting features Adding features can remove value! Don't over-design Simple contracts are usually better

60 60 Key Points The Power Of Sameness Meet the developer's expectations Framework Design Matters Carefully design an API so it can survive Tools For Communication Different artifacts have different meanings The Pit Of Success Developers fall into doing the right thing

61 61 Framework Design Guidelines: Conventions, Idioms, and Patterns for Reusable.NET Libraries Brad Abrams' Blog: Krzysztof Cwalina's Blog: FxCop Microsoft Visual Studio Team System Compuware DevPartner

62 62 Thank You! Thanks for your attention I'll be happy to answer all your questions Right after the session Compuware Booth Community Booth: Ask-The-Experts VISUG Booth

63 63


Download ppt "1 public sealed class Environment { private Environment() { } public bool HasShutDownStarted public bool HasShutDownStarted { get {... } get {... } } }"

Similar presentations


Ads by Google