A Twisted Look at Object Oriented Programming in C

download A Twisted Look at Object Oriented Programming in C

of 57

Transcript of A Twisted Look at Object Oriented Programming in C

  • 7/31/2019 A Twisted Look at Object Oriented Programming in C

    1/57

    A Twisted Look at Object Oriented Programming in C# - Introduction

    AuthorJeff Louie

    Introduction

    I must admit that my first exposure to object oriented programming (OOP) was frustrating and

    difficult. As a hobbyist I have struggled through Z80 assembly and EPROM burners, BASIC,Turbo Pascal, Java, C++ COM and now C#. The move to event driven programming and then toobject oriented programming presented major conceptual hurdles to my function drivensequential programming mindset. The aha moment when OOP made sense was mostgratifying, but did not come quickly or easily. It has been a few years since I got the OOPmindset and I feel comfortable enough now to try to help fellow travelers with this journey. IfOOP comes easily to you, feel free to skip this tutorial. If you are having problems getting yourmind around objects and inheritance I hope this tutorial can help you. This tutorial does notrepresent a conventional teaching method. It assumes a passing knowledge of the C# languageand familiarity with the Visual Studio .NET IDE. This is a work in progress and may require

    correction or revisions.

    Classes, Objects, and Properties

    Why program with objects and inheritance?

    Simply put, programming with objects simplifies the task of creating and maintaining complexapplications. OOP is a completely different way of thinking that differs significantly from themore traditional function driven sequential programming model of old. Programming withobjects without inheritance is object-based programming. Adding inheritance to objects isobject-oriented programming. OOP provides built in support for code reuse (inheritance) andsupport for runtime variations in program behavior (polymorphism). Without attempting todefine these terms, OOP at a minimum:

    1. Simplifies the creation and maintenance of complex applications.2. Promotes code reuse.3. Allows flexibility in runtime program behavior (a very cool feature).

    What is OOP?

    Well, lets cut right to the point. What the heck is Object Oriented Programming? Answer: It is awhole new way of thinking about programming! It is a way of modeling software that maps yourcode to the real world. Instead of creating programs with global data and modular functions,you create programs with classes. A class is a software construct that maps to real worldthings and ideas. Think of a class as a blueprint that contains information to construct asoftware object in memory. Unlike a simple data structure, software objects contain code forboth data and methods. The class binds the data and methods together into a single namespaceso that the data and methods are intertwined.

    Just as you can build more than one house from a single blueprint, you can construct multiplesoftware objects from a single class. Each object (represented by code in memory) is generatedfrom a class and is considered an instance of the class. Since each instance of the class existin separate memory space, each instance of the class can have its own data values (state). Justas multiple houses built from a single blueprint can differ in properties (e.g. color) and haveidentity (a street address), multiple objects built from a single class can differ in data values andhave a unique identifier (a C++ pointer or a reference handle in C#). Got that! Now take andbreak and re-read this paragraph. When you come back, you can look at some C# code.

    What is a class?

    http://www.developerfusion.co.uk/profile/18319http://www.developerfusion.co.uk/profile/18319
  • 7/31/2019 A Twisted Look at Object Oriented Programming in C

    2/57

    A class is a software construct, a blueprint that can describe both values and behavior. Itcontains the information needed to create working code in memory. When you create an object,you use the information in the class to generate working code. Lets create a simple programthat models a toaster! The toaster is a real life object. The toaster can have state such assecondsToToast and has a behavior, MakeToast(). Here is our first toaster class in C#:

    class Toaster1{

    /// /// The main entry point for the application./// [STAThread]static void Main(string[] args){

    //// TODO: Add code to start application here//Toaster1 t= new Toaster1();System.Console.WriteLine(t.MakeToast());System.Console.ReadLine();

    }private int secondsToToast= 10;public string MakeToast(){

    return "Toasted for "+secondsToToast.ToString()+" seconds.";}

    }

    If you execute this program, the output is:

    Toasted for 10 seconds.

    A working toaster yes, but not very useful unless you like 10-second toast .

    What is an object?

    An object is an instance of a class. A specific class describes how to create a specific object inmemory. So the class must contain information about the values and behaviors that each objectwill implement. You can create an object using the reserved word new. In our Toaster1application, you create a single instance of the Toaster1 class with the call:

    Toaster1 t= new Toaster1();

    The reference variable t, now contains a reference to a unique instance of the Toaster1 class.You use this reference variable to touch the object. In fact, if you set the reference variable tto null, so that the object is no longer touchable, the garbage collector will eventually deletethe Toaster1 object!

    t= null;// If "t" contains the only reference to the Toaster1 object, theobject can be garbage collected. (Strictly speaking, if the Toaster1object cannot be "reached", it can be garbage collected.)

    MakeToast() is a public method of the Toaster1 object so it can be called from outside the class(Main) using the reference variable t to touch the objects behavior:

  • 7/31/2019 A Twisted Look at Object Oriented Programming in C

    3/57

    t.MakeToast();

    Since each object exists in a separate memory space, each object can have state, behavior andidentity. Our Toaster1 object has identity since it is unique from any other object created fromthe Toaster1 class:

    Toaster1 t2= new Toaster1();

    Now there are two instances of the Toaster1 class. There are two reference variables t andt2. Each reference variable identifies a unique object that exists in a separate memoryaddress. Since each object contains a method MakeToast(), each object has behavior. Finally,each object contains a value secondsToToast(). In a sense, each object now has its ownstate. However, the state is the same for each object! This is not a very useful class design. Infact, the Toaster1 class is not a good representation of a real world toaster since the toast timeis immutable.

    Here is a second run at the Toaster class that demonstrates the use of public accessors, getand set methods. This is a standard idiom in OOP. The actual data is declared private (orprotected) so that users of the class cannot access the underlying data. Instead, public methodsare exposed to the callers of the class to set and get the underlying hidden data values.

    Note: The modifiers private, protected and public are access modifiers that control thevisibility of methods and data. The compiler will enforce these visibility rules and complain if yousay try to touch a private variable from outside the class. Public methods and data are visibleto any caller. Private methods and data are only visible and touchable within the class.Protected is a special level of access control of great interest to object oriented programmers,but is a subject that must be deferred to the chapter on inheritance. If you dont declare anaccess modifier, the method or variable is considered private by default.

    using System;namespace JAL{

    ///

    /// Summary description for class./// ///class Toaster2{

    /// /// The main entry point for the application./// [STAThread]static void Main(string[] args){

    Toaster2 t= new Toaster2();t.SetSecondsToToast(12);

    Console.WriteLine(t.MakeToast());Console.ReadLine();}

    private int secondsToToast= 0;public string MakeToast(){

    return "Toasted for "+GetSecondsToToast().ToString()+"seconds.";

    }// Public Accessor Functions, Get and Set

  • 7/31/2019 A Twisted Look at Object Oriented Programming in C

    4/57

    public bool SetSecondsToToast(int seconds){

    if (seconds > 0){

    secondsToToast= seconds;return true;

    }else{

    secondsToToast= 0;return false;

    }}public int GetSecondsToToast(){

    return secondsToToast;}}

    }

    The callers of the class cannot touch the secondsToToast variable which remains private orhidden from the caller. This idiom is often called encapsulation so that the class encapsulatesor hides the underlying data representation. This is an important aspect of OOP that allows thewriter of the class to change the underlying data representation from say several variables oftype int to an array of ints without affecting the caller. The class is a black box that hides theunderlying data representation. In this new version of toaster, Toaster2, there are two newmethods: SetSecondsToToast() and GetSecondsToToast(). If you look at the setter method itvalidates the callers input and sets the value to zero if the callers input is invalid ( 0){

    secondsToToast= seconds;}else{

    secondsToToast= 0;}

    }

    The getter method really does not do much simply returning the private data valuesecondsToToast:

    public int GetSecondsToToast(){

    return secondsToToast;}

    What is a property?

    C#.NET implements a language idiom called a property. In a nutshell, a property is a method

    that appears as a variable. By convention, a property name starts with an uppercase letter.Here is our new version of Toaster that replaces the get and set methods with properties:

  • 7/31/2019 A Twisted Look at Object Oriented Programming in C

    5/57

  • 7/31/2019 A Twisted Look at Object Oriented Programming in C

    6/57

    }}

    The reserved word value is used to represent the callers input. Note the syntax used to call aproperty. To set a property use:

    t.SecondsToToast= 12;

    The method set() now appears as a variable SecondsToToast. So a property is a method thatappears as a variable.

    Well, congratulations. You have constructed your first real world class in C#. Since this is ahands on tutorial, I strongly urge you to compile the Toaster3 code and experiment.

    Where is My Inheritance?

    In this chapter you will learn how the fictional character Phaedrus explains the complex subjectof a class hierarchy in "Zen and the Art of Motorcycle Maintenance", Robert M. Pirsig, Quill,1974, 418 pp. You will also learn the art of "black box programming" with abstract classes and

    abstract methods.

    Lets Get Abstract

    One of the major advantages of OOP is that is simplifies the task of creating and maintaining

    complex applications. The road to this simple life is through "abstraction". Abstraction is theability to "decompose" a complex problem or structure into simpler problems or pieces. Inabstraction, you try to find the "essence" of a thing or idea. You break down a complex probleminto smaller, more manageable chunks. Abstraction is what the character Phaedrus describes inChapter 8 in "Zen and the Art of Motorcycle Maintenance."

    "John looks at the motorcycle and he sees steel in various shapes and has negative feelingsabout theses steel shapes and turns off the whole thing. I look at the shapes of the steel now

    and I see ideas. He thinks I am working on parts. I'm working on concepts."

    Phaedrus then proceeds to divide up the concept of a motorcycle into components and functions.Then he divides the components into a power assembly and a running assembly. To which heconcludes:

    "Finally you see that while I was splitting the cycle up into finer and finer pieces, I was alsobuilding a structure. This structure of concepts is formally called a hierarchy and since ancienttimes has been a basic structure for all Western knowledge.... That's all the motorcycle is, asystem of concepts worked out in steel."

    Thus the fine art of motorcycle maintenance is based on abstraction, decomposing the complexconcept of the motorcycle into a hierarchy of smaller simpler concepts. The fine art of OOP is

    also based on abstraction. You decompose the complex application domain into a hierarchy ofsmaller pieces that make the application easier to create and maintain. Now I am not sayingthat Phaedrus was a great object oriented programmer, but he clearly understood theimportance of critically examining the problem at hand and dividing up the problem into ahierarchy of ideas.

    Let's look at Phaedrus' motorcycle in C#. First, a motorcycle is a vehicle since it can carry apayload. Second, it is motorized since it has a motor and consumes fuel. The "essence" of amotorcycle is that of a "vehicle" that is "motorized". Of course a motorcycle differs from a a car,an airplane, or a boat. Motorized vehicles can be ridden, driven, flown or piloted. Land vehicles

  • 7/31/2019 A Twisted Look at Object Oriented Programming in C

    7/57

    can have two wheels or four wheels. What we have here is a hierarchy of ideas. We go from amost general concept to a more specific or "specialized" concept. Just as Phaedrus' abstractionof the motorcycle made him a better mechanic, your abstraction of a complex application,makes you a better and more efficient programmer. You do not think of a program as concreteparts (global data and methods). You think of a program as a hierarchy of ideas. Welcome to"Zen and the Art of Application Maintenance."

    Inheritance Is the Means to Abstraction

    Let's face it. Just creating a hierarchy of ideas is not enough. The language must provide amechanism to support the abstraction hierarchy. That mechanism is called inheritance.Inheritance allows programmers to modify or extend (or inherit) the properties and behavior(methods) of a class. It promotes "code reuse", the holy grail of programming. Throughoutthe .NET framework, you see the use of abstraction and class hierarchies.

    Inheritance in the .NET Framework

    All classes in the .NET framework derive from a single base class called Object. The Object classis the "root of the type hierarchy." Even the built in value types are aliases to classes that derivefrom Object, so that int actually maps to System.Int32, which derives from Object. As a result,

    you can call the Object class methods Equals, Finalize, GetHashCode and ToString on any classin the .NET framework. This makes it very easy to debug an application using console output

    since any .NET class will implement the ToString() method.

    An example of inheritance in the ASP.NET framework is a TextBox. Here is the class hierarchyfor System.Web.UI.WebControls.TextBox:

    System.ObjectSystem.Web.UI.ControlSystem.Web.UI.WebControls.WebControlSystem.Web.UI.WebControls.TextBox

    The TextBox control inherits from WebControl which inherits from Control which inherits fromObject. Wow. And I thought my family tree was complicated.

    Getting Your Inheritance

    In the following section you, a twisted programmer, build a "SpaceToaster" class in C# thatinherits from the Toaster class.

    Disclaimer: This is a very twisted tutorial. Reading this online book may be hazardous to yourmental health.

    You have been contracted by a famous "Boy Genius" movie cartoon character to extend thecommon household toaster for use as a orbiting satellite transmitter. SpaceToaster is aspecialization of a Toaster that extends the behavior of the lowly toaster into a satellite.

    Note: For those of you who don't know what cartoon movie I am talking about, either you haveno children or you need to get out more. Here's a hint: "Jimmy Neutron Boy Genius", ParamountMovies, Nickelodeon Movies, 2001.

    First you need to delete the Main method of the Toaster3 class since an executable can onlyhave one entry point. You can now create a new class "SpaceToaster" that inherits all of thecode in the Toaster3 class and has a Main method:

  • 7/31/2019 A Twisted Look at Object Oriented Programming in C

    8/57

    class SpaceToaster : Toaster3{

    [STAThread]static void Main(string[] args){}

    }

    This is not a very useful class! The syntax for inheritance is

    class ChildClass : ParentClass {}

    Note: Toaster3 is theparentclass and SpaceToaster is the childclass. You could also say thethe child class is a "subclass" or "derived class" and that the parent class is the "superclass" or"base class." The child inherits the knowledge (methods and variables) of the parent class, butcan only "touch" the public (and protected) methods and variables of the parent. Sort ofreminds me of a trust account. The child's ability to "touch" the assets of the trust is limited.

    Next, you can add a new behavior to the derived class extending the functionality of the lowly

    Toaster:

    class SpaceToaster : Toaster3{

    [STAThread]static void Main(string[] args){

    SpaceToaster st= new SpaceToaster();Console.WriteLine(st.Broadcast());Console.ReadLine();

    }public string Broadcast() //

  • 7/31/2019 A Twisted Look at Object Oriented Programming in C

    9/57

    }}

    Inheritance vs. Containment

    One difficult design decision is to decide if a class should inherit from a parent class or hold a

    reference to a new object. Inheritance represents an IS_A relationship from a generalization to aspecialization. Containment represents a HAS_A relationship between the whole and a part. So acar IS_A motorized vehicle, but HAS_A radio. The two relationships can be expressed in codethusly:

    class Radio{

    ...}class Vehicle{

    ...}class Car : Vehicle{

    Radio r= new Radio();}

    The essence of a car is that it is a vehicle. A radio is not essential to a car. Instead a radio ispart of a car. That said; let me acknowledge that none of my teenage children agree with me.They are adamant that a radio with a CD player _is_ essential to a car. So a teenage designlooks more like:

    class TeenageVehicle : Radio{

    ...}

    Public, Protected and Private

    Heck. I forgot that I had promised in Chapter 1 to explain the access modifier "protected". In anutshell, a private method or variable is only touchable within the class that declared thevariable. A public method or variable is touchable from outside the class. A protected method orvariable lies between public and private. Protected methods or variables are only touchable(visible) from within the declaring class _or_ from a class that inherits from the declaring class.So declaring a variable protected allows a designer to access your base class variable inside oftheir derived class. Suffice it to say that there has been a lot of discussion about the use ofprivate versus protected in class design.

    Make It Abstract

    Is your head spinning yet? If so, I apologize, but I need to introduce one more subject that isrelated to abstraction, the "abstract class". An abstract class defines zero or more abstractmethods. An abstract method defines the signature of the method, but not the body of themethod. You cannot create an instance of an abstract class.

    Note: Similar in concept to an abstract class is the concept of an "interface". However, aninterface contains no implementation, only abstract methods, and is similar to a pure virtualclass in C++.

  • 7/31/2019 A Twisted Look at Object Oriented Programming in C

    10/57

    Nothing helps explain a new programming idiom like sample code. Here is an abstract C# class"SpaceToaster" that defines an empty abstract method "BroadcastID()":

    abstract class SpaceToaster : Toaster3{

    public string Broadcast()

    { return "Hello From Earth!";}abstract public string BroadcastID(); //

  • 7/31/2019 A Twisted Look at Object Oriented Programming in C

    11/57

    long as the updated class derives from the same abstract class and as long as the client makescalls through the abstract class, there is no need to recompile the client application. Cool!

    Allow Runtime Variation in Implementation

    This concept is difficult to grasp at first, but is an extremely powerful idiom. In this idiom, one or

    more concrete classes inherit from an abstract class, but each child class may provide a differentimplementation of the the abstract class method or methods. The client does not know whatconcrete class is going to be requested at runtime, but simply invokes the public view of themethod. The actual runtime behavior will depend on which concrete classes is requested atruntime. Thus the method can have more than one form at runtime, which is referred to aspolymorphism, to have more than one form.

    The classic example is an abstract class Drawable with an abstract method DrawYourself().Different concrete classes of Drawable items (such as circle or square) implement theDrawYourself() method in a unique manner and inherit from Drawable. You can now create aHashtable of non-null Drawable objects and iterate over the collection callingsomeObjectInHashtable.DrawYourself(). Each concrete object in the collection is guaranteed toimplement the DrawYourself() method.

    Note: Polymorphism implies late binding of a method name to a concrete implementation. Insome languages, this magic is done with a v_table, which stores an offset pointer to the actual

    concrete implementation. OK. That was probably more than you wanted to know.

    Mark Thyself

    Finally, the abstract class can simply be a marker, allowing you to identify all classes that arebased on your empty abstract class like this:

    abstract class MyMarker {} //

  • 7/31/2019 A Twisted Look at Object Oriented Programming in C

    12/57

    }abstract public string BroadcastID(); //

  • 7/31/2019 A Twisted Look at Object Oriented Programming in C

    13/57

    The Model -- View/Controller architecture is a modification of the Model -- View -- Controllerarchitecture used in the SmallTalk language. In the SmallTalk language, the application isdivided into three parts. The Model encapsulates the application logic or algorithms. The Viewdraws the presentation. The Controller responds to user or system events. The key concept isthe separation of the application logic from the presentation and event handling code. The Modelclass is independent of the GUI and is ignorant of any implementation of the GUI. A good Model

    class should be able to function as part of a console application and support unit testing. In this

    chapter, you will build an application that separates the complex mathematics of a mortgagecalculator (Model) from the presentation and event handling code (View/Controller). The codebehind technique of Web Form programming further contributes to the separation of the View(HTML code) and Controller (code behind event handler) code.

    There is no question that the complete separation of GUI code from the application logic is adifficult concept for many to grasp. It can be a painful learning experience as it forces aprogrammer to change the basic approach to application design. Many will fight the process,dragged into the new world of OOP kicking and screaming. But, when you see how much simplera Model -- View/Controller application is to maintain or migrate, you will _see_ the light. Ipromise.

    The Model Class

    The following code was adapted from our book "Visual Cafe for Java Explorer, DatabaseDevelopment Edition" Brogden, Louie, Tittel, Coriolis, 1998. The only real change from the Javaversion is the use of C#'s support for "properties." The Model class implements the algorithms ofa mortgage calculator. The fact that the Java code was completely separate from the Java GUIgreatly simplified the reuse of this 1997 code in this C# Windows Form application!

    In a nutshell, given three of four mortgage parameters (principal, interest, period in months,payment), you can calculate the unknown parameter. Solving for interest is not a trivialmathematical solution. I readily admit that I had help solving that equation from my goodfriend, Dr. W. Carlini! The Model class has an "Init" method that takes all four parametersneeded for a mortgage calculator. One and only one parameter must have a value of zero. Thezero parameter acts as a marker for the unknown value.

    This class also demonstrates the use of two common programming idioms: the use of a public"IsValid" function to return the internal state of the object and the use of pre and postconditions to validate the input and output of an algorithm.

    Using IsValid()

    Note that all of the actual calculations occur on a call to the "Init" method, either directly orindirectly through the "args" constructor. If the input parameters and result appear valid, the"target" variable is set to a valid value. If the input parameters or result appear invalid, the

    "target" variable is set to -1. A public function "IsValid" is provided to the caller that returns theinternal state of the object. The public function "IsValid" encapsulates or hides the internalvalidation logic. I would argue that the use of a public "IsValid" function is a common and usefulprogramming idiom.

    Pre and Post Conditions

    The downside of separating out the algorithm from the GUI, is that both the Model class and theView/Controller class does input checking to insure runtime reliability and useful user feedback.The Model class implements a common programming construct, the use of pre and postconditions. In the Model class, the "Init" method statically validates the input parameters beforepassing them on to the DoAlgorithm method (pre-conditions). The algorithm does not check fora divide by zero error, which is handled internally. After the calculation is complete, the

  • 7/31/2019 A Twisted Look at Object Oriented Programming in C

    14/57

    "DoAlgorithm" method validates the result by calling Double.IsNaN (IsNotANumber) (post-conditions). The decision to turn off pre and post conditions in the release build (no checkversion) is beyond the scope of this tutorial.

    The compulsive coder will note the the input validation scheme is not mathematically correct,rejecting interest rates of greater than 100%. Apparently the twisted class has a social agenda.

    Complete Code Listing Model.cs

    The downside of posting all of the code is that it goes on forever. Click here to skip the code.You can come back later.

    /// /// Class Model.cs/// jlouie 07.07.02/// Adapted from Model.java/// "Visual Cafe for Java Explorer, Database Development Edition"/// William Brogden, Jeffrey A. Louie, and Ed Tittel, Coriolis, 1998,585pp.

    /// Supplied "as is"/// No warranty is expressed or implied/// This code is for instructional use only/// public class Model{

    // internal class constants, not "versionable"private const int INVALID= -1; // flags errorprivate const int PRINCIPAL= 0;private const int INTEREST= 1;private const int MONTHS= 2;private const int PAYMENT= 3;private double[] arrayDb= new double[4];private int target= INVALID;

    private string message= "";/* // uncomment to run console self test// self test static method outputs state to consolestatic void ConsoleDebug(Model model){

    if (model == null){

    System.Console.WriteLine("Null object.");return;

    }System.Console.WriteLine("Message: "+model.Message);System.Console.WriteLine("Result: "+model.Result);System.Console.WriteLine("Principal: "+model.Principal);

    System.Console.WriteLine("Interest: "+model.Interest);System.Console.WriteLine("Months: "+model.Months);System.Console.WriteLine("Payment: "+model.Payment);

    }*//* // uncomment to run console self test// self test[STAThread]static void Main(){

  • 7/31/2019 A Twisted Look at Object Oriented Programming in C

    15/57

    // test internal consistency of algorithmsModel model= new Model(100000,8.5,360,0);Model.ConsoleDebug(model); // payment = 768.9134584334model.Init(0,8.5,360,768.9134584334);Model.ConsoleDebug(model);model.Init(100000,0,360,768.9134584334);Model.ConsoleDebug(model);model.Init(100000,8.5,0,768.9134584334);Model.ConsoleDebug(model);System.Console.ReadLine();

    }*/

    // no arg constructorpublic Model(){;}// arg constructorpublic Model(double principal, double interest, int months, double

    payment){

    Init(principal, interest, months, payment);}

    // factored code, can be called after call to constructor// allowing reuse of instance of class// eg. object is _not_ immutable by designpublic void Init(double principal, double interest, int months,

    double payment){

    // reset flagstarget= INVALID;message= "";// store input into array of doublearrayDb[PRINCIPAL]= principal;arrayDb[INTEREST]= interest;arrayDb[MONTHS]= (double)months;arrayDb[PAYMENT]= payment;// validate input// one, and only one, "value" must be zero --> targetint zeros= 0;int tempTarget= INVALID;for (int i=0; i1)

    {message= "Too many zero parameters.";return;

    }if (zeros == 0){

    message= "One parameter must be zero.";return;

    }// validate interest

  • 7/31/2019 A Twisted Look at Object Oriented Programming in C

    16/57

    if (interest > 100 || interest < 0){

    message= "Invalid interest.";return;

    }// validate monthsif (months < 0){

    message= "Invalid months.";return;

    }// validate principalif (principal < 0){

    message= "Invalid principal.";return;

    }// validate paymentif (payment < 0){

    message= "Invalid payment.";return;

    }// input parameters appear validtarget= tempTarget;DoAlgorithm(target);

    }// the actual amortization algorithm// m= P*i(1-(1+i)^-N)// i=r/1200// result= 0 --> marks errorprivate void DoAlgorithm(int target){

    double result= 0;double P= arrayDb[PRINCIPAL]; // principaldouble i= arrayDb[INTEREST]/1200; // monthly percentage ratedouble N= arrayDb[MONTHS]; // loan period in monthsdouble m= arrayDb[PAYMENT]; // monthly payment

    if (target>= 0 && target< 4) // validate target{

    try{

    switch (target){

    case PRINCIPAL: // principalresult= 1+i;

    result= 1/Math.Pow(result, N);result= ((1-result)/i)*m;break;

    case INTEREST: // annual interest// algorithm fails if N*m >= P !!if ((N*m)

  • 7/31/2019 A Twisted Look at Object Oriented Programming in C

    17/57

    result= CalcInterest(P,N,m);break;

    case MONTHS: // loan periodresult= (1-(P*i/m));result= Math.Log(result);result= -result/Math.Log((1+i));break;

    case PAYMENT: // monthly paymentsresult= 1+i;result= 1/Math.Pow(result,N);result= (P*i)/(1-result);break;//default://break;

    }}catch{

    result= 0;}

    }// validate resultif (Double.IsNaN(result)){

    result= 0;}if (result == 0){

    message= "Input Error.";}else // valid result{

    arrayDb[target]= result;}

    }

    // a complex iterative calculation for interest// thanks to Dr. W. Carlini (and Newton)for the solution// returns zero on error// ASSERT (N*m)>=Pprivate double CalcInterest(double P, double N, double m){

    double temp= (m/P), answer= (m/P), diff= 100, numerator= 0,denominator= 0,accuracy= .00001;

    int index, maxIterations= 1000;try

    {for (index= 0; ((diff>accuracy) && (index

  • 7/31/2019 A Twisted Look at Object Oriented Programming in C

    18/57

    if (diff

  • 7/31/2019 A Twisted Look at Object Oriented Programming in C

    19/57

    {return arrayDb[PRINCIPAL];

    }else{

    return 0.0;}

    }}public double Interest{

    get{

    if (IsValid()){

    return arrayDb[INTEREST];}else{

    return 0.0;

    }}

    }public double Months{

    get{

    if (IsValid()){

    return arrayDb[MONTHS];}else{

    return 0;}

    }}public double Payment{

    get{

    if (IsValid()){

    return arrayDb[PAYMENT];}else{

    return 0.0;}

    }}

    }

    Creating a Windows Form Application

  • 7/31/2019 A Twisted Look at Object Oriented Programming in C

    20/57

    I fired up the Visual Studio IDE, dragged a few controls around and wired up two eventhandlers. This is what I got:

    You could certainly spiff up this application by adding radio buttons that let the user select thetarget of the calculation. You could then disable the appropriate input control, setting the valueof the target control to zero. Interestingly, the Parse method happily accepts embeddedcommas.

    In the application you simply create an instance of the Model class:

    private Model model= new Model();

    You then call the appropriate Model methods and properties in the buttonCalculate andbuttonReset event handlers:

    private void buttonCalculate_Click(object sender, System.EventArgs e){

    double principal= 0;double interest= 0;int months= 0;double payment= 0;

    bool isInputError= false;// validate user input, must allow zerotry{

    principal= Double.Parse(textBoxPrincipal.Text);if (principal

  • 7/31/2019 A Twisted Look at Object Oriented Programming in C

    21/57

    catch{

    textBoxPrincipal.Text= "Invalid Input.";isInputError= true;

    }try{

    interest= Double.Parse(textBoxInterest.Text);if ((interest < 0) || (interest > 100)){

    throw new Exception();}

    }catch{

    textBoxInterest.Text= "Invalid Input.";isInputError= true;

    }try{

    months= Int32.Parse(textBoxPeriod.Text);if (months

  • 7/31/2019 A Twisted Look at Object Oriented Programming in C

    22/57

    {textBoxMessage.Text= model.Message.ToString();ResetControls();

    }}private void buttonReset_Click(object sender, System.EventArgs e){

    textBoxMessage.Text= "";ResetControls();

    }private void ResetControls(){

    textBoxPrincipal.Text= "";textBoxInterest.Text= "";textBoxPeriod.Text= "";textBoxPayment.Text= "0";textBoxPrincipal.Focus();

    }

    Creating a Web Form Application

    Just to prove how easy it is to reuse the Model class, I then fired up the IDE and built a browserbased version of the mortgage calculator. Just think. If your client suddenly wakes up one dayand ask for a browser based version of your application, you won't be having a panic attack. Byseparating out the application logic from the GUI (view and event handling code), you areprepared for code reuse.

    Here is a snapshot of the browser based calculator:

  • 7/31/2019 A Twisted Look at Object Oriented Programming in C

    23/57

    Now it's your turn to do some coding. Just create a new Windows Form or Web Form application

    and copy and paste the Model class into your project. You will need to remove any embeddedcarriage returns that were added to the actual code for easy HTML viewing. If you want todownload the working projects, they are available athttp://www.geocities.com/jeff_louie/download.html

    Hopefully, I have convinced you of the need to separate out your application logic from thepresentation and event handling code. I have reused the Model code from a Java application inboth a Windows Form and Web Form application. Use this most basic design pattern, the Model-- View/Controller architecture. It will grow on you!

    Static Methods, Factories & Constructors

    Well, I've tried as long as possible to avoid the the "nuts and bolts" of object oriented

    programming. It's sort of like going in to the dentist for a root canal. You know it needs to bedone, but it is going to be painful and you want to put it off. The good news is that once youhave the root canal the pain goes away! So just dive in. In this chapter you will learn aboutstatic methods, factory methods and constructors. You will be introduced to the creationalpatterns "Class Factory" and "Singleton".

    What Is a Static Field or Method?

    http://www.geocities.com/jeff_louie/download.htmlhttp://www.geocities.com/jeff_louie/download.html
  • 7/31/2019 A Twisted Look at Object Oriented Programming in C

    24/57

    Let's change the question. When is a field or method not part of an object? Answer: when it ispart of the class! Remember, an object is an instance of a class and each object exists in aseparate space in memory. It is possible to access class fields and class methods withoutcreating an instance of a class using the "static" key word. Declaring a field or method with thestatic key word, tells the compiler that the field or method is associated with the class itself, notwith instances of the class. In a sense, static or "class" fields and methods are global variables

    and methods that you can touch using the class name. If you think of a class as a blueprint used

    to create objects, then you can think of static fields and methods are being part of the blueprintitself. There is only one copy of the static fields and methods in memory, shared by all instancesof the class.

    Static fields are useful when you want to store state related to all instances of a class. A counteris a good example of a static field. The classic use of a static counter is to generate a unique IDor serial number for each instance of a class.

    Static methods are useful when you have behavior that is global to the class and not specific toan instance of a class. In contrast, instance methods are useful when the method needs to knowabout the state of an object. Since data and behavior are intertwined in an object, instancemethods have access to the instance fields and can exhibit behavior that is specific to the stateof an object.

    A Static Counter

    Here is the classic example of a static counter that is zero based. It contains a static field"uniqueID" and a thread safe static method "GetUniqueID" that increments the unique ID:

    /// /// Summary description for TestStatic./// class TestStatic{

    // static stuffprivate static int uniqueID= 0;

    private static int GetUniqueID(){

    lock(typeof(TestStatic)){

    return uniqueID++; // returns zero at start}

    }// member stuffprivate int identity;public TestStatic(){

    this.identity= TestStatic.GetUniqueID();}public int Identity{

    get{

    return identity;}

    }}public class Test{

  • 7/31/2019 A Twisted Look at Object Oriented Programming in C

    25/57

    /// /// The main entry point for the application./// [STAThread]static void Main(string[] args){

    //// TODO: Add code to start application here//TestStatic ts1= new TestStatic();TestStatic ts2= new TestStatic();Console.WriteLine(ts1.Identity.ToString());Console.WriteLine(ts2.Identity.ToString());Console.ReadLine();

    }}

    If you compile and run this code the output is: 0 and 1. The static field "uniqueID" is global tothe application and stores the value of the next unique ID. Each call to the constructor returnsthe unique ID and then increments the counter using the "postfix" operator ++. Notice how you

    use the class name to touch a static field or method:

    ClassName.fieldName;ClassName.MethodName();

    Note: In Java you can touch a static field or method using the class name or a referencevariable to an instance of a class. Not so in C#.

    Managing Concurrency Conflicts

    The curious coder will note the call to "lock" which causes callers of the static method"GetUniqueID" to queue up to this method. (Lock is basically a shortcut to "Monitor.Enter" and"Monitor.Exit".) Locking inside the method insures that the method is thread safe. The problem

    is that the increment operator (++) is not an atomic operation, but performs a read and then awrite. If you don't force callers to queue up to the increment operation it is possible for twocallers to "almost simultaneously" enter the method. Both callers could read the uniqueID valuebefore either caller can write the incremented value. In this case, both callers will receive thesame ID. Not very unique! Be careful. If your locking code is poorly written, it is possible for twocallers to queue up in a "catch-22" conflict where neither call can proceed, an example of"deadlock." The topic of locking, deadlock, and concurrency is an advanced topic not covered bythis tutorial.

    Let's Get Constructed

    When you create an instance of an object using the key word "new", you call a class constructor.In fact, if you don't explicitly declare a class constructors, the compiler creates a hidden no

    argument constructor for you. Here is an example of explicitly declaring a no-arg do nothingconstructor:

    class Toaster{

    public Toaster() {} // this is a do nothing constructor}

  • 7/31/2019 A Twisted Look at Object Oriented Programming in C

    26/57

    The compiler will create this constructor, if and only if, you do not declare any constructors forthe class. The syntax for a public constructor is:

    public NameOfClass(parameterList){

    ... stuff here

    }

    Let's Get Initialized

    Constructors are often used to initialize the state of an object. Alternatively, you can initializethe instance fields when they are declared. Finally, you can break out the initialization code intoa separate "Init" method. The following code demonstrates all three idioms for initializing anobject:

    /// /// Summary description for Idioms./// class Idioms

    { private Hashtable idiom1= new Hashtable();private Hashtable idiom2;private Hashtable idiom3;/// /// The main entry point for the application./// [STAThread]static void Main(string[] args){

    //// TODO: Add code to start application here//Idioms c= new Idioms();}

    public Idioms(){

    Init();idiom2= new Hashtable();

    }private void Init(){

    idiom3= new Hashtable();}

    }

    Assigning an instance variable a value when you declare the variable is an example of defensiveprogramming. It minimizes the chance of forgetting to initialize a variable in the constructor or

    Init method.

    Creating Multiple Constructors

    A common programming task is to create multiple constructors that differ only in theirparameter list. The C# language supports this concept by allowing you to "overload" a methodname. As long as the parameter list is sufficiently unique, you can create multiple methods orconstructors with the same name.

  • 7/31/2019 A Twisted Look at Object Oriented Programming in C

    27/57

    Note: Be careful not to confuse overloading with overriding. Overriding a virtual method is quitedifferent than overloading a method or constructor. Overriding is a subject of a future tutorial. Ipromise.

    It's time to resurrect the Toaster class. Here is a new version of the Toaster class with two newinstance fields that contain information about the color of the toaster and the model name of thetoaster:

    class Toaster{

    public const string DEFAULT_NAME= "Generic";public enum ColorType {Black, Red, Yellow, White};private static ColorType DEFAULT_COLOR= ColorType.Black;

    private ColorType color= DEFAULT_COLOR;private string modelName= DEFAULT_NAME;

    }

    Note the use of an enum "ColorType" to limit the domain of valid toaster colors. Here again is

    the default no-args constructor:

    public Toaster(){} // black toaster with default name

    The no-arg constructor simply leaves the default field values unaltered. You can now create aconstructor that takes two parameters, the color type and the model name. Note that theconstructor does validity checking to insure that the state of the object remains valid.

    public Toaster(ColorType color, string modelName){

    this.color= color;if (modelName != null){

    this.modelName= modelName;}

    }

    You can now create a constructor that only takes one parameter, the model name:

    public Toaster(string modelName){

    if (modelName != null){

    this.modelName= modelName}

    }

    Now this looks like redundant code, just begging to be refactored. Happily, C# allows you tochain constructor calls, eliminating the redundant null checking code. You can chain the twoconstructors like this:

    public Toaster(string modelName) : this(DEFAULT_COLOR, modelName) {}

    The syntax is:

  • 7/31/2019 A Twisted Look at Object Oriented Programming in C

    28/57

    public ClassName(someParameters) : this(someParameters) {}

    Pretty cool! By using C#'s built in support for constructor overloading and constructor chainingyou can write a series of constructors. Here is the final version of the Toaster class usingmultiple overloaded constructors:

    class Toaster{public const string DEFAULT_NAME= "Generic";public enum ColorType {Black, Red, Yellow, White};private static ColorType DEFAULT_COLOR= ColorType.Black;private ColorType color= DEFAULT_COLOR;private string modelName= DEFAULT_NAME;public Toaster(){} // black toaster with default namepublic Toaster(ColorType color, string modelName){

    this.color= color;if (modelName != null){

    this.modelName= modelName;

    }}public Toaster(ColorType color) : this(color,DEFAULT_NAME){}public Toaster(string modelName) : this(DEFAULT_COLOR,modelName) {}public string Color{

    get{

    return Enum.Format(typeof(ColorType), color,"G");}

    }public string ModelName{

    get{

    return modelName; // danger, return ModelName --> stackoverflow!

    }}

    }

    What Is a Destructor?

    C++ programmers are familiar with the concept of a destructor. I only briefly mention this topichere in self defense. In C++, a destructor is a method that is called when an object goes out ofscope, is deleted, or the application closes. In C++, a destructor is often used to release

    valuable system resources. This works in C++ since memory reuse in C++ is deterministic.When an object in C++ goes out of scope, the destructor is called and resources can be releasedimmediately.

    Things are quite different in C#. First, memory reuse in C# is based on garbage collection. In anutshell, when application memory becomes limited, the garbage collector executes andattempts to reclaim memory by reclaiming objects that are not "reachable". As a result, in C#,you cannot depend on a destructor to reclaim system resources in a timely manner.

  • 7/31/2019 A Twisted Look at Object Oriented Programming in C

    29/57

    Second, although C# supports the syntax of destructors, destructors in C# simply map tofinalize. According to the IDE documentation:

    ~ MyClass(){

    // Cleanup statements.

    }

    ... is converted by the compiler to:

    protected override void Finalize(){

    try{

    // Cleanup statements.}finally{

    base.Finalize();}

    }

    If your object uses valuable external resources, you may want your class to inherit from theIDisposable interface and implement the Dispose method, calling GC.SuppressFinalize.Alternatively, you want to rely on C#'s support for try, catch, finally to release externalresources. For instance, you might want to open a connection in try and close any open

    connections in finally.

    The concept of garbage collection and reclaiming external resources is definitely beyond thescope of this tutorial.

    Using Static Factory Methods Instead of Multiple Constructors

    You might wonder why I have chosen to combine the topics of static methods and constructorsinto a single chapter. The answer is "static factory methods." Instead of writing multiple publicconstructors, you can write multiple static factory methods and private constructors that returnobjects. First, here is an example of a static factory method. The method simply constructs anobject with default values and then returns a reference to the object.

    public static Toaster GetInstance(){

    return new Toaster(ColorType.Black, DEFAULT_NAME);}

    In a sense, this static method is analogous to the no-arg constructor.

    public Toaster() {}

    Here is the version of the Toaster class that uses static methods and a single private constructor

    to return toaster objects:

    /// /// Summary description for Toaster///

  • 7/31/2019 A Twisted Look at Object Oriented Programming in C

    30/57

    class Toaster{

    // static factory methodspublic static Toaster GetInstance(){

    return new Toaster(ColorType.Black, DEFAULT_NAME);}public static Toaster GetInstance(string modelName){

    return new Toaster(ColorType.Black, modelName);}public static Toaster GetInstance(ColorType color){

    return new Toaster(color, DEFAULT_NAME);}public static Toaster GetInstance(ColorType color, string modelName){

    return new Toaster(color, modelName);}public const string DEFAULT_NAME= "Generic";

    public enum ColorType {Black, Red, Yellow, White}; // black is theenum default value!

    private static ColorType DEFAULT_COLOR= ColorType.Black;private ColorType color= DEFAULT_COLOR;private string modelName= DEFAULT_NAME;// the single private constructorprivate Toaster(ColorType color, string modelName){

    this.color= color; // ColorType cannot be null --> compile timeerror or defaults to ColorType.Black!

    if (modelName != null){

    this.modelName= modelName;}

    }// the getterspublic string Color{

    get{

    return Enum.Format(typeof(ColorType), color,"G");}

    }public string ModelName{

    get{

    return modelName; // danger, return ModelName --> stackoverflow!

    }}

    }

    Declaring the only constructor private, prevents any outside caller from directly instantiating theclass. The only path to a Toaster object is through a static factory method. So, you can usemultiple overloaded public constructors or multiple static factory methods and privateconstructors to create toaster objects. If you are interested in learning more about using static

  • 7/31/2019 A Twisted Look at Object Oriented Programming in C

    31/57

    factory methods instead of multiple constructers check out Effective Java ProgrammingLanguage Guide by Joshua Bloch, Addison-Wessley, 2001, 252 pp.

    Note: The behavior of enum is quite complicated. You cannot set an enum to null and if you failto explicitly initialize an enum variable, it defaults to the first member of the enumeration. Forexample:

    public static ColorType c; // c --> ColorType.Black

    Creational Patterns -- Class Factory and Singleton

    I am going to finish off this chapter by introducing two common design patterns: the "Class

    Factory" and "Singleton" patterns. The class factory is useful when you want to return concreteobjects that share a base class, at runtime. The singleton pattern is useful when you only wantto allow the creation of one instance of an object in a application. These patterns are bothconsidered "Creational" patterns since they abstract the creation of objects.

    Using a Static Method to Return Concrete Classes -- The Class Factory.

    The concept of using static methods to return objects is a useful one. In the previous code, youlearned how to replace multiple constructors with multiple static factory methods. Another usefuldesign pattern is the "Class Factory." A class factory can be used to return concreteimplementations of a common base type.

    In Chapter 2, you learned about polymorphism using the Drawable abstract class. Concreteimplementations of the Drawable class such as square or circle provide a concreteimplementation of the abstract "DrawYourself" method. Let's resurrect our Drawable class.

    abstract class Drawable{

    public abstract String DrawYourself();}

    class Circle : Drawable{public override String DrawYourself(){

    return "Circle";}

    }class Square : Drawable{

    public override String DrawYourself(){

    return "Square";}

    }

    In this example of the class factory pattern, you pass a parameter to a static factory methodthat then returns the appropriate concrete implementation of the Drawable abstract class. Toinsure that the method is passed valid parameters at compile time, you can define a type safeenum "DrawableType":

    public enum DrawableType {CIRCLE,SQUARE};

    Here is our class factory:

  • 7/31/2019 A Twisted Look at Object Oriented Programming in C

    32/57

    /// /// Summary description for class Factory./// class Factory{

    public enum DrawableType {CIRCLE,SQUARE};public static Drawable GetInstance(DrawableEnum e){

    if (e == DrawableType.CIRCLE){

    return new Circle();}else if (e == DrawableType.SQUARE){

    return new Square();}else{

    throw new IndexOutOfRangeException(); // should never gethere

    }}/// /// The main entry point for the application./// [STAThread]static void Main(string[] args){

    //// TODO: Add code to start application here//Drawable d1= Factory.GetInstance(Factory.DrawableType.CIRCLE);Console.WriteLine(d1.DrawYourself());Drawable d2= Factory.GetInstance(Factory.DrawableType.SQUARE);Console.WriteLine(d2.DrawYourself());Console.ReadLine();

    }}

    Note that d1 and d1 are reference variables of the Type Drawable, yet the code outputs: Circle,Square. Polymorphism at work! The class factory design pattern allows your application tocreate concrete implementations of a base class or interface dynamically at runtime in responseto user or system input.

    The Singleton Pattern

    The "Singleton" pattern is a special version of the class factory that only returns a singleinstance of a class. The singleton pattern is useful when there should only be one instance of anobject. As an example, there may be many soldiers that derive from person, but there shouldonly be one reigning King of England that derives from person! Here is a sample that uses astatic factory method to insure that only one instance is created. The factory method"GetInstance" returns a reference to the single instance of the class. Note that you must declareany constructors private, so that the constructors are not visible outside of the class. Thisinsures that. there will be one and only one instance of MyClass.

    /// /// Summary description for MyClass.

  • 7/31/2019 A Twisted Look at Object Oriented Programming in C

    33/57

    /// class MyClass{

    private static MyClass theOnlyOne= new MyClass(); // create one andonly one instance of the class

    public static MyClass GetInstance(){

    return theOnlyOne;}public readonly string description= "The One and Only.";private MyClass(){}/// /// The main entry point for the application./// [STAThread]static void Main(string[] args){

    //// TODO: Add code to start application here//

    MyClass mc= MyClass.GetInstance();Console.WriteLine(mc.description);Console.ReadLine();

    }}

    One of the advantages of the factory method is that you can modify the singleton behavior ofthe class without affecting the caller of the class. If you decide that your application should nowsupport Kings present and past, then you can modify MyClass to return a new instance for eachcall to GetInstance. Here is the modified multi-instance version of MyClass:

    /// /// Summary description for MyClass

    /// class MyClass{

    public static MyClass GetInstance(){

    return new MyClass();}public readonly string description= "OneOfMany";/// /// The main entry point for the application./// [STAThread]static void Main(string[] args){

    //// TODO: Add code to start application here//MyClass mc= MyClass.GetInstance();Console.WriteLine(mc.description);Console.ReadLine();

    }}

  • 7/31/2019 A Twisted Look at Object Oriented Programming in C

    34/57

    That's enough pain! I suggest the you jog around the block, clear your head and re-read thischapter later. In the next chapter, you will learn the top ten "gumption traps" for C++ and Javaprogrammers.

    C++ and Java Gumption Traps

    It's time for another break from theory and on to some real world programming challenges. Inthis chapter, you take a detour into the world of gumption traps. A gumption trap is a situationthat is so frustrating that it sucks the "gumption" or energy out of you. Surprisingly, a lot ofgumption traps come from preconceived notions of what "should" be correct. C++ and Javaprogrammers are prone to gumption traps due to their assumptions about the C# language. Inother words, C++ and Java programmers have a bit of "language baggage" that needs to be leftbehind. So, if you have a language neurosis, this chapter is for you.

    Top Ten C++ Gumption Traps

    In no particular order.

    1) Arrays in C# are Objects

    In C#, arrays are objects derived from System.Array. The following code snippet creates anarray object that can contain ten elements of MyClass:

    MyClass[] arrayMC= new MyClass[10];

    What may surprise you, is that this call does not create any instances of MyClass! In fact, if youiterate over the array, you will find that the array contains ten null elements. To fill the array,you must explicitly create ten instances of MyClass and fill the array:

    MyClass[] arrayMC= new MyClass[10];[STAThread]static void Main(string[] args)

    {//// TODO: Add code to start application here//Class1 c1= new Class1();for (int i=0; i

  • 7/31/2019 A Twisted Look at Object Oriented Programming in C

    35/57

    The following code snippet, creates a variable and initializes the variable to null, so that thereference does not refer to any object. If you try to use the reference variable to touch a field ormethod of the class, the code will throw a null reference exception.

    MyClass c= null;

    So, if you want to declare and initialize a reference variable and create an object in C# you mustuse the new keyword like this:

    MyClass c= new MyClass();

    "c" is now a reference variable of Type MyClass. If this is a local variable, then "c" uses memoryon the stack which contains the address of an object of Class MyClass on the heap.

    As discussed earlier, the string class (strings are immutable and shared) is an exception to therule. You can create a string like this:

    string s= "Hello";

    3) C# Uses Automatic Garbage Collection, Destructors are not Deterministic

    The call to new may bother a C++ programmer who may now feel obligated to call deleteappropriately. All I can say is lighten up! Objects are (mostly) reclaimed automatically in C#. Ina nutshell, when available memory falls, the garbage collector is called, freeing up any objectsthat are unreachable. If you are done with an object, you can assist the garbage collector byreleasing all references to the object. Even if two objects contain references to each other(circular references), the objects can still be collected if they become "unreachable."

    Since objects in C# are garbage collected, it is not a good idea to reclaim resources in thedestructor. A destructor will not be called until the object is reclaimed by the garbage collector.In other words, destructors are not deterministic in C#. Critical external resources are bestreleased by inheriting from IDisposable and implementing the Dispose method, or by using C#'s

    try, catch, finally construct to insure that any allocated resources are reclaimed in the finallyclause. Here is a twisted example of try, catch, finally in C#:

    try{

    OpenToiletLid();Flush();

    }catch(OverflowException e){

    CallPlumber();}finally

    { CloseToiletLid();}

    4) The Assignment Operator Does Not Call the Copy Constructor

    This one really confuses a lot of coders. In C# the assignment operator simply assigns areference variable to an existing object, to a new object, or to null. After the assignment, thereference variable contains a reference to an object or to no object (is null). The assignmentoperator does not call the copy constructor to create a new object. It is quite legal in C# to have

  • 7/31/2019 A Twisted Look at Object Oriented Programming in C

    36/57

    two reference variables that contain references to the same object. The two variables occupydifferent memory locations on the stack, but contain values that point to the same memoryaddress on the heap. Both references would have to be released (e.g. the reference variables goout of scope, be reassigned, set to null) before the object can be reclaimed. As a result, the"destructor" will only be called once. The following code simply creates two references to thesame object:

    MyClass c1= new MyClass();MyClass c2;c2= c1;bool isSameReference= (c1 == c2); // c1 and c2 contain references tothe same object on the heapConsole.WriteLine(isSameReference.ToString()); // output--> true

    Be clear that if variable c1 contains the only reference to an object, setting c1 to null orreassigning c1 to another object will make the original object unreachable and eligible forgarbage collection.

    5) Values and References to Objects are Passed By Value

    By default, objects in C# are not passed by reference. (Unlike Java, C# does support passing byreference using the ref keyword.) In C#, you pass a reference or a value to a method. Youcannot pass an object to a method. By default, all calls to methods are by value. Now is thatclear! In other words, you pass a reference to an object to a method, not the object itself. Thereference is passed by value so that the a copy of the reference goes on the stack. The key hereis that the object is not copied onto the stack and you can touch the object while inside themethod. If you want to truly pass an object by reference (for a swap routine) use the refkeyword. Remember, you cannot pass an object, so you are actually passing a reference byreference. Oh, I have a headache.

    6) Const is Hard Coded Into the Caller and not Version-able

    I find this one a bit weird. A const field value is hard coded into the caller for optimization so

    that the value is not updated until you recompile the caller. If you want to version-able readonly field declare it readonly. Finally, you can provide a get only Property like this:

    public string ModelName{

    get{

    return modelName; // danger, return ModelName --> stackoverflow!

    }}

    7) Supports Single Inheritance of Implementation and Multiple Inheritance of

    Interfaces

    C# does not support multiple inheritance of implementation. It does support multiple inheritanceof interfaces (pure virtual classes) and single inheritance of implementation.

    8) Program to Return Single Values

    Although C# does support an out parameter, in general, C# programs are designed to returnsingle values. Consider redesigning your application or returning immutable objects.

  • 7/31/2019 A Twisted Look at Object Oriented Programming in C

    37/57

    9) Strings are Immutable

    The string class is a very special class. First strings are immutable. Every time you concatenatea string, you may be creating a new string object. If you want a mutable class, useStringBuilder. Second, you can create a string object using the assignment operator. Third,

    strings are shared so that two strings that you create may occupy the same space in memory.Fourth, the equality operator is overloaded for string and checks for content equivalence, not"reference based equality."

    Note: The overloaded string equality operator only works on reference variables of Type string.Be careful! Thanks to Jon S. for this insight.

    object a= "Hello";object b= "Hello";bool isSameReference= (a == b); // test if a and b contain referencesto the same object or to no object (are both null)bool isSameContent= ((string)a == (string)b); // test if stringreferenced by a and string referenced b have the same content/value ora and b are both null

    Session["KEY"]="VALUE"; // Error! The left hand operand is of typeobject! This is a reference based comparison. Do this:(String)Session["KEY"]="VALUE"; // content equivalence

    10) bool is a Value Type

    C# has a built in type for Boolean which can have a value true or false. The default value of boolis false. Enough said.

    Top Ten Java Gumption Traps

    In no particular order.

    1) No Checked Exceptions

    The compiler in C# will not enforce catching of any checked exceptions. So there is no supportfor declaring a checked exception (no throws keyword).

    2) All Methods are Not Virtual By Default. All Members are Private by Default.

    In Java, all methods are virtual by default and can be overridden. Not so in C#. You mustexplicitly declare a method virtual if you want it to allow it to be overridden. You also cannotimplicitly override or hide a virtual method, but must explicitly use the override or new keyword.In Java, members have package level access by default. In C# all members are private bydefault.

    3) Const, ReadOnly and Get Only

    I find this one a bit weird. A const field value is hard coded into the caller for optimization sothat the value is not updated until you recompile the caller. If you want to version-able readonly field declare it readonly. Finally, you can provide a get only Property like this:

    public string ModelName{

  • 7/31/2019 A Twisted Look at Object Oriented Programming in C

    38/57

    get{

    return modelName; // danger, return ModelName --> stackoverflow!

    }}

    4) All Types in the NET Framework Derive from Object

    C# has a unified type system so that all reference and value types derive from Object. Forinstance, int is an alias for System.Int32. As a result, you can call ToString() on any value orreference type. This simplifies debugging in the Console mode.

    5) The Visual Studio IDE Startup Object is Empty By Default

    If the startup object string is empty and you declare more than one "Main" method in a VisualStudio project, the project will not compile. This is very frustrating. Trying to set the startupobject property in the Visual Studio IDE is non-trivial. Let me save you some pain. To set thestartup object, select View --> Solution Explorer. In the Solution Explorer window select thename of the project. Now select View --> Property Pages. (Do not select the Property Window!)Alternatively, right click on the project name and select Properties. Now select the CommonProperties folder in the left window. You can now select the appropriate startup object from thedrop down list. Don't forget to click on "Apply."

    6) Method Names Start with Upper Case

    This one is pretty self explanatory.

    7) Getters and Setters are Implemented Using Properties, Which are Upper Case

    C# formally supports the concept of getters and setters with Properties. Note that properties areupper case by convention. Here are the setter and getter methods as properties:

    // Propertiespublic int SecondsToToast{

    get {return secondsToToast;} // danger, return SecondsToToast -->stack overflow!

    set{

    if (value > 0){

    secondsToToast= value;}else{

    secondsToToast= 0;}

    }}

    The reserved word value is used to represent the callers input. Note the syntax used to call aproperty. To set a property use:

    t.SecondsToToast= 12;

  • 7/31/2019 A Twisted Look at Object Oriented Programming in C

    39/57

    8) Use "is" instead of "instanceof", ArrayList instead of ArrayList/Vector,StringBuilder instead of StringBuffer, Hashtable instead of HashMap/Hashtable,System.Environment.NewLine instead of line.separator..

    Just trying to save you some headaches.

    9) There is an "enum"

    Java evolved before the concept of type safe enum. C# has built in support for type safe enumslike this:

    public enum ColorType {Black, Red, Yellow, White};private static ColorType DEFAULT_COLOR= ColorType.Black;

    You can still create a custom enum in C# like this:

    sealed class MyEnum{

    private String name;

    private static int nextOrdinal= 1;private int ordinal= nextOrdinal++;private MyEnum(String name){

    this.name= name;}public override String ToString(){

    return name;}public int ToOrdinal(){

    return ordinal;

    }public static MyEnum INVALID= new MyEnum("Invalid"); // ordinal 1public static MyEnum OPENED= new MyEnum("Opened"); // ordinal 2public static MyEnum CLOSED=new MyEnum("Closed"); // ordinal 3/// /// The main entry point for the application./// [STAThread]static void Main(string[] args){

    //// TODO: Add code to start application here//Console.WriteLine(MyEnum.OPENED.ToString());

    Console.WriteLine(MyEnum.OPENED.ToOrdinal().ToString());Console.WriteLine(MyEnum.INVALID.ToString());Console.WriteLine(MyEnum.INVALID.ToOrdinal().ToString());Console.WriteLine(MyEnum.CLOSED.ToString());Console.WriteLine(MyEnum.CLOSED.ToOrdinal().ToString());Console.ReadLine();

    }}

  • 7/31/2019 A Twisted Look at Object Oriented Programming in C

    40/57

    10) String Equality Operator is Overridden for Content Comparison

    Thankfully, the string equality operator in C# has been overloaded and checks for content/valueequivalence. One less gotcha for the C# novice.

    Note: The overloaded string equality operator only works on reference variables of Type string.

    Be careful! Thanks to Jon S. for this insight.

    object a= "Hello";object b= "Hello";bool isSameReference= (a == b); // test if a and b contain referencesto the same object or to no object (are both null)bool isSameContent= ((string)a == (string)b); // test if stringreferenced by a and string referenced b have the same content/value ora and b are both null

    Session["KEY"]="VALUE"; // Error! The left hand operand is of typeobject! This is a reference based comparison. Do this:(String)Session["KEY"]="VALUE"; // content equivalence

    OK, boys and girls. It's not your father's language. Get over it.

    The Equality Operator Revisited

    Thanks to Jon S. I have revisited the concept of equality on operands of the reference type. Theequality operator, in general, compares operands by reference. The string equality operator isoverloaded to compare operands by value. In plain English, the equality operator normallychecks to see if two object variables refer to the same object on the heap. The string equalityoperator is overloaded to check for content or value equivalence.

    In not so plain English, the equality operator normally checks to see if two reference variablescontain references to the same object on the heap. In C# local reference variables go on the

    stack and contain the address of the object on the heap. So local reference based equality in C#checks to see if two reference variables, stored on the stack, contain addresses which are equal.In other words, it checks for address equality. This is referred to as "reference based" equalityor "compare by reference" or "referential equality". Whew!

    As previously stated, the string equality operator is overloaded to check for value or contentequivalence. In not so plain English, the string equality operator compares the content or valueof string objects on the heap. It does this by obtaining the address of the objects from thevalues of the reference variables stored on the stack.

    Now I would like to simplify this discussion to that of "object" equality vs. "content" equality, butI cannot! By convention, object equality refers to content equality! I would also like to reducethis discussion to referential "equality" vs. content "equivalence", but I cannot. Unfortunately,by convention, the Equals() method is used to determine content equivalence!

    Objects Have Class, References Have Type

    Well, you have arrived. If you have survived to this point, you are beginning to realize both thepower and complexity of programming using objects and inheritance. Much of the confusionabout references, types, classes and objects is simplified by the following statement "Objectshave class, references have type." The more technically correct version may be "Objects haveclass, reference variables have type." As long as it is understood that reference variables"contain" references to objects, the former statement is a superior in its simplicity.

  • 7/31/2019 A Twisted Look at Object Oriented Programming in C

    41/57

    What is a Type?

    There are a number of definitions of a type, but I have struggled to find an illuminatingstatement.

    According to Grady Booch (Object Oriented Analysis and Design) type is "The definition of the

    domain of allowable values that an object may possess and the set of operations that may beperformed upon the object. The terms class and type are usually (but not always)interchangeable; a type is a slightly different concept than a class, in that it emphasizes theimportance of conformance to a common protocol... Typing lets us express our abstractions sothat the programming language in which we implement them can be made to enforce designdecisions."

    According to Bertrand Meyer (Object-Oriented Software Construction) "A type is the staticdescription of certain dynamic objects: the various data elements that will be processed duringexecution of a software system...The notion of type is a semantic concept, since every typedirectly influences the execution of a software object by defining the form of the objects that thesystem will create and manipulate at run time."

    According to the "Gang of Four" (Design Patterns) "The set of all signatures defined by an

    object's operations is called the interface to the object... A type is a name used to denote aparticular interface.... An object may have many types, and widely different objects can share a

    type.... An object's interface says nothing about its implementation--different objects are free toimplement requests differently."

    It is the last definition that emphasizes the concept of programming to an interface, one or morepublic views of an object. You can look at an interface as a contract between the designer of theclass and the caller of the class. The interface determines what public fields and methods arevisible to a caller of a class. C# provides direct support for "design by contract" with the keyword interface. In C#, a class can inherit multiple interfaces and a single implementationhierarchy. Thus a class can contain one or more distinct public contracts. Both Booch and Meyerallude to the fact that types allow the compiler to enforce design decisions and influence theexecution of software. Why is this so important? The answer is that references imply restricted

    access.

    References Have Type

    You will recall that methods and properties of an object have access modifiers such as public,protected and private. The calling context and access modifiers determine the visibility of fieldsand methods of an object. Thus, public fields and methods are visible to callers outside of theclass. However, there is another level of access control that is much more difficult to grasp andexplain. In a nutshell, when you declare a reference variable, the type of the reference variablerestricts access to one of the object's public contracts.

    You use a reference variable to touch an object's fields and properties. The key concept is thatthe type of the reference variable determines which of the objects public contracts (interfaces) isaccessible using the reference variable. If an object had only one distinct public contract, thisdiscussion would be moot. But in fact an object can have many public contracts. For instance,every object in the C# framework derives from the base class Object. Lets look again at theinheritance hierarchy for TextBox:

    System.ObjectSystem.Web.UI.ControlSystem.Web.UI.WebControls.WebControlSystem.Web.UI.WebControls.TextBox

  • 7/31/2019 A Twisted Look at Object Oriented Programming in C

    42/57

    The TextBox control inherits from WebControl which inherits from Control which inherits fromObject. Each of these four classes defines an interface or public view, a type. If you declare areference variable of type Object, only the public members defined in System.Object are visibleusing the reference variable.

    object tb= new TextBox();

    If you use the Visual Studio IDE and enter "tb." the IDE will automatically display the only fourmethods that can be touched using "tb":

    Equals()GetHashCode()GetType()ToString()

    Thus the type of the reference variable "tb", object, limits access to a subset of the publicmethods and fields of the instance of class TextBox. Only one of the many public interfaces canbe touched with the reference variable "tb". You could also declare "tb" as type Control:

    Control tb= new TextBox();

    Now if you enter "tb.", a larger number of public fields and methods are automatically displayedby the IDE including:

    Equals()GetHashCode()GetType()ToString()...DataBind()Dispose()

    Finally, if you declare a reference variable of type TextBox all of the public fields and membersof the class TextBox are visible using the reference variable "tb" including:

    Equals()GetHashCode()GetType()ToString()DataBind()Dispose()...Text

    All I can suggest is try it! Declare the variable "tb" using different types and see how the type of

    the reference variable restricts access to the public interface of the object. Note that an object'sset of possible interfaces (types) can be defined by the objects class hierarchy as in thepreceding example or through inheritance of multiple interfaces. For example, here is the

    declaration of the class Hashtable that implements six distinct interfaces:

    public class Hashtable : IDictionary, ICollection, IEnumerable,ISerializable, IDeserializationCallback, ICloneable

    IEnumerable hash=new Hashtable();

  • 7/31/2019 A Twisted Look at Object Oriented Programming in C

    43/57

    The reference variable hash is of type IEnumerable and is restricted to the public methods andfields of the IEnumerable Interface and System.Object:

    Equals()GetHashCode()GetType()

    ToString()GetEnumerator()

    Objects Have Class

    Well this should be pretty self explanatory. Remember, an object is an instance of a class andgoes on the heap. A local reference variable goes on the stack and is used to touch an object.

    The full interface of the object is defined in the class so an object has class. The object variable,on the other hand, is restricted by its type and can only be used to touch fields and propertiesdefined in its type (or in System.Object). The compiler enforces the design decisions. Be clear,when you created a reference variable of type object in the previous example, you still createdan instance of class TextBox on the heap.

    object tb= new TextBox();

    This line of code creates a local reference variable of type object on the stack and an object ofclass TextBox on the heap.

    Casting About

    Since you can only touch an object using a reference variable, at times the need arises tochange the type of a reference variable. You can do this by "casting" the type of a referencevariable to another valid type. The type of the variable must be in the domain of types (public

    interfaces) defined by the class of the object. If you try to cast an object variable to a type thatis not supported by the class of the object, a runtime exception will be thrown. "Casting up" theclass hierarchy from a subtype to a base type is always safe. The converse is not true. "Castingdown" the class hierarchy is not always safe and result in a runtime InvalidCastException. Hereis an example of casting down the class hierarchy:

    object tb= new TextBox();((TextBox)tb).Text= "Hello";

    By explicitly casting the reference variable to the type TextBox, you are telling the compiler thatyou want to access the full interface of the class TextBox. A more common task is createanother reference variable like this:

    TextBox textBox= (TextBox)tb;

    This creates a separate local reference variable on the stack of type TextBox. Both variables,

    "tb" and "textBox", contain references to the same object on the heap of class TextBox, buteach variable has a different type and hence different access to the public fields and methods ofthe single object on the heap.

    A Twisted Analogy

    Now if this is just not making sense to you, let me try a twisted analogy of types. Just as anobject can have different public views, a complex person can wear different "hats" or playdifferent roles in life. A complex person can have multiple defined roles or types. When acomplex person is wearing the "hat" of say a police officer, he or she is restricted by the implied

  • 7/31/2019 A Twisted Look at Object Oriented Programming in C

    44/57

    contract between the clients (the populace) and the role of a police officer. When in uniform, thecomplex person has a type of police officer. When that same complex person goes home, he orshe may put on the "hat" of a parent and is expected to exhibit behavior consistent with the roleof a parent. At home, off duty, the complex person is expected to have the type of a parent. Inan emergency, the off duty complex person is expected to assume the role of a police officer.You can "cast" an off duty officer of type parent to a police officer. You should not cast a twisted

    programmer of type parent to the type police officer. This will definitely result in a runtime

    exception!

    IS and AS

    Since casting down the class hierarchy is not "safe", you must code defensively. The C#language provides the key words is and as which greatly simplifies writing exception safe code.The key word is returns true if the object referred to by the left sided operand supports the typeof the right sided operand. According to the IDE:

    The is operator is used to check whether the run-time type of an object is compatible with agiven type. The is operator is used in an expression of the form:

    expression is type

    Where:

    expressionAn expression of a reference type.

    typeA type.

    Remarks

    An is expression evaluates to true if both of the following conditions are met:

    expression is not null. expression can be cast to type. That is, a cast expression of the form (type)

    (expression) will complete without throwing an exception. For more information, see

    7.6.6 Cast expressions .

    A compile-time warning will be issued if the expression expression is type is known to

    always be true or always be false.

    The is operator cannot be overloaded.

    Here is an example using is:

    private TextBox Cast(object o){if (o is TextBox){return (TextBox)o;}else{return null;}

  • 7/31/2019 A Twisted Look at Object Oriented Programming in C

    45/57

    }object tb= new TextBox();TextBox textBox= Cast(tb);

    In this sample using is, if the cast is invalid the result is null. Alternatively, you can use the keyword as. According to the IDE:

    The as operator is used to perform conversions between compatible types. The as operator isused in an expression of the form:

    expression as type

    where:

    expressionAn expression of a reference type.

    typeA reference type.

    Remarks

    The as operator is like a cast except that it yields null on conversion failure instead of raising anexception. More formally, an expression of the form:

    expression as type

    is equivalent to:

    expression is type ? (type)expression : (type)null

    except that expression is evaluated only once.

    As in the previous example using is, if the cast is not valid, the result is null. I prefer using is. Iwould argue that code using is, is more readable than code using as.

    Well I hope this discussion of references, types, classes and objects has clarified things for you.In a nutshell, when you declare a reference variable, the type of the reference variable restrictsaccess to one of the object's public contracts. When in doubt, repeat the mantra "Objects haveclass, references have type."

    To Inherit or Contain? That is the Question.

    In Chapter 2, you visited the design conundrum of using inheritance or containment. In thischapter you will use both. First you will use inheritance to create a custom, type safe, null safe

    collection. You will then use containment to wrap the custom collection and "adapt" theread/write collection interface to a read only interface.

    Here again is the discussion from Chapter 2: One difficult design decision is to decide if a classshould inherit from a parent class or hold a reference to a new object. Inheritance represents anIS_A relationship from a generalization to a specialization. Containment represents a HAS_Arelationship between the whole and a part. So a car IS_A motorized vehicle, but HAS_A radio.The two relationships can be expressed in code thusly:

  • 7/31/2019 A Twisted Look at Object Oriented Programming in C

    46/57

    class Radio{

    ...}class Vehicle{

    ...}class Car : Vehicle{

    Radio r= new Radio();}

    Let's Get Your Inheritance

    One common real world task is to create a type safe, null safe collection. For instance, youmight want to create a collection that can only store elements that are non null references oftype Drawable. This allows you to iterate over the collection casting each element and thencalling a public method on every element without fear of a NullReferenceException or aInvalidCastException.

    Here again is the Drawable type implemented as an interface:

    // an interface version of Drawableinterface Drawable{

    void DrawYourself();}class Circle : Drawable{

    public void DrawYourself(){

    System.Console.WriteLine("Circle");

    }}class Square : Drawable{

    public void DrawYourself(){

    System.Console.WriteLine("Square");}

    }

    You can now create a type safe, null safe collection by extending the abstract base classSystem.Collections.CollectionBase. CollectionBase was designed for use as a base class of acustom type safe collection. Extending CollectionBase automatically exposes all of the public

    methods of CollectionBase such as Count and GetEnumerator(). Here is an example of usinginheritance to create a type safe, null safe collection of Drawable elements. The set indexer callsthe type and null safe Insert method..

    Note: You could also create a type safe collection by creating a class that contains an ArrayListand provides pass through getter and setter methods that take and return only references oftype Drawable. This would require that you provide a do nothing pass through method for everypublic type safe method in ArrayList that you want to expose in the containing class.

  • 7/31/2019 A Twisted Look at Object Oriented Programming in C

    47/57

    /// /// DrawableCollection/// A type safe, null safe collection of Drawable objects/// Demonstrates the use of Inheritance/// A DrawableCollection IS_A Collection/// Extends CollectionBase to create a specialization/// class DrawableCollection : System.Collections.CollectionBase{

    // Custom implementations of the protected members of IList// returns -1 if parameter is nullpublic int Add(Drawable value){

    if (value != null){

    // throws NotSupportedExceptionreturn List.Add(value);

    }else{

    return -1;}

    }public void Insert(int index, Drawable value){

    if (value != null){

    //throws ArgumentOutOfRangeExceptionList.Insert(index, value);

    }// else do nothing

    }public void CopyTo(Array array, int start){

    //throws ArgumentOutOfRangeExceptionList.CopyTo(array, start);

    }// provide an indexerpublic Drawable this[int index]{

    get{

    // ArgumentOutOfRangeExceptionreturn (Drawable)List[index];

    }set{

    //throws ArgumentOutOfRangeExceptionInsert(index,value);

    }}

    }

    The key here is that all of the setter methods (Add, Insert, set) validate for non null and take areference of type Drawable. Any attempt to pass a null reference will be ignored. Any attempt topass a reference to an object that does not support the Drawable interface will fail. Thisguarantees that all elements in the collection are of the type Drawable and are not null. This

  • 7/31/2019 A Twisted Look at Object Oriented Programming in C

    48/57

    allows you to iterate over the collection without fear of a NullReferenceException or aInvalidCastException like this:

    foreach(Drawable d in drawableCollection){

    System.Console.WriteLine(d.ToString());

    }

    Note: Using foreach hides the call to GetEnumerator(). Here is the explicit call usingIEnumerator:

    System.Collections.IEnumerator enumerator= dc.GetEnumerator();while (enumerator.MoveNext()){

    System.Console.WriteLine(((Drawable)(enumerator.Current)).ToString());}

    C# supports the concept of an indexer which supports random access to a collection using the

    index operator ([]). A custom indexer does not add support for a Length property. Here again isthe get and set code that