Selected Software Engineering Books

Methodologies / Requirements
Testing / Quality
Web Services and .Net
Java (and other languages)
User Interfaces
General Textbooks on Software Engineering
Configuration Management
Design / UML
Open source tools
Web development
More Textbooks and Classics
Professional Development

Thread Safe code

Thread-safety is a computer programming concept applicable to multi-threaded programs. A piece of code is thread-safe if it is reentrant or protected from multiple simultaneous execution by some form of mutual exclusion.

Thread-safety is a key challenge in multi-threaded programming. It was once only a concern of the operating system programmer but has of late become a commonplace issue to be tackled by the everyday programmer. In a multi-threaded program, several threads execute simultaneously in a shared address space. Every thread has access to virtually all the memory of every other thread. Thus the flow of control and the sequence of accesses to data often have little relation to what would be reasonably expected by looking at the text of the program. This violates the principle of least astonishment. Thread-safety is a property aimed for so as to minimize surprising behavior by re-establishing some of the correspondences between the actual flow of control and the text of the program.

The requirement for thread-safety highlights the inherent tension in multi-threaded programming: the need for multiple threads to access the same shared data, and the need for a shared piece of data to be accessed by only one thread at any given time.

It is not easy to determine if a piece of code is thread-safe or not. However, there are several indicators that suggest the need for careful examination to see if it is unsafe:

  • Accessing global variables or the heap.
  • Allocating/freeing resources that have global limits (files, sub-processes, etc.)
  • Indirect accesses through handles or pointers

A subroutine that only uses variables from the stack, depends only on the arguments passed in, and calls other subroutines with similar properties is reentrant, and thus thread-safe.

As seen in the definition, there are a few ways to achieve thread-safety:

  • Reentrancy: Basically, writing code in such a way as to avoid sharing of data across threads.
  • Mutual exclusion: Access to shared data is serialized using mechanisms that ensure only one thread is accessing the shared data at any time. If a piece of code accesses multiple shared pieces of data, there needs to be an enormous amount of care in using mutual exclusion mechanisms — problems include race conditions, deadlocks, livelocks, starvation, and various other ills enumerated in many operating systems textbooks.

A commonly used idiom combines both approaches:

  • Make changes to a private copy of the data, and finally, atomically update the shared data from the private copy. Thus, most of the code would be close to re-entrant, and the amount of time spent serialized would be small.

The concept of exception safety is closely related, since it again deals with (synchronous) flows of control not directly correlated to the text of a program.

Hash Tables Vs. Binary Search Trees

This is one of my favorite programming interview questions: “What’s the difference between Hash Tables and Binary Search Trees?”.

Hash Tables Binary Search Trees
Algorithm Keys are mapped to values by using hash functions. Hash functions transform the key to a numeric index (usually by calculating an integer value from the key first, and then applying a “modulo arraysize” operation). This index identifies an array element (“bucket”), where all corresponding values reside (values which all stem from keys with equal hash value). The key must still be looked up within the bucket, but as hashing algorithms are supposed to ensure a good hash value distribution, hence small bucket size, this lookup is very fast. The bucket array may have to be resized dynamically when a certain load factor is reached. Node-based tree data structure, where every node contains one record (key-only, or key and value), and has a left subtree (with smaller keys) and a right subtree (with larger keys); hence keys must be comparable. Self-balancing trees, like red-black-trees, keep their height as small as possible for fast searching and inserting.
Java Implementations Hashtable
HashMap
HashSet
TreeMap
.NET Implementations Hashtable
Dictionary
HashSet
SortedDictionary
SortedList
C++ STL Implementations std::unordered_map
std::unordered_set
std::map
Sorted NO YES
Range Search NO YES
Runtime Complexity Inserting: O(1) (normal case), O(N) (worst case, only with bad hash algorithm)
Searching: O(1) (normal case), O(N) (worst case, only with bad hash algorithm).
More details.
Inserting: O(log(n)) (when balanced)
Searching: O(log(n)) (when balanced)
More details.
Implementation Notes Equal objects must produce the same hash code, however unequal objects need not produce distinct hash codes. Equals() implementations must be reflexive, symmetric, transitive, consistent. More details.
.NET’s ValueType.Equals() and GetHashCode() methods are based on reflection, hence slow; you should provide your own implementation in structs.
CompareTo() implementations must be reflexive, symmetric, transitive, consistent.More details.

Replace invalid characters with empty strings by using Regular expression

using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
using System.Xml;
using System.IO;

namespace Billing
{
    public class StringUtils
    {
        public static String CleanInput(string str)
        {
            // Replace invalid characters with empty strings.
            return Regex.Replace(str, @"[^\w ]", "");
        }
    }
}

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

What is REST?

It is rather style or pattern of development resource-oriented web applications. Beauty of REST is that its really easy to understand and basically you are using REST everyday but may not noticing that. REST works on top of HTTP protocol, but is is not protocol itself. It seems to me that it actually appears with HTTP/1.1 but only with Roy Fieldingwork it became well understood, defined and attractive.

REST popularized by such applications as twitter, flickr, bloglines, technorati etc. And of cause, by Ruby On Railsframework.

REST vs. SOAP

Sure, REST is not first who approaches issue of using recourses in Web, it rather trendier new kind in a block. We know bunch of web technologies, SOAP, WSDL, ATOM, WS-*, WCF, ODATA and many many more.. So, what are the difference?

Major difference is that all above are protocols, but REST is style. This has pros and cons. Protocol’s are more strict and heavyweight, with a number of rules, formats etc. SOAP is using XML as data exchange format, REST could work any format depending on client needs. SOAP is using its own security model, REST relies on HTTP and web server security. SOAP requires tools, REST learning curve is small and less less reliance on tools. SOAP designed to handle distributed computing environments, REST assumes a point-to-point communication model.

But my opinion is simplicity always win against complexity. Key popularity of REST is because is simple, easy understand by developers and as a result – implemented in applications. My believe that SOAP and other heavyweight protocols will slightly die more and applications will be using REST.

 ASP.net MVC and REST

Developers of ASP.net MVC framework designed it to be REST compatible. In the level of framework, there is an URL routing system (System.Web.Routing) that allows you easily follow REST design principles. It gives you total control over your URL schema and its mapping to your controllers and actions, with no need to conform to any predefined pattern.

So, basically ASP.net MVC web applications development is: create a controller class (LoginController for instance), implement number of actions (Index, CheckCredentials) and map those actions to particular URL. For instance http://mysite.com/login mapped to LoginController.Index method, that handles GET request from server and return View, containing Login form. http://mysite.com/login/check mapped toLoginController.CheckCredentialsmethod, that handles POST and checks users credentials.

It is much more easier to create web applications API’s with MVC framework. TheActionResult is polymorphic, so it could return HTML, JSON, XML results (and you are free to implement own ActionResult, for any format you might need).

Performance tests

Performance tests focused on determining or validating performance characteristics of the product under test when subjected to workload models, and load volumes beyond those anticipated during production operations.

  • How many users can the application handle before “bad stuff” happens
  • How much data can my database/file server handle?
  • Are the network components adequate?

Stress test

These tests are all about determining under what conditions an application will fail how it will fail and what indicators can be monitored to warn of an impending failure.

What are the benefits?

  • Determining if data can be corrupted by over stressing the system
  • Estimating how far beyond the target load an application can go before causing failures and errors in addition to slowness
  • Establishing application monitoring triggers to warn of impending failures
  • Ensuring that security holes are not opened up by stressful conditions.
  • Determining the side effects of common hardware or supporting application failures.
  • What risks does it address?
  • What happens if we underestimated the peak load?
  • What kind of failures should we plan for?
  • What indicators should we be looking for to intervene prior to failure?

Endurance test

A performance test focused on determining or validating performance characteristics of the product under test when subjected to workload models and load volumes anticipated during production operations over an extended period of time.

What are the benefits?

  • Slow memory leaks
  • Insufficient file storage capacity
  • Performance degradation as a result of an increased in stored data
  • Overnight, automatic virus definition updates on a server causing performance degradation
  • What risks does it address?
  • Will performance be consistent over time?
  • Are there slow growing problems that we haven’t detected?
  • Is there external interference that we didn’t account for?

Spike test

A performance test focused on determining or validating performance characteristics of the product under test when subjected to workload models and load volumes that repeatedly increase beyond anticipated production operations for short periods of time.

What are the benefits?

  • Memory leaks
  • Disk I/O (thrashing)
  • Slow return to steady – state
  • What risks does it address?
  • What happens if we underestimated the peak load?
  • What kind of failures should we plan for?
  • What indicators should we be looking for to intervene prior to failure?

Capacity testing

Capacity testing is related to stress testing .It determines your server’s ultimate failure point. You perform capacity testing in conjunction with capacity planning.

You use capacity planning to plan for future growth, such as an increased user base or increased volume of data. For example, to accommodate future loads you need to know how many additional resources (such as CPU, RAM, disk space, or network bandwidth) are necessary to support future usage levels.

Capacity testing helps you identify a scaling strategy to determine whether you should scale up or scale out.

What are the benefits?

  • Provide actual data to the capacity planners to validate or enhance their models and/or predictions.
  • Conduct various tests to compare capacity planning models and/or predictions.
  • Determine current usage and capacity of existing system to aid in capacity planning.
  • Provide usage and capacity trends of existing system to aid in capacity planning.

What risks does it address?

  • Validate that capacity planning models represent reality.
  • Ensure capacity planning remains in sync with actual system usage and growth patterns

How to: Collect Event Tracing for Windows (ETW) Data

Event Tracing for Windows (ETW) is an efficient kernel-level tracing facility that enables profiler log kernel or application-defined events. The data that is collected from the event provider can be viewed only by using the /Summary:ETW option of the VSPerfReport command-line tool. You can use this report to determine where performance issues occur in the application.

To enable event trace providers
  1. In Performance Explorer, right-click the performance session, and then click Properties.

  2. In the Property Pages, click the Windows Events properties.

  3. In the Select event trace provider to collect data from list, select the event providers that you want to use to profile your application.

Visual Studio 2010 Diagnostic Tool

Visual Studio 2010 add-ins

Productivity Power Tools

  • No More Extension Resets – This version of the Productivity Power Tools will be the last which resets the extensions.
  • Find – Quick find & incremental search now pops up at top right-hand corner of the editor.
  • Enhanced Scrollbar – Icons overlay the scrollbar to show edits, breakpoints, bookmarks, errors, warnings, etc.
  • Middle-Click Scrolling – Use your scroll wheel to quickly scroll through your document.
  • Organize Imports for Visual Basic – Sort the imports logically and remove the ones that aren’t being used.

    Regex Editor

    JScript Editor Extensions

    PowerCommands for Visual Studio 2010

    Microsoft All-In-One Code Framework Sample Browser

    PHP Language Support

  • jQuery Globalization Plugin

    Microsoft released a prototype of a new jQuery Globalization Plugin that enables you to add globalization support to your JavaScript applications.

    jQuery Globalization Plugin includes globalization information for over 350 cultures ranging from Scottish Gaelic, Frisian, Hungarian, Japanese, to Canadian English.  We will be releasing this plugin to the community as open-source.

    You can download our prototype for the jQuery Globalization plugin from our Github repository:

    http://github.com/nje/jquery-glob

    You can also download a set of samples that demonstrate some simple use-cases with ithere.

    ASP.NET error CS0016: Could not write to output file

    If you attempt to run an ASP.NET application hosted on IIS7.0 running on Windows Home Basic or Premium (Vista or Windows 7, x86 or x64), you may receive the following error:

    error CS0016: Could not write to output file 

    The problem occurs because Windows Home Basic and Premium lack Windows Authentication. You can solve this problem with a few mouse clicks:

    1.  Run the Internet Information Services (IIS) Manager program.  It can be found in the Start > Administrative Tools menu.  You may have to edit the Start Menu properties to show the Administrative Tools folder.

    2.  Select the Application Pools item in the Connections pane.

    3.  Right-click on the application pool in which you are running your ASP.NET application.  On my PC, this was the DefaultAppPool.

    4.  Select Advanced Settings from the popup menu.

    5.  In the Process Model section, set the Identity to LocalSystem.  Click the OK button.

    Freely Available .NET Libraries

    Ajax

    • Ajax Control Toolkit – Microsoft
    • AJAXNet Pro
    • ASP.NET MVC Project Awesome – a rich set of helpers (controls) that you can use to build highly responsive and interactive Ajax-enabled Web applications. These helpers include Autocomplete, AjaxDropdown, Lookup, Confirm Dialog, Popup Form and Pager. Thanks Omu (April 20, 2011)

    Build Tools

    • Prebuild – Generate project files for all VS version, including major IDE’s and tools like SharpDevelop, MonoDevelop, NAnt and Autotools
    • Genuilder – Precompiler which lets you transform your source code during the build. Thanks Harry McIntyre (April 13, 2011)

    Charting/Graphics

    Collections/Generics

    • PowerCollections – is a library that provides generic collection classes that are not available in the .NET framework. Some of the collections included are the Deque, MultiDictionary, Bag, OrderedBag, OrderedDictionary, Set, OrderedSet, and OrderedMultiDictionary. Thanks Adam Ralph (April 20, 2011)

    Compression

    Controls

    • Krypton – Free winform controls. Link fixed (April 14, 2011)
    • Source Grid – A Grid control
    • DevExpress – Over 60 Free Controls from DevExpress. Thanks Florian Standhartinger (April 20, 2011)
    • ObjectListView – is a C# wrapper around a .NET ListView. It makes the ListView much easier to use and provides some neat extra functionality. Thanks Florian Standhartinger (April 20, 2011)

    Data Mapper

    Dependency Injection/Inversion of Control

    Design by Contract

    IDE

    • SharpDevelop – is a free IDE for C#, VB.NET and Boo projects. Thanks Florian Standhartinger (April 20, 2011).

    Logging

    ORM

    PDF Creators/Generators

    Automated Web Testing

    Misc Testing/Qualitysupport/Behavoir Driven Development (BDD)

    URL Rewriting

    MS Word/Excel Documents Manipulation

    • DocX to create, read, manipulate formatted word documents. Easy syntax, working nicely, actively developed. No Microsoft Office necessary.
    • Excel XML Writer allows creation of .XLS (Excel) files. No Microsoft Office necessary. Been a while since it has been updated. It also provides code generator to create code from already created XLS file (saved as xml). Haven’t tested this but looks very promising. Too bad author is long time gone.
    • Excel Reader allows creation/reading of .XLS (Excel) files. No Microsoft Office necessary. Been a while since it has been updated.
    • Excel Package allows creation/reading of .XLSX (Excel 2007) files. No Microsoft Office necessary. Author is gone so it’s out of date.
    • EPPlus is based on Excel Package and allows creation/reading of .XLSX (Excel 2007). It is actually the most advanced even comparing to NPOI.
    • NPOI is the .NET version of POI Java project at http://poi.apache.org/. POI is an open source project which can help you read/write xls, doc, ppt files.
    • sharp2word – a Word 2003 XML Documents Generator from C# code without any components or libraries. Thanks dublicator (April 20, 2011)
    • ClosedXML – an actively developed library for generating OpenXML Excel files. Thanks Joseph Robichaud (April 26, 2011)

    Serialization

    • sharpserializer – xml/binary serializer for wpf, asp.net and silverlight
    • Protobuf.NET – fastest serialization port protobuf format into .NET platform. Thanks slava pocheptsov (April 26, 2011)

    Silverlight

    Social Media

    • LinqToTwitter – Linq-based wrapper for all Twitter API functionality in C#
    • Facebook C# SDK – A toolkit for creating facebook applications / integrating websites with Facebook using the new Graph API or the old rest API.

    Package managers for external libraries

    • NuGet (formerly known as NuPack) – Microsoft (developer-focused package management system for the .NET platform intent on simplifying the process of incorporating third party libraries into a .NET application during development)
    • OpenWrap – Sebastien Lambla – Open Source Dependency Manager for .net applications

    Unit Testing/Mocking

    Validation

    Threading

    • Smart Thread Pool – Thread Pool management library
    • Retlang – a high performance C# threading library. Thanks MarcBot (April 13, 2011)
    • bbv.Common – an open source library of software components that makes building multi-threaded, event-based and loosely coupled systems easy. Thanks Urs Enzler (April 14, 2011)
    • PowerThreading – a llibrary (DLL) containing many classes to help with threading and asynchronous programming. Thanks Adam Ralph (April 20, 2011)

    Unclassified

    • CSLA Framework – Business Objects Framework
    • AForge.net – AI, computer vision, genetic algorithms, machine learning
    • Prism – Composit UI application block for WPF, Silverlight and WP7 – Microsoft patterns & practices
    • Enterprise Library 5.0 – Logging, Exception Management, Caching, Cryptography, Data Access, Validation, Security, Policy Injection – Microsoft patterns & practices
    • File helpers library
    • C5 Collections – Collections for .NET
    • Quartz.NET – Enterprise Job Scheduler for .NET Platform
    • MiscUtil – Utilities by Jon Skeet
    • Noda Time – DateTime replacement (idomatic port of Joda Time from Java)
    • Lucene.net – Text indexing and searching
    • Json.NET – Linq over JSON
    • Flee – expression evaluator
    • PostSharp – AOP
    • IKVM – brings the extensive world of Java libraries to .NET.
    • C# Webserver – Embeddable webserver
    • Long Path – Microsoft
    • .NET Engines for the GOLD Parsing System
    • NCQRS – library for event-driven architectures (CQRS).
    • Reactive Extensions for .NET – a library for composing asynchronous and event-based programs using observable collections. Thanks steve (April 14, 2011)
    • Mono.GameMath – a project to develop a highly-performant math library for games, based on XNA APIs. Thanks Alex Rønne Petersen (April 14, 2011)
    • SLSharp – a runtime IL-to-GLSL translation engine, allowing people to write GLSL shaders as C# code. Thanks Alex Rønne Petersen (April 14, 2011)
    • InfusionSoftDotNet – a dll to ease the pain for .Net developers to access the InfusionSoft API. Thanks Michael Gibbs (April 20, 2011)
    • re-mix – provides mixins for C# and Visual Basic .NET. Thanks Stefan Papp(April 20, 2011)
    • Mono.Cecil – a library written by Jb Evain to generate and inspect programs and libraries in the ECMA CIL format. It has full support for generics, and support some debugging symbol format. Thanks Florian Standhartinger(April 20, 2011)
    • ImapX – is an modern .NET 2.0 library for management of IMAP folders, supports SSL Connection and different IMAP formats, such as Gmail IMAP, AOL IMAP (November 30, 2011)

    When and Where to use Generic?

    Problem: 

    You want to use generic types in a new project or convert nongeneric types in an existing project to their generic equivalent. However, you do not really know why you would want to do this, and you do not know which nongeneric types should be converted to be generic.
     

    Solution:

    You need to consider several things:
    1. Will you type contain or be operating on various on unspecified data types? If so, creating a generic tyep will offer several benefits over creating a nongeneric type. If your type will operate on only a single specific type, then you may not need to create a generic type.
    2. If your type will be operating on value types, so that boxing and unboxing operations will occur, you should consider using generics to prevent the boxing and unboxing operations.
    3. The stronger type checking associated with generic will aid in finding erros sooner, thus shortening your bug-fixing cycle.
    4. Is your conde suffering from "code bloat" with you writing multiple classess to handle diffrent data types on which they operate? It is easier to write the code once and have it just work for each of the data type it operates on.
    5. Generics allow for greater clarity of code. By eliminating code bloat and forcing stronger type checking on your types, your code will be easier to read and understantd.

    See Also: See the "Generics Overviews" and "Benefits of Generics" topics in the MSDN documentation.

     
     
     

    C#: Effective Class Design

    Effective Class Design
    1. Type Design
    1.1. Nested Types
    – When logical grouping and name-collision avoidance are your only goals, namespace should be used.
    – Nested types should be used, the notion of member accessibility semantics is a desirable part of you design.
     
    1.2. Class Design
    – Do favor using classes over interfaces; Unlike other type systems (e.g., COM) uses interfaces heavily, in the managed world, classes are the most commonly used constructs.
    – Best Practice: Always define at least one constructor (and make it private if you don’t want the class creatable).
     
    1.3. Base Class Design
    – Recommended to use base class:
      – Base class is more versionable; With a class, you can ship V1, and then in V2 decide to add another method.
        As long as the method is not abstract (as long as a default implementation is provided), any existing derived classes continue to function unchanged.
        Adding a method to an interface is like adding an abstract method to a base class, any class that implements the interface will break.
      – Interface is more appropriate in the following scenarios:
        – Several unrelated classes want to support the protocol.
        – These class already have a base class (no multiple implementation inheritance, but multiple interface inheritance).
        – Aggregation is not appropriate or practical.
      – For instance, make IByteStream an interface, so a class implement multiple stream types (multiple interface inheritance).
        Make ValueEditor as abstract class because dervied class from ValueEditor have no other purpose than to edit value (single implementation inheritance).
    – Recommended to provide customization through protected virtual methods:
      Customizers of a class often want to implement the fewest methods possible to provide a rich set of functionality to consumers.
      To meet this goal, provide a set of non-virtual or final public methods that call through a very small set of protected virtual "Core" methods.
    public Control{
       public void SetBounds(int x, int y, int width, int height) {
          …
          SetBoundsCore(…);
       }
       public void SetBounds(int x, int y, int width, int height, BoundsSpecified specified) {
          …
          SetBoundsCore(…);
       }
       protected virtual void SetBoundsCore(int x, int y, int width, int height, BoundsSpecified specified) {
          // Do the real work here.
       }
    }
    – Do define a protected constructor on all abstract classes; Many compilers will insert a protected constructor if you do not.
    – Avoid prefixing or postfixing "Base", or "Root" as a type is likely to show up in public APIs. Exceptional e.g. ButtonBase class.
    – Do prefer using base types in public signatures rather than concrete types to provide better opportunity of substitution and more flexibility in changing the implementation. e.g., public Stream GetDataStream() is prefered to public FileStream GetDataStream().
    Do not change inherited public members to private. This does not prevent callers from accessing the base class implemenation.
    public class ABaseType {
       public void BasePublicMethod() {
          Console.WriteLine("Called base implementation.");
       }
    }
    public void ADerivedType {
       private new void BasePublicMethod() {
          Console.WriteLine("Called derived implementation.");
       }
    }
     
    1.4. Designing for Subclassing
    – Do minimize the number and complexity of virtual methods in your APIs. Virtual members defeat some performance optimizations the CLR provides and could "box-in" your design.
    – Do think twice before you virtualize members:
      – As you version your component (like template methods), you must be sure that the virtual members are called in the same order and frequency.
      – GoF: A template method defines an algorithm in terms of abstract operations that subclasses override to provide concrete behavior.
      – As you version your virtual members, you must not widen or narrow the inputs and outputs to the members.
      – e.g., ArrayList.Item property calls several virtual methods per each MoveNext and Current. Fixing these performance problems could break template methods that are dependent upon virtual method call order and frequency.
    Do make only the most complex overload virtual to minimize the number of virtual calls needed to interact with your class and reduce the risk of introducing subtle bugs in subclasses.
    Consider sealing virtual members you override from your base class. There are potential bugs with virtual members you introduce in your class as well as virtual members you override.
    – Do fully document the contract for any virtual members. It is especially important to specify what guarantees are NOT given about the order in which virtuals are called relative to each other, relative to raising of events, and relative to changes in observable states.
     
    1.5. Interface Design
    – Recommended to provide a default implementation of an interface where it is appropriate. E.g., System.Collections.DictionaryBase
    class is the default implementation of System.Collections.IDictionary interface.
    – Use a marker interface to mark a class and verify the presence of the marker at compile time.
    public interface ITextSerializable { } // empty interface
    public void Serialize(ITextSerializable item) {
       // use reflection to serialize all public properties
       …
    }
    – Use a custom attribute to mark a class (as having a specific characteristic) and verify the presence of the marker at runtime.
    [immutable]
    public class Key {
       …
    }
    // methods can reject paramters that are not marked with a specific marker at runtime:
    public void Add(Key key object value) {
       if (!key.GetType().IsDefined(typeof(ImmutableAttribute))) {
          throw new ArgumentException("The paramter must be immutable", "key");
       }
    }
    – Consider implementing interface members privately (or explicitly), if the members are intended to be called only through the interface.
    – Consider implementing interface members privately (or explicitly) to simulate covariance (to change the type of parameters or return values in "overriden" members).
    // Covariance creates strong typed collections.
    public class StringCollection : IList {
       public String this[int index] { … }
       string IList.this[int index] { …}
    }
    – Do provide protected method that offers the same functionality as the privately implemented mehtod if the functionality is meant to be specialized by dervied classes. Otherwise, it is impossible for inheritors of the type to call the base method(???).
    public class List<T> : ISerializable {
       void ISerializable.GetObjectData(
          SerializationInfo info, StreamingContext context) {
          GetObjectData();
       }
    protected virtual void GetObjectData(
          SerializationInfo info, StreamingContext context) {
          GetObjectData();
       }
     
    1.6. Value Type Design
    – Do not define methods on structs that mutate the struct’s state.
    NOTE: The pattern for implementing IEnumerable which often involves using a mutable struct (MoveNext() method modifies an internal counter). Although technically this pattern violates this guideline, it is acceptable because the struct is soley for foreach statement, not for users.
     
    1.7. Enum Design
    – Do use an Enum to strongly type parameters, properties, and return values.
    pulbic enum TypeCode {
       Boolean,
       Byte,
       Char,
       DateTiem
       …
    }
    – Do use the System.FlagsAttribute custom attribute for an enum only if a bitwise OR operation is to be performed on the numeric values. Do use powers of two for the enum values so they can easily be combined.
    [Flags()]
    public enum WatcherChangeTypes {
       Created = 1,
       Deleted = 2,
       Changed = 4,
       Renamed = 8,
       All = Created | Deleted | Changed | Renamed
    }
    – Consider providing named constants for commonly used combinations of flags.
    [Flags()]
    public enum FileAccess {
       Read = 1,
       Write = 2,
       ReadWrite = Read | Write
    }
    – Do not use flag enum values that are zero or negative.
    [Flags]
    public enum SomeFlag
    {
       ValueA = 0, // bad design, don’t use 0 in flags
       ValueB = 1,
       ValueC = 2,
       ValueBAndC = ValueB | ValueC;
    }
    SomeFlag flags = GetFlags();
    if (flags & SomeFlag.ValueA) // this will never evaluate to true
    {
    }
    – Do argument validation; Do not assume enum arguments will be in the defined range. It is legal to cast any integer value into an enum even if the value is not defined in the enum.
    public void PickColor(Color color) {
       switch (color) {
          case Red: …
          case Blue: …
          case Green: …
          default:
             throw new ArgumentOutOfRangeException();
       }
       // do work
    }
    NOTE: Do not use Enum.IsDefined() for these checks as it is based on the runtime type of the enum, so thus deceptively expensive and changible out of sync with the code.
    public void PickColor(Color color) {
       if (!Enum.IsDefined(typeof(Color), color) { // this check is expensive and breakable by versioning
          throw new InvalidEnumArgumentException("color", (int)color, typeof(Color));
       }
       // Security issue: never pass a negative color value
       NativeMethods.SetImageColor(color, byte[] image);
    }
     
    2. Member Design
    2.1. Property Design
    – Do allow properties to be set in any order; The semantics are the same regardless of the order in which the developer sets the property values or how the developer gets the object into the active state; Properties should be stateless with respect to other properties.
    – Recommended: Components raise <Property>Changed events and there is a protected helper routine On<Property>Changed, which is used to raise the event. Data binding uses this pattern to allow two-way binding of the property.
    – Each property that raises <Property>Changed event should provide metadata to indicate that the property supports two-way binding.
    Recommended: Components raise <Property>Changing events when the value of a property change via external forces and allow developers to cancel the change by throwing an exception.
    class TextBox{
       public event TextChangedEventHandler TextChanged;
       public event TextChangingEventHandler TextChanging;
       public string Text {
          get { return text; }
          set {
             if (text != value) {
                OnTextChanging(Event.Empty);
                text = value;
                OnTextChanged(…);
             }
          }
       }
       protected virtual void OnTextChanged(…) { TextChanged(this, …); }
       protected virtual void OnTextChanging(…) { TextChanging(this, …); }
    }
    Avoid throwing exceptions from property getters; If a getter may throw an exception, it should be redesigned to be a method. TIP: One expects exceptions from indexers as a result of validating the index (index bound, type mismatch, etc).
     
    2.2. Properties vs. Methods
    – Prefer methods to properties in the following situations:
      – The operation is a conversion.
      – The operation is expensive, e.g. planning to provide an async version of this operation not to be blocked.
      – The operation is not local, e.g. having an observable side effect; different results in succession of calling.
      – The member is static but it returns a mutable value.
      – The member returns an array, IOW, avoid using array valued properties.
        – Instead return a readonly collection (ArrayList.ReadOnly() method to get a readonly IList wrapper).
        Type type = // get a type window
        for (int i = 0; i < type.Methods.Length; i++)
        {
           if (type.Methods[i].Name.Equals("foo"))
           {
              …
           }
        }
     
    * Common Design Considerations
      – Have fewer properties and "complex" methods with a large number of parameters to maintain "atomicy" of the actions—Less Customizable.
        public class PersonFinder {
           public string FindPersonsName (int height, int weight, string hairColor, string eyeColor, int sheoSize, int whichDatabase)
           {
              // perform operation using the parameters
              …
           }
        }
      – Have more properties to set "configuration" (a set of states individually set and hold) and "simple" methods with a small number of parameters.
        public class PersonFinder {
           public int Height { get {…} set {…} }
           public int Weight { get {…} set {…} }
           public string HairColor { get {…} set {…} }
           public string EyeColor { get {…} set {…} }
           public int ShoeSize { get {…} set {…} }
           public string FindPersonsName (int whichDatabase)
           {
              // use the perperties already set to perform operation
           }
        }
     
    2.3. Read-Only and Write-Only Properties
    – Do use read-only properties when a user cannot change the logical backing data field.
    – Do not use write-only properties; Implement the functionality as a method instead if the property getter cannot be provided.
     
    2.4. Indexed Property (Indexer) Design
    – Do use only Int32, Int64, String, and Object for the indexer; If the design requires others for the indexer, strongly re-evaluate if it really represents a logical backing store. If not, use a method.
    – Consider using only one index; If the design requires multiple indices reconsider if it really represents a logical backing store. If not, use a method.
    – Do use the name Item for indexers unless there is an obiviously better name (e.g. Chars property on String).
     
    2.5. Event Design
    – Do use the "raise" terminology for events rather than "fire" or "trigger" terminology. When referring to events in documentation, use the phrase "an event was raised" instead of "an event was fired" or "an event was triggered".
    – Do not create a special event handler when not using a strongly typed EventArgs subclass; Simply use the EventHandler class.
    – Do use a protected virtual On<Event> method to raise each event in order to provide a way for a derived class to handle the event using an override.
    – Do assume that anything can go wrong in an event handler and do not assume that anything about the object state after control returns to the point where the event was raised.
    public class Button {
       ClickedHandler onClickedHandler;
       protected void DoClick() {
          PaintDown(); // paint button in depressed state
          try {
             OnClicked(args); // call event handler
          }
          finally {
             // window may be deleted in event handler
             if (windowHandle != null) {
                PaintUp(); // paint button in normal state
             }
          }
       }
       protected virtual void OnClicked(ClickedEvent e) {
          if (onClickedHandler != null)
             onClickedHandler(this, e);
       }
    }
    – Do raise cancelable events to allow the caller to cancel events w/o generating an error:
       public class MainForm : Form {
          TreeView tree = new TreeView();
          void LabelEditing(Object source, NodeLabelEditEventArgs e) {
             e.Cancel = true;
          }
       }
    – Do raise an exception to cancel an operation and return an exception.
       public class MainForm : Form {
          TreeView tree = new TreeView();
          void TextChanging(Object source, EventArgs e) {
             throw new InvalidOperationException("Edit not allowed in this mode");
          }
       }
     
    2.6. Method Design
    – Avoid methods that cannot be called on an object instantiated with a simple constructor because the method requires further initialization of the object. If this is not unavoidable, throw an InvalidOperationException exception clearly stating in the message. e.g., throw new InvalidOperationException("Connection must be valid and open"); 
    – Do use default values correctly in a family of overloaded methods; The complex method should use parameter names that indicate changes from the default states assumed in the simple method.
    MethodInfo Type.GetMethod(String name); // case sensitive is assumed.
    MethodInfo Type.GetMethod(String name, Boolean ignoreCase); // a change from case sensitive to case insensitive.
    – Avoid method families with the simplest overload having more than 3 parameters; Do not have constructor families with the simplest overload having more than 5 parameters.
    – If extensibility is needed, do make only the most complete overload virtual and define the other overloads in terms of it.
     
    2.8. Variable Number of Arguments
    – Consider using Params if a simple overload could use Params but a complex overload could not and ask yourself "would users value the utility of having params on this overload even if it wouldn’t be on all overloads".
    – Do order parameters so that it’s possible to apply "params" to the methods:
      e.g., Find (String[], IComparer) would have been written as Find (IComparer, String[]).
    – Do not use Params when the array can be modified by the method since the array is temporary and any modifications will be lost.
    – Do provide special code paths for a small number of elements in order for performance sensitive code to special case the entire code path. The following pattern is recommended:
      void Format (string formatString, object arg1)
      void Format (string formatString, object arg1, object arg2)
      …
      void Format (string formatString, params object[] args)
    – CLS requirement: All types that overload operators include alternative methods with appropriate domain-specific names that provide equivalent functionality.
    public struct DateTime {
       public static TimeSpan operator- (DateTime t1, DateTime t2) { }
       public static TimeSpan Substract (DateTime t1, DateTIme t2) { }
    }
     
    2.10. Implementing Equals and Operator==
     
    2.11. Conversion Operators
    Do not throw exceptions from an implicit cast because it is very difficult for the users to understand what is happening.
    – Do case values that are in the same domain; Do not cast values from differnt domains:
      e.g., it’s appropriate to convert a Time or TimeSpan into an Int32 where the Int32 still represents the time or duration.
            It does not make sense to convert a file name string such as, "c:\mybitmap.gif", into a Bitmap object.
     
    2.12. Constructor Design
    – Do have only a default private constructor if there are only static methods and properties on a class.
    – Do make static constructors private (called a class constructor or a type initializer).
    – Do minimal work in constructors; Constructors should not do much work other than to capture the constructor parameters.
      The cost of the other work is delayed until the user uses a particular feature of the instance.
    Do not call a virtual method in a constructor if the virtual method is in the constructor’s type.
      When a constructor calls a virtual method, there is a chance that the constructor for the instance of the virtual method hasn’t executed.
      Annotation: In C++, the vtable is updated during the construction, so that a call to a virtual function during construction only calls to the level of the object hierarchy that has been constructed. For the CLR, the decision is ultimately based on the desire to support extremely fast object creation.
    Do throw exceptions from constructors if appropriate. When an exception propagates out of a constructor, the object is created but the operator new does not return the reference. The finalizer of the object will run when the object becomes eligible for collection.
    Do use a private constructor, if the type is not meant to be creatable.
    The best practice is to always explicitly specify the constructor even if it is a public default constructor.
    – Do provide a protected constructor that can be used in derived types.
    Recommended: You do not provide a default (parameterless) constructor for a struct (a value type).
      Note: Many compilers don’t allow structs to have default parameterless constructors for this reason.
      With no constructors, the CLR initializes all the fields of the struct to zero; This is for faster array and static field creation.
     
    * Constructor vs. Static Factory Methods
    – Do use static factory if:
      – If the parameters to a constructor do not completely describe the object being created, a method name is required to provide more context or more of the semantics of the member.
      – If you need to control the instantiation (e.g., in a singleton class), a static factory may return a cached instance to limit the expensive instance creation.
      – If you need to return a subclass of the return type, it is often handy to return a subclass to hide implementation details.
       public static ArrayList ReadOnly(ArrayList list) {
          if (list==null) throw new ArgumentNullException("list");
          return new ReadOnlyArryList(list);
       }
    – Do use constructor if:
      – If the member needs to be available for subclasses to specialize; Subclasses are not able to customize the behavior of static factory methods.
      – if none of the above applies, use constructors as they are more convient than static factories.
     
    2.13. Field Design
    – Do not use instance fields that are public or protected; Use a protected property to expose a field to a derived class.
    – Do not expose fields to be more versonable:
      – Able to change a field to a property while maintaining binary compatibility.
      – Able to allow demand-creation or change-notifcation of an object upon usage of the property.
    – Do use const (static literal) fields for constants that will NEVER change; compilers burn the values of const fields directly into calling code.
    – Do use public static readonly fields for predefined object instance:
    public struct Color{
       public static readonly Color red = new Color(0x0000FF);
       public static readonly Color green = new Color(0x00FF00);
       public static readonly Color blue = new Color(0xFF0000);
       …
    };
    – Do not use readonly fileds of mutable types (or arrays).
     
    2.14. Explicit Member Implementation
    – Explicit member implementation allows an interface member to be implemented such that it is only available when cast to the interface type.
    – Do use explicit members to hide implementation details from public view (or to approximate private interface implementations).
    – Do expose an alternative way to access any explicitly implemented members that subclasses are allowed to override.
    public class ViolatingBase : ITest
    {
       void ITest.SomeMethod() { … }
    }
    public class FixedBase : ITest
    {
       void ITest.SomeMethod() { SomeMethod(); }
       virtual protected void SomeMethod() { … }
    }
    public class Derived : FixedBased, ITest
    {
       override protected void SomeMethod()
       {
          // …
          base.SomeMethod();
          // This would cause recursion and a stack overflow.
          ((ITest)this).SomeMethod();
       }
    }
     
    3.1. Argument Checking
    – Perform argument validation for every public or protected method and property set accessor and throw meaningful exceptions to caller. The actual checking could happen at a lower level in some private routines.
    class Foo{
       public int Count{
          get{
             return count;
          }
          set{
             if (value < 0 || value >= MaxValue)
                throw new ArgumentOutOfRangeException(Sys.GetString("InvalidArgument", "value", value.ToString()));
             count = value;
          }
       }
       public void Select(int start, int end){
          if (start < 0)
             throw new ArgumentException(Sys.GetString("InvalidArgument", "start", start.ToString()));
          if (end < start)
             throw new ArgumentException(Sys.GetString("InvalidArgument", "end", end.ToString()));
        }
    }
     
    3.2. Parameter Passing
    – In general, favor using enums where it makes the source code more readable; In case where enums would add unneeded complexity and actually hurt readability of the source code, Boolean should be prefered.
    – Do use enums if there are two or more Boolean arguments:
    FileStream fs = File.Open("foo.txt", true, fale); // No context to understand the meanings of true and false.
    FileStream fs = File.Open("foo.txt", CasingOptions.CaseSensitive, FileMode.Open); // Much easier to work with.
    Annotation: Most of the time, numerics are passed around as constants and variables (not as "magic numbers"). 80% of the time, a Boolean argument is passed in as a constant to turn a piece of behavior on or off.
    Annotation: Developers inadvertently switches two Boolean arguments; It’s somewhat easier to make a mistake even with just one Boolean argument, does true mean "case insensitive" or "case sensitive"?
    Annotation: If there is even a slight possibility of needing more options in the future, use an enum now (not to be forced to add another Boolean option).
    – Avoid using enums if the method does not take more than one Boolean arguement and there are now and forever only two states.
    – If a value is typically set in the constructor, an enum is better; For constructor parameters that map onto properties, a Boolean is better.
    Annotation: Today, there is a very small overhead (on the order of 300 bytes for each enum type referenced) but this is at the noise range and should not be considered a factor in choosing to use a Boolean over an enum.

    C#: Design Guide: Disposable Pattern

    Design Guide: Disposable Pattern
    Both an explicit and an implicit way to free those resources should be provided. Implicit control should always be provided by implementing the protected method Finalize() on an Object (using the destructor syntax in C#). If implemented, the explicit control is provided by a Dispose() method from the IDisposable interface.
     
    public class Window : IDisposable
    {
       private IntPtr handle; // pointer to a external resource
       private Component Components; // other resource you use
       private bool disposed = false;
       public Window()
       {
          handle = //allocate on the unmanaged side
             otherRes = new OtherResource(…);
       }
       // Implements IDisposable
       public void Dispose()
       {
          Dispose(true);
          GC.SuppressFinalize(this);
       }
       protected virtual void Dispose(bool disposing)
       {
          if (!this.disposed)
          {
             //if this is a dispose call dispose on all state you
             //hold, and take yourself off the Finalization queue.
             if (disposing)
             {
                Components.Dispose();
             }
             ///free your own state (unmanaged objects)
             this.disposed = true;
             Component = null;
             Release(handle);
             handle = IntPtr.Zero;
          }
       }
       //Simply call Dispose(false)
       ~Window()
       {
          Dispose (false);
       }
       //Whenever you do something with this class, check to see if the  
       //state is disposed, if so, throw this exception.
       public void GetWindowHandle()
       {
          if (this.disposed)
          {
             throw ObjectDisposedException(…);
          }
          //…
       }
       //Derived class
       public class MyWindow: Window 
       {
          private bool disposed = false;
          public MyWindow()
          {
          }
          protected override void Dispose(bool disposing)
          {
             if (!this.disposed)
             {
                if (disposing)
                {
                   //free any disposable resources you own
                }
                //free your own state
                this.disposed = true;
                base.Dispose(disposing);
             }
          }
       }
    }
     
    – Do make the Finalize() method protected; Do not make it more visible like public.
    – Do call base.Finalize method in your finalizer. Note: this is done automatically with the C# and the MC++ destructor syntax.
    – Do suppress finalization of your instance once Dispose has been called, unless there is other work to do in Finalize (not covered by Dispose).
    – Do call base.Dispose method if it implements IDisposable.
    – Consider not being recreatable. Recreating an object that has already been disposed is often a difficult undertaking.
    – Do allow your Dispose method to be called more than once w/o throwing an exception. Do nothing after the first call.
    – Other instance methods should check whether resources have been disposed. If so, reacquire the resources or throw an ObjectDisposedException.

    C#: Design Guide: Collection vs. Array

    Design Guide: Collection vs. Array
    Collections
    "Collections": Types implementing IEnumerable, ICollection, or IList.
    "Dictionaries": Types implementing IDictionary.
    "collection" (lower case) refers to both Collections and Dictionaries.
    – Do not postfix your collection names with List, Hashtable or any other word implying particular implementation.
    – In rare cases, it’s OK to postfix some specialized collections w/ Queue, Stack, or Set (rather indicate specific semantics).
    – Do implement strongly typed collections for value types; Any method storing or retrieving items from a collection should take or return objects of a specific type, not the generic Object type.
    public ExceptionCollection: IList,  {
           object IList.this[int item] { … }
           public Exception this[int item] { … }
    }
     
    * IEnumerable and IEnumerator: MoveNext, Current, Reset
    – The Current property returns a Object type—a cast is needed because you can’t implicitly downcast from Object to the item type.
    Recommended: Use the is or the as operator to test that a type implements a given interface before attempting to use the type.
    Quick Way: Implement collections storing reference types by delegating to a collection of reference types; For value types, do not do this.
     
    * Protecting Data While Allowing Enumeration
    class ItemStorage {
       class Enumerator : IEnumerator;
       {
          public Enumerable(IEnumerable enumerable) { enumerator = enumerable.GetEnumerator(); }
          IEnumerator enumerator;
          public IEnumerator GetEnumerator() { return enumerator; }
       }
       ArrayList items = new ArrayList();
       public IEnumerable ItemCollection
       {
          get
          {
             return new Enumerator(items);
          }
       }
    }
    ItemStorage items = new ItemStorage();
    foreach (Object item in items.ItemCollection())
    {
       Console.WriteLine(((Item)item).Name);
    }
     
    * Implement Strongly Typed Enumerators for Value Types
    – First, change the way the item data is stored in the enumerator, e.g. moving from a reference-based collection to a value-based array.
    – Second, have your own versions of GetEnumerator method and Current property (besides IEnumerable.GetEnumerator and IEnumerator.Current).
      Have strongly typed GetEnumerator to return a nested public struct called "Enumerator" and strongly typed Current to return the item type.
    class ItemCollection {
       public struct Enumerator : IEnumerator;
       {
          public Enumerator(…) { … }
          public ValItem Current {
             get {
                return …;
             }
          }
          object IEnumerator.Current { get { return Current; } }
          ValItem items[4] = new ValItem[4];
       }
       public Enumerator GetEnumerator() { return new Enumerator(…); }
       IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); }
       ValItem items[4] = new ValItem[4];
    }

    ItemCollection items = new ItemCollection();
    ItemCollection.Enumerator e = (ItemCollection.Enumerator)items.GetEnumerator();
    while (e.MoveNext())
    {
       Console.WriteLine(e.Current.Name);
    }

     
    * Use mutator interface allows to modify collected value types w/o requiring any boxing.
    interface IValItem
    {
       string Name { get; set; }
    };
    struct ValItem : IValItem
    {
       public ValItem(string name) { this.name = name; }
       string name;
       public string name {
          get { return name; }
          set { name = value; }
       }
    }
     
    – Consider using keyed collections if the items stored in the collection have natural names; Keyed collections are collections that are indexed by a string-typed index and an integer-typed index.
    – Do consider taking IEnumerable<T> as a parameter and dynamically check if the object implements ICollection<T> to implement a more efficient code.
    public class List<T> : IList<T> {
       public List<T>(IEnumerable<T> collection){
          // check if it implements ICollection
          ICollection<T> col = collection as ICollection<T>;
     
          int numberOfNewItems=0;
          // optimized and slow code paths
          if(col!=null){
             numberOfNewItems = collection.Count;
          }
          else{
             IEnumerator<T> enumerator = collection.GetEnumerator();
             while(enumerator.MoveNext()) numberOfNewItems++;
          }
          this.Capacity = numberOfNewItems;
          foreach(T item in collection){
             Add(item);
          }
          this.TrimToSize();
       }
    }
     
    – Prefer implementing IEnumerable interface with optimistic concurrency for most usage scenarios and better performance.
    Rationale:  There are two legitimate ways to implement the IEnumerable interface. The first is to assume that the collection will not be modified while it is being enumerated.  If it is modified throw an InvalidOperationException exception.  The 2nd way is to make a snap-shot of the collection in the enumerator thus isolating the enumerator from changes in the underlying collection.
     
    Array vs. Collections.
    – Do prefer collections over arrays in common scenarios. Collections provide more control over the contents of the container, are more version-able, and more usable.
    TRADEOFF: For targeting lower level developers it is often better to use arrays for read-write scenarios. Arrays have a smaller memory footprint which helps reduce working set and access to elements in an array can be inlined by the JIT. However usability studies have shown that there are problems in the conceptual overhead of understanding the techniques to declare arrays in VB. Collections provide them a simple and consistent model. Array usage for read only scenarios is discouraged even in low level APIs as the cost of cloning the array is prohibitive.
    – Do use a readonly collection or clone an array to prevent internal data from being changed by calling code.
    – Recommended: Use collections to avoid the inefficiencies in cloning the array-valued properties:
    for (int i = 0; i < obj.myObj.Count; i++) {
       DoSomething(obj.myObj[i]);
    }
     
    – Do not use a readonly fields of an array or any other mutable type.
    – Consider using jagged arrays instead of multi-dimensional arrays; The CLR optimizes the access path of jagged arrays.
    – General Rule: Do return an empty array or String.Empty() instead of a null reference since users assume this.

    View in Web Browser

    /_layouts/images/ichtmxls.gif

    /sites/hmlee/eicar/_layouts/xlviewer.aspx?listguid={ListId}&itemid={ItemId}&DefaultItemOpen=1

    0x0

    0x1

    FileType

    xlsx

    255

    View in Web Browser

    /_layouts/images/ichtmxls.gif

    /sites/hmlee/eicar/_layouts/xlviewer.aspx?listguid={ListId}&itemid={ItemId}&DefaultItemOpen=1

    0x0

    0x1

    FileType

    xlsb

    255

    Snapshot in Excel

    /_layouts/images/ewr134.gif

    /sites/hmlee/eicar/_layouts/xlviewer.aspx?listguid={ListId}&itemid={ItemId}&Snapshot=1

    0x0

    0x1

    FileType

    xlsx

    256

    Snapshot in Excel

    /_layouts/images/ewr134.gif

    /sites/hmlee/eicar/_layouts/xlviewer.aspx?listguid={ListId}&itemid={ItemId}&Snapshot=1

    0x0

    0x1

    FileType

    xlsb

    256

    C#: Callback Patterns and Choice

    Callback Patterns and Choice
    Use Event if the following are true:
    – One signs up for the callback up front (typically through Add and Remove methods).
    – More than one object will typically be cared.
    – One is designing a high-level API, esp. a designable Component.
     
    Use Delegate if the following are tru:
    – You want a C style function pointer.
    – Single callback.
    – Registered in a call or at a construction time (not through separate Add method).
     
    Use Interface if the following is true.
    – The callback entails complex behavior.
     
    – Do favor using events over methods that take delegates. Events are a more familiar idea to developers, and therefore are simpler to use. Methods taking delegates should only be used when the target user fully understands the concept of delegates, and the situation is not event-related.
    Situations such as notification of an object’s state change should be implemented by events only.
     
    Tradeoff: Events are definitely not appropriate as a general purpose customization mechanism. They have much higher performance overhead and as not as flexible as, for example, inheritance based customization.

    C#: Asynchronous Pattern

    Asynchronous Pattern

    The underlining philosophy is as follows:
    – It is the client that decides if a particular call should be asynchronous.
    – It is not necessary for a server to do additional programming; The CLI should be able to manage the difference between the client and server views.
    – The server can choose to explicitly support asynchronous behavior either because it can implement it more efficiently than a general architecture, or it wants to support only asynchronous behavior.
    – It is supposed to enforce type safety.
    – The CLI will provide a list of necessary services to support the asynchronous programming model:
      – Synchronization primitives, such as critical sections and ReaderWriterLock.
      – Synchronization constructs, such as containers that supports WaitForMultipleObjects method.
      – Exposure to the underlying infrastructure pieces, such as Message objects and Thread pools.

    – The object that implements IAsyncResult must be a waitable object and its underlying synchronization primitive should be signaled after the call is canceled or completed. The waitable objects support waiting to become signaled with "any" or "all" semantics.
    – The Cancel method is a request to cancel processing of the method after the desired timeout period has expired and the server is recommended to honor it. The client is recommended to not destory the resources such as file objects as the server may be actively using them. It’s safe for the client to destory the resources after the IsCompleted or IsCancelled property returns true.
    – The semantics of the one-way qualifier: The callback itself may execute asynchronously through the context dispatcher infrastructure.
    – Calling EndInvoke before the asynchronous operation is complete will block the caller. Calling it a second time with the same AsyncResult is undefined.

    class FactorizeCallback {
       public FactorizeCallback(unsigned long number) {
          _ulNumber = number;
       }
       // Note the qualifier one-way. See last paragraph of this section for its explanation.
       public one-way boolean FactorizedResults(IAsyncResult ar) {
          unsigned long factor1, factor2;
          FactorizingDelegate fd = ar.AsyncObject;
          fd.EndInvoke(factor1, factor2, ar);

          // Output the results.
          Console.Writeline("Factors of" + _ulNumber + ":" + factor1 + " " + factor2);
        }
       private unsigned long _ulNumber
    }

    // Client code.
    delegate FactorizingDelegate(unsigned long factorizableNum,
           ref unsigned long primefactor1,
           ref unsigned long primefactor2);
    PrimeFactorizer pf = new PrimeFactorizer();
    FactorizingDelegate fd = new FactorizingDelegate(pf.Factorize);

    // ———————————————————————————————-
    // Async Variation 1.
    unsigned long factorizableNum = 1000589023, temp;

    // Define the asynccallback delegate.
    FactorizeCallback fc = new FactorizeCallback(factorizableNum);
    AsyncCallback cb = new AsyncCallback(fc.FactorizedResults);

    // Asynchronously invoke the Factorize method on pf.
    // Note: If we have pure out parameters, we do not need temp
    fd.BeginInvoke(factorizableNum, temp, temp, cb);

    // Proceed to do other work.
    ……

    // ———————————————————————————————-
    // Async Variation 2.
    // Asynchronously invoke the Factorize method on pf.
    // Note: If we have pure out parameters, we do not need temp
    unsigned long factorizableNum = 1000589023, temp, factor1, factor2;
    IAsyncResult ar = fd.BeginInvoke(factorizableNum, temp, temp, NULL);

    // Do other work.
    ……

    // Wait for the callback.
    SynchronizationServices.WaitForSingleObject(ar);

    // Output the results.
    fd.EndInvoke(factor1, factor2, ar);
    Console.Writeline("Factors of" + factorizableNum + ":" + factor1 + " " + factor2);

    Summary
    – Supply or DO NOT supply the callback delegate when beginning an asynchronous operation.
    – Poll the returned IAsyncResult waitable object for completion.
    – End the operation prematurely thereby being blocked until the operation completes.
    – Wait on the IAsyncResult waitable object using a timeout to wake up periodically.
    – End the operation in the callback routine.

    C#: Static Class Pattern

    Static Class Pattern
    public sealed class Environment {
       private Environment() {}
       public static void Exit() {int exitCode) {…}
       public static int ExitCode() {
          get { … }
          set { … }
       }
       public static String CommandLine() {
          get { … }
       }
    }
     
    NOTICE:
    – It is sealed.
    – It has a private default constructor.
    – It has no instance members.