'NET Object Design - PowerPoint PPT Presentation

1 / 33
About This Presentation
Title:

'NET Object Design

Description:

Throwaway auto-generated, project specific. Eg Form1.vb ... TYPE AUTHORS: HIDE YOUR IMPEMEMTATION DETAILS. TYPE USERS: PROGRAM TO AN INTERFACE. ... – PowerPoint PPT presentation

Number of Views:35
Avg rating:3.0/5.0
Slides: 34
Provided by: nicholas55
Category:
Tags: net | autohide | design | object

less

Transcript and Presenter's Notes

Title: 'NET Object Design


1
.NET Object Design
  • Authoring Effective Types and Objects Hierarchies
  • Nick Wienholt
  • Nick_at_dotnetperformance.com

2
Agenda
  • Designing and implementing a single type
  • .NET specific.
  • Designing type interfaces so a group of types
    work well together
  • Applicable on any platform and with any
    technology.
  • Object-orientated design.
  • Component orientated aspects.

3
Basic Terminology
  • Type
  • Blueprint for an thing that exist in a program.
    Eg. Int32, String, System.Windows.Forms.Button.
  • Mostly synonymous with class, but class is also
    used by some languages to mean a particular group
    of types.
  • Interface
  • Provide a contract of a group of functions that a
    type must implement.
  • Object
  • Instance of a type.
  • Represented by a variable.
  • CODE EXAMPLE

4
Type Design
  • Two categories
  • Throwaway auto-generated, project specific. Eg
    Form1.vb
  • Business represent real entities, useful across
    many projects. Eg Employee, System.Net.Cookie

5
Type Design in .NET Who Cares?
  • Every type inherits from System.Object.
  • Types in the Base Class Libraries (BCL) expect
    certain behaviour from your types collection
    classes, serialization, garbage collector.
  • Users of your type should feel that it is a
    natural extension of the BCL.
  • Type inheritance now an issue.
  • Doing something properly reduces maintenance
    costs, and decrease bugs.

6
Type Design The First Big Decision
  • Reference vs. value types
  • Value types feel like language primitives.
  • Reference types feel like complex objects.
  • Value types cannot be derived from.
  • Value types do not support Finalization.
  • Value types usually composed of other value types
    like ints and doubles.
  • CODE EXAMPLE

7
Type Allocation
  • Reference types always heap allocated
  • Value types not embedded in reference types are
    stack allocated

Reference Effective Types, Peter Drayton
8
Type Allocation
  • Value types are boxed onto the heap when cast
    to System.Object

Reference Effective Types, Peter Drayton
9
Performance
  • Value type allocation is about an order of
    magnitude quicker than reference type allocation.
  • Mathematical operations on value types are
    quicker less indirection.
  • Boxing can make value types perform worse than
    reference types consider wrapping in reference
    types.
  • CODE EXAMPLE
  • Value types can perform poorly when used as
    method parameters, but ref (C)/ ByRef(VB) can
    eliminate this issue.

10
System.Object Public Methods
  • Equals test for equivalence. Static and
    Instance.
  • GetHashCode returns an integer for use as a key
    in a hash table.
  • ReferenceEquals test if two objects refer to
    the same heap-based object.
  • GetType returns a System.Type object that
    represents the actual type of the object.
  • ToString returns textual representation of the
    object. Default implementation returns type
    name. Override to return a better
    implementation.

11
Object Equality
  • Reference types default to reference equality.
  • Value types perform a bitwise comparison of
    member variables. Should be overridden for
    performance reasons.
  • CODE EXAMPLE
  • Reference types can override Equals to provide
    value-based equality.
  • Many BCL types do this eg System.String,
    System.Net.Cookie.
  • Type authors should follow established pattern
    for Equals method.

12
Overridding Equals
  • C
  • Reference equality, use is keyword to check
    type, and forward to operator for member
    variable checks.
  • public override bool Equals(object o)
  • if (o this) return true
  • return o is MyStruct this (MyStruct )o
  • public static bool operator (MyStruct a,
    MyStruct b)
  • //compare member variable
  • VB
  • Use TypeOf Is syntax instead of is, and
    compare member variables..
  • Operator overloading not possible.
  • Remember short-circuit evaluation (AndAlso,
    OrElse).
  • CODE EXAMPLE

13
GetHashCode The Contract
  • Objects overridding Equals MUST override
    GetHashCode.
  • Two objects that are Equal MUST have the same
    hash code.
  • Calls to GetHashCode MUST be safe no exceptions
    or circular references.
  • Subsequent calls to GetHashCode SHOULD return the
    same value not always possible. A type should
    document this aspect of its behavior.
  • GetHashCode SHOULD return an even distribution
    use all 32 bits.

14
Implementing GetHashCode
  • Use member variables to generate hash code,
    particularly initonly(IL), readonly(C), ReadOnly
    (VB) variables if you have any.
  • Ensure that data used in hash code calculations
    is also used in equality calculations.
  • Understand the hash code contract of your member
    variables, and ensure your type documentation
    reflects this behavior.
  • Make calls to GetHashCode quick cache expensive
    results, but ensure the Equality contract is not
    broken.
  • CODE EXAMPLE

15
GetHashCode (cont.)
  • Public Class BaseClass
  • Private i As Integer
  • Private j As Long
  • Public Overrides Function GetHashCode() As
    Integer
  • Return i.GetHashCode() Xor
    j.GetHashCode()
  • End Function
  • End Class
  • Public Class DerivedClass
  • Inherits BaseClass
  • Private k As Integer
  • Public Overrides Function GetHashCode() As
    Integer
  • Return MyBase.GetHashCode Xor
    k.GetHashCode()
  • End Function
  • End Class

16
Method Modifies
  • abstract (MustOverride) forms part of the types
    interface, but it is not possible to define a
    meaningful default implementation. Derived types
    MUST override.
  • static (Shared) method does not access member
    variable. Belongs to the type rather than a
    particular object.
  • CODE EXAMPLE
  • virtual (Overridable) member can be overridden
    by a derived type. The actual method called
    determined at runtime.
  • override (Overrides) provide a new
    implementation to a method signature inherited
    from a base type. May call the base type
    implementation if appropriate.
  • new (Shadows) similar to override, but gives
    very different behaviour. The actual method
    called is determined at compile time based on the
    variable type.
  • CODE EXAMPLE

17
Interfaces
  • Advertise that a type implements a specific
    behavior.
  • A type can implement as many interfaces as it
    wants.
  • Impart no per-object cost function layout
    joined together in a single method table per
    type.
  • Many BCL interfaces exists, and allow a class to
    be slotted into a framework pattern. Eg.
    Implement IEnumerable to be usable in a For Each
    loop.

18
BCL Interfaces
  • ICloneable type can have a new, identical copy
    generated.
  • IFormattable supports advanced ToString
    processing.
  • IEnumerable has collection class semantics.
  • ISerializable type has custom processing to
    controls it serialization.
  • IComparable support less than and greater than
    comparisons. CODE EXAMPLE

19
Whats missing
  • Mechanics of good type design have been defined.
  • Designing type interfaces so they are usable and
    extensible has NOT been defined this is the
    domain of -

20
Object Orientated Programming
  • Basic Definition combination of data and
    functionality to model real world entities.
  • Main Principles
  • Abstraction/ Encapsulation.
  • Polymorphism.
  • Inheritance.

21
Abstraction/ Encapsulation
  • Simple principle well supported by VB6/ COM.
  • TYPE AUTHORS HIDE YOUR IMPEMEMTATION DETAILS.
  • TYPE USERS PROGRAM TO AN INTERFACE.

22
Abstraction/ Encapsulation
  • How does the CLR support it?
  • Same as COM.
  • Properties are a first class concept.
  • Access modifiers for member variables
    (properties) and methods.
  • Interfaces offer ultimate encapsulation.
  • Simple concept easy to add to your types, easy
    to use on existing types.

23
Polymorphism
  • Client code calls a method of an interface.
  • The object supplying the implementation for that
    interface method is determined at runtime.
  • Basic principle of COM. Used to implement the
    For Each logic in VB6. In every For Each
    loop the VB runtime called the same function
    (IEnumUnknownNext), but each type that this
    method is called on supplies a different
    implementation.

24
Polymorphism
  • How does the CLR support it?
  • Virtual functions.
  • CODE EXAMPLE

25
Inheritance
  • Not supported under COM could be simulated with
    interface inheritance and aggregation(C only)/
    containment.
  • New feature of .NET.
  • Cross-language inheritance fully supported.
  • Supports human tendency to group everything into
    hierarchies.
  • CODE EXAMPLE

26
OO Is that the end of the story?
  • A pattern is a group of objects where each
    different object has a distinct responsibility.
  • Similar patterns emerge in many different types
    of programs.
  • Active area of commercial and academic research.
  • A good pattern can make a piece of software more
    understandable, maintainable and quicker to write.

27
Pattern Examples
  • Façade an object is responsible for condensing
    the interaction of a bunch of lower level objects
    into a coherent interface.
  • Strategy different algorithms that perform the
    same job are derived from a single interface.
    The code that uses the needs to use the
    algorithms is decoupled from the implementation.
  • Singleton allows only one instance of a object
    to be created. All clients share the same
    instance.
  • Object factory hides knowledge of exact type
    allocated. CODE EXAMPLE

28
Component-Orientated Programming
  • OO and Patterns doesnt provide everything
    demanded from a modern language. We also need
  • Delegates support type-safe object orientated
    call backs.
  • Events support reporting interesting events to
    other parties really a special case delegate.
  • Licensing integrated support for code
    licensing.

29
Component-Orientated Programming
  • Robust versioning policy huge area in the CLR
    and BCL.
  • Assemblies self-describing unit of
    functionality that form the boundary for many CLR
    support services, such as security and
    versioning.
  • Security framework ability for a type to
    document its security requirements, and for the
    CLR to enforce these.
  • Meta-data comprehensive and extensible system
    for a type to describe its needs, wants and
    desires.

30
Summary
  • System.Object and the BCL impart certain
    requirements that a type must obey comply with
    these, and your type will achieve full
    effectiveness.
  • Object Orientated Programming coupling of data
    and functionality together. Classes act and
    feel like real world entities.
  • Component Orientated Programming taking
    advantage of features provided in .NET to make
    your type more robust and powerful.

31
References
  • Type Design
  • MSDN System.Object documentation
  • Effective Types presentation at Conference.NET
    (http//develop.com/conferences/conferencedotnet/m
    aterials/N9.pdf)
  • Java design docs will help as .NET matures
    there will be much more material.
  • Object Orientated Programming
  • Tons of resources see Amazon.
  • My favourite Refactoring, Martin Fowler. Get
    to read about the mistakes BEFORE you make them.

32
References (cont.)
  • Component Orientated Design
  • Designing Component-Orientated Applications, Mary
    Kirtland. Dated now, but still very good.
  • Many .NET should be out soon.

33
Download Me From
www.DotNetPerformance.com
Write a Comment
User Comments (0)
About PowerShow.com