Deborah's Developer MindScape






         Tips and Techniques for Web and .NET developers.

Archive for OOP

September 5, 2014

Abstract Class vs Interface

Filed under: C#,OOP @ 5:10 pm

Since publishing my course on Object-Oriented Programming Fundamentals in C# for Pluralsight, I often receive questions from viewers. One of the common questions is on the difference between an Abstract Class and an Interface.

Abstract Class

An abstract class is a class that cannot be instantiated, meaning you can’t use the new keyword to create one. Some key qualities of an abstract class:

  • It is intended to be used as a base class for other classes that inherit from it.
  • It can provide implementation, meaning that it can contain the code for an operation.

For example, you could define an abstract product base class:

public abstract class ProductBase

{

   public bool Save {

       // Code here to save the product

   }

}

The Save method here would contain the code to save a product.

You could then create specialized product classes: BookProduct, GroceryProduct, and OfficeProduct. Each of these specialized classes inherit from the ProductBase class. The specialized product classes then don’t need to contain the logic for the save, because it is provided in the base class.

Say you then define another abstract class for logging.

public abstract class Logging

{

   public void Log{

       // Code here to log information

   }

}

You need the logging functionality in the BookProduct class. Since C# does not allow multiple inheritance, the BookProduct class cannot inherit from *both* the ProductBase class and the Logging class. You instead have to create a hierarchy:

BookProduct class inherits from ProductBase class which inherits from the Logging class.

GroceryProduct class also inherits from ProductBase class which now inherits from the Logging class. So even if the GroceryProduct class does not want or need logging, it still has all of the logging features because Logging is part of its class hierarchy.

This can lead to deep inheritance chains that make the code more complex and difficult to maintain/extend.

Interface

An interface is a set of properties and methods. You can think of an interface as a contract whereby if a class implements the interface, it promises to implement *all* of the properties and methods in the interface. Some key qualities of an interface:

  • It is intended to be implemented by other classes. Each class that implements the interface promises to provide code for each property and method in the interface.
  • An interface cannot contain any implementation, meaning that it does not contain any code, just declarations.

Using the same example as above, you could define IProduct:

   public interface IProduct{

       bool Save();

   }

This interface cannot contain any code for the save. So each product class (BookProduct, GroceryProduct, and OfficeProduct) would need to implement this interface and provide its own code for the save feature.

Say you then define an interface for logging.

   public interface ILoggable{

       void Log();

   }

Any of the product classes that need logging can implement this interface. You can think of an interface as defining a role that a class can take on. For example, the BookProduct class could take on a logging role, email role, and printing role by implementing a logging interface, email interface, and printing interface.

By using an interface:

  • Only the specialized product classes that need logging can implement the ILoggable interface.
  • Each product class that does implement the ILoggable interface needs to provide its own implementation.
  • Other classes (completely unrelated to products) can use the ILoggable interface. The class does not need to be defined within the same hierarchy.

Summary

You can think of an abstract class as a bucket of functionality shared by all of your relatives. And an interface as a role that anyone in the community can take on.

Use an abstract class if:

  • You are building a base class.
  • You want to provide code that the specialized child classes could use (or override)
  • You don’t need the functionality in the abstract class for any classes other than those within the class hierarchy.

Use an interface if:

  • You are defining a “role” that a class could take on.
  • You may want to use the interface on unrelated classes.
  • Each class implementing the interface will provide an implementation.

Thoughts? Questions? Please use the space below to submit your comments.

Enjoy!

PS circle

Check out my Pluralsight courses!

April 29, 2010

Collection Initializers

Filed under: C#,OOP,VB.NET @ 5:08 pm

One of the new features in VB 10.0 is collection initializers. Collection initializers allow you to initialize an array or list in a single line of code.

(C# has had collection initializers since C# 3.0. The examples here show both C# and VB for completeness.)

This example uses the customer class defined here and builds a list of customers using collection initializers.

In VB:

Dim custList As New List(Of Customer) From
            {New Customer() With
                  {.CustomerId = 1,
                    .FirstName = "Bilbo",
                    .LastName = "Baggins",
                    .EmailAddress = "bb@hob.me"},
            New Customer() With
                  {.CustomerId = 2,
                    .FirstName = "Frodo",
                    .LastName = "Baggins",
                    .EmailAddress = "fb@hob.me"},
            New Customer() With
                  {.CustomerId = 3,
                    .FirstName = "Samwise",
                    .LastName = "Gamgee",
                    .EmailAddress = "sg@hob.me"},
            New Customer() With
                  {.CustomerId = 4,
                    .FirstName = "Rosie",
                    .LastName = "Cotton",
                    .EmailAddress = "rc@hob.me"}}

In C#:

List<Customer> custList = new List<Customer>
        {new Customer()
              { CustomerId = 1,
                FirstName="Bilbo",
                LastName = "Baggins",
                EmailAddress = "bb@hob.me"},
        new Customer()
              { CustomerId = 2,
                FirstName="Frodo",
                LastName = "Baggins",
                EmailAddress = "fb@hob.me"},
        new Customer()
              { CustomerId = 3,
                FirstName="Samwise",
                LastName = "Gamgee",
                EmailAddress = "sg@hob.me"},
        new Customer()
              { CustomerId = 4,
                FirstName="Rosie",
                LastName = "Cotton",
                EmailAddress = "
rc@hob.me"}};

Notice how these two code snippets are very similar. VB even has the same curly braces!

The key differences are that VB requires the From keyword when initializing the list, the With keyword when initializing each customer in the list, and the "." in front of the property names.

Compare this VB example to the one shown for VB 9 (VS 2008) here.

Use this technique whenever you need to initialize a list or array of objects.

Enjoy!

September 8, 2009

Understanding Object Binding

Filed under: C#,Data Binding,OOP,VB.NET,Visual Studio @ 2:26 pm

Before going through the details of how to use object binding, it is important to understand exactly what it is—and what it is not. Object binding is binding your business object properties to user interface elements. Object binding is not database binding in the strict sense of the term. It does not directly collect or bind any data from your database.

When you are using business object classes without object binding, the flow of data from the database to your user interface and back again requires these steps:

1. The business object calls the data access component to get the data from the database and sets the business object properties using that data.

For example, the Product class calls the data access component, which uses a query or stored procedure to fill a DataTable from the Product table. The data access component returns the DataTable to the Product class, which assigns each field from the table to a property of the object. To illustrate, the line of code required to get the ProductName field from the DataTable and set the
ProductName property is as follows:

In C#:

myProduct.ProductName = dt.Rows[0]["ProductName"];

In VB:

myProduct.ProductName = dt.Rows(0).Item("ProductName")

2. The user interface component accesses the business object properties to fill the values of the controls on the form.

For example, each control on the ProductWin form is assigned to the value of the appropriate Product business object property. To illustrate, the line of code required to set the Text property of the Name TextBox control to the ProductName property of the Product business object is as follows:

In C#:

NameTextBox.Text = myProduct.ProductName;

In VB:

NameTextBox.Text = myProduct.ProductName

3. After the user makes any changes, the user interface component assigns the current values in the controls back to the business object properties.

For example, the value in each control on the ProductWin form is assigned back to its associated Product business object property. To illustrate, the line of code required to set the ProductName property to the current value in the Name TextBox control is as follows:

In C#:

myProduct.ProductName = NameTextBox.Text;

In VB:

myProduct.ProductName = NameTextBox.Text

4. The business object component updates the DataTable using the property values and passes it back to the data access component, which updates the database with the changed data.

For example, the value of each Product business object property is assigned to the associated field in the DataTable, and the result is passed to the data access component, which updates the Product table. To illustrate, the line of code required to set the ProductName field in the DataTable to the value of the ProductName business object property is as follows:

In C#:

dt.Rows[0]["ProductName"] = myProduct.ProductName;

In VB:

dt.Rows(0).item("ProductName") = myProduct.ProductName

Using object binding allows you to skip steps 2 and 3. Object binding automatically populates the controls on the user interface from the business object properties. As the users change the contents of the controls, object binding updates the associated business object properties, keeping them in synchronization.

That still leaves steps 1 and 4 for you. This link provides information on building a data access component to handle steps 1 and 4.

In summary, object binding is the process of binding control properties directly to properties of your business objects. For example, you could bind the Text property of a TextBox control to the ProductName property of a Product business object. When the form is displayed, the runtime automatically displays the value of the ProductName property in the TextBox. And if the user changes the text in the TextBox control, the runtime modifies the ProductName property accordingly. This saves you from writing the code required to transfer data back and forth between the controls on the user interface and the business object properties.

Visual Studio provides design-time tools for working with your business objects as data sources for your user interface, making it easy to bind each control to its associated business object property. The only requirement for your business objects to work with these tools is that the business object class needs at least one public property. No specific constructors, interfaces, or attributes are needed.

Object Binding Versus Data Binding

Don’t confuse the term object binding with the more generalized term data binding. Data binding is the broad term for binding control properties to data from any data source. Object binding is just one type of data binding. Some common types of data binding are as follows:

  • Binding to tables in a database (Visual Studio generates code to
    define a typed DataSet and TableAdapters)
  • Binding to stored procedures in a database (Visual Studio generates
    code to define a typed DataSet and TableAdapters)
  • Binding to a business object (object binding does not generate code;
    it just sets control properties)
  • Binding to an array or collection of data
  • Binding to a Web service

When binding to a database, Visual Studio generates a significant amount of code and then binds the user interface to that generated code. Object binding binds to your code. That gives you much more control and greatly simplifies the maintenance of your application.

Using Object Binding

You use object binding by following these steps:

1. Build the business objects for your application.

2. Define a business object data source in the Windows Application
project containing your user interface.

3. Bind properties of the controls on the form to business object
properties.

Although it is much easier to think about object binding as a direct binding of a control’s property to a specific business object’s property, object binding frequently uses a BindingSource component as an intermediary. A BindingSource is a component on a form that binds the controls on the form to the business object. Each control is bound to the BindingSource component, which in turn is bound to the business object. This makes it much easier to change the binding for all controls by changing the BindingSource without having to separately rebind each control.

You set the BindingSource to an individual business object instance in your code. The runtime then binds all the properties associated with that instance to the controls, thereby displaying the business object property values in the controls. And as the user changes the content of any controls, the business object property values are changed accordingly.

A form can contain multiple BindingSource components. For example, a ProductWin form can contain product data and display a drop-down list of product types. You can define a BindingSource component for the product data and a second BindingSource component for the product type data.

(Based on an except from "Doing Objects in Visual Basic 2005".)

For more information on object binding, see these links:

Enjoy!

September 1, 2009

Basic Pillars of an Object-Oriented System

Filed under: C#,OOP,VB.NET @ 12:16 pm

The four basic elements of an object-oriented system are abstraction,
encapsulation, inheritance, and polymorphism. This post defines
these terms and describes why they are important to software design and
development.

[To begin with an overview of OO, start here.]

Abstraction: Focusing on What is Important

Abstraction is a technique that we all use to manage the complexity of the
information we collect every day. It allows us to recognize how things are
similar and ignore how they are different, to think about generalities and
not specifics, and to see what things are without thinking about what makes
them that way. You can abstract important characteristics at any given time
and for any particular purpose and ignore all other aspects.

How you develop an abstraction depends on both its purpose and your
perspective. For example, on a warm summer day I look at a tree and
abstract it as a shade provider. A young child abstracts it as a place to
climb. One tree, two different abstractions.

Abstraction is used to identify the objects involved with a particular
application. In developing a payroll system, you would think about Jessica
Jones and abstract her as an employee, thinking only about her salary and
how she gets paid. When working on the company softball league application, you would abstract Jessica as a player and be more concerned with her position and batting average. One object, two completely different abstractions.

Scenarios (or use cases) can ensure that the correct abstraction is used in a particular application. They provide context for the objects, giving them a purpose.

Using abstraction, you can focus on the objects and not on the implementation. This lets you think about what needs to be done and not how the computer will do it.

Encapsulation: Hiding Your Private Parts

Most organizations have independent units, usually called departments.
The sales department makes the sales, the production department produces
the item, the shipping department ships it, and so on. Each department
is responsible for its own procedures and internal information. For example, the sales department has procedures for calling prospects, evaluating
the opportunity, sending sales materials, following up with current
customers, maintaining prospect information, and so on.

You could say the departments are encapsulated because the internal
information (properties) and standard operating procedures (methods)
are contained within the department. These are figuratively hidden from
other departments except through defined interfaces. Anyone who needs
the department’s procedures or information goes to that department to
ask for it.

If a shipping clerk acquires the name of a prospect, the clerk knows
better than to handle the prospect directly. Instead, the clerk collaborates
with the sales department by using the publicly accessible defining prospects
feature and sends the name to them.

The same principles are used in object-oriented applications to encapsulate
each object’s properties and methods. When an object needs to perform
a procedure that is encapsulated in another class, it does not perform
the procedure directly. Instead, it collaborates with an object belonging to
the other class to perform the procedure.

Encapsulation aids in abstraction by hiding the internal implementation
of an object within the class. You then can use an object without
understanding how its class is implemented. So the shipping clerk can
define a prospect to the sales department without knowing how the sales
department actually handles the prospect.

Inheritance: Attaining Reuse

Things that are similar still have some differences, and things that are
different often have some similarities. Reviewing the inheritance
example (from my post here), both your desk phone and your cell phone can be classified as phones. Looking at their differences, your desk phone can transfer calls, and your cell phone can take pictures.

Say you are asked to create phone emulator software. You could implement
all properties and methods for a cell phone into a cell phone class. This class would include volume and picture count properties and dial, answer, disconnect, and take picture methods. Likewise, you could implement all properties and methods for a desk phone into a desk phone class.

This class would include volume and line status properties and dial,
answer, disconnect, and transfer call methods. This duplicates the common
phone information and functionality in both classes.

You can remove the property and method redundancy and attain reuse
by using inheritance. You can remove the common phone properties and
methods from the specialized classes and put them in a higher-level phone
class. The cell phone class and desk phone class can then inherit from the
phone class, attaining all its properties and methods. This “is a” relationship
is depicted here.

If a new type of phone class, such as a Web phone, were added, objects of the new class would automatically have all the properties and methods defined for the base phone class, greatly simplifying the development of the new class.
Inheritance is a powerful tool for code reuse.

Polymorphism: Same Behavior, Different Implementation

Two or more classes can have methods that are named the same and have
the same basic purpose but different implementations. This is polymorphism.
The Text property of the .NET Framework is an example of polymorphism.
Although the basic purpose of the Text property is the same, how the property works depends on whether you are setting the Text property of a Form, a Label, or a TextBox.

In the phone example, say the implementation of the Dial method
needed to be different in the cell phone class and the desk phone class.
The cell phone class would then need its own Dial method, and a desk
phone class would need its own Dial method. You can request the Dial
method by an object from either class without knowing how either class
plans to implement that request. Both the cell phone class and the desk
phone class have the Dial method, but the implementation of that behavior
can be completely different.

Polymorphism can be implemented using inheritance. The base phone
class would retain a Dial method, but the implementation would be empty
(or would provide a default implementation). Each derived class would
then override the base class Dial method by implementing the method.
The result is that the desk phone class and cell phone class each have a
Dial method, but the implementations are different.

Polymorphism can also be implemented using an interface. In the
phone example, the Dial method would be removed from the base phone
class. An IDial interface would define the properties and methods for
handling dialing. Both the desk phone class and cell phone class implement
this interface so that they both have the same properties and methods
for dialing but different implementations. (See this link for more information on interfaces.)

The benefit of polymorphism is that you don’t need to know the
object’s class to execute the polymorphic behavior. For example, you may
have many classes in an application, each with its own save method. When
the application is saved, each object knows the class it belongs to and automatically calls the correct save routine.

(Based on an except from "Doing Objects in Visual Basic 2005".)

Enjoy!

What is an Interface?

Filed under: C#,OOP,VB.NET @ 11:29 am

When talking about OO, the term “interface” has nothing to do with your
user interface. An interface defines a list of properties and methods that
a class can implement. But if the class implements a particular interface, it
must implement all properties and methods defined by that interface.

[To begin with an overview of OO, start here.]

For example, you can think of a phone as implementing a dial interface,
IDial. (By convention, interfaces begin with the letter I.) This interface defines Connect and MakeTone methods but does not implement them. This allows each phone to define how it connects and makes tones. Every phone that implements the IDial interface must provide an implementation
for both the connect and make tone methods.

An interface is different from a base class in that an interface defines
the list of properties and methods with no implementation. The implementation
is left to the class that implements the interface. A base class contains both the list of properties and methods and their implementation. The class that inherits from the base class does not need to provide any implementation.

In your application, you can implement interfaces provided in the
.NET Framework or define and implement your own interfaces. For
example, if you want to ensure that every MDI child form in your application
provides a standard set of methods, you could define an IMDIChild interface as follows:

In C#:

public interface IMDIChild
{
    bool ProcessDelete();
    bool ProcessNew();
    bool ProcessSave();
}

In VB:

Public Interface IMDIChild
    Function ProcessDelete() As Boolean
    Function ProcessNew() As Boolean
    Function ProcessSave() As Boolean
End Interface

In this example, the interface is comprised of three methods: ProcessDelete, ProcessNew, and ProcessSave. Each of these methods must be implemented in any class that implements this interface.

To implement an interface in a class, specify the interface when defining the class. For example, if the TimeSheetWin class implements the IMDIChild
interface, it would look like this:

In C#:

public class TimeSheetWin : IMDIChild

In VB:

Public Class TimeSheetWin
    Implements IMDIChild

Each class that implements this interface must provide an implementation
for all three of the interface methods.

[For an example of implementing the .NET IDataErrorInfo and INotifyPropertyChanged interfaces, see this link.]

Implementing an interface allows a class to be more formal about the
behavior it promises to provide. Interfaces form a contract between the
class and the rest of the application, and the compiler enforces this contract.
If your class claims to implement an interface, all methods defined by that
interface must be implemented before the class successfully compiles.

(Based on an except from "Doing Objects in Visual Basic 2005".)

Enjoy!

What is Inheritance?

Filed under: C#,OOP,VB.NET @ 10:58 am

In object-oriented (OO) terms, inheritance defines an “is a” relationship between two or more classes. A beagle is a dog, and a poodle is a dog, so both beagle and poodle inherit from dog. Both beagle and poodle have dog attributes and exhibit dog behaviors. A dog class in this example is called the parent class or base class, and the classes that inherit from it (beagle and poodle) are called child classes or derived classes.

[To begin with an overview of OO, start here.]

Likewise, think about your phone. All types of phones have basic
phone attributes and behaviors, such as volume, dial, answer, and disconnect.
Your desk phone may have additional, specialized behaviors, such
as transfer features. Your cell phone has amazing features such as taking
pictures and playing movies.

Even though each type of phone may have specialized behaviors, your
desk phone is a phone, and your cell phone is a phone, so both desk phone
and cell phone inherit their basic functionality from phone. Phone is the
parent (or base) class, and desk phone and cell phone are the child (or
derived) classes. You could draw this relationship as shown below.

image


When you inherit from a class, all the properties and methods in the
base class are available to the derived class, just as if the properties and
methods were in the derived class. So the desk phone can perform the
answer method, as can the cell phone, even though the implementation
for answer is defined in the base phone class.

Any class in the .NET Framework that is not intentionally sealed
(marked as not inheritable) can be a used as a base class. So you can inherit
the functionality of the .NET Framework classes in your application.
You can also use any class in your application as a base class and inherit
from it.

You can see inheritance in action as soon as you create your first form.
When you create a form, Visual Studio generates the following code:

In C# (in the TimeSheetWin.cs file):

public partial class TimeSheetWin: Form

In VB (in the TimeSheetWin.Designer.vb file):

Partial Class TimeSheetWin
    Inherits Windows.Forms.Form

In VB, the Inherits keyword specifies that your form inherits from the .NET
Framework’s Windows.Forms.Form class. In C#, a colon separates the class name from the base class, which again is the Form class. This Form class provides all the common code required to make your form work like a Windows form.

NOTE: In VB, the designer file is, by default, hidden from view in Solution Explorer. To see the designer files for a VB project, select the project in Solution Explorer and then click on the Show All Files button in the Solution Explorer toolbar. Repeat the process to hide the files.

As you define the classes for your application, you may find that some
classes have a number of the same properties and methods but also have
some properties and methods that are different. You can extract the common
properties and methods into another class and then use that class as
a base class.

For example, you may find that each of your business object classes
(such as Employee and TimeSheet) requires a property to keep track of
the dirty state (added, updated, deleted). You can build a business object
base class that contains this property instead of adding it to every class.
Every business object class can then inherit from this base class and therefore have this property.

[For a code example of a business object base class, see this link.]

Using inheritance can minimize the amount of repeated code in your
application. Common code is written only once in the base class and is
reused by every derived class. Inheritance also makes your derived classes
easier to build and maintain, because the derived classes focus exclusively
on the features that make them unique. And if you ever need to change
that common code, you have to change it in only one place.

(Based on an except from "Doing Objects in Visual Basic 2005".)

Enjoy!

August 31, 2009

What is a Class?

Filed under: C#,OOP,VB.NET @ 5:48 pm

Humans like to classify things, to find similarities in things, and to group
them accordingly. Things with similar attributes (properties) and behaviors
(methods) are grouped. In object-oriented terminology, the definition of
the properties and methods that describe a particular classification is called
a class. A class defines a particular object type. You can think of a class as a
blueprint, providing the details of how objects of that type are made.

[To begin with an overview of OO, start here.]

A cookie cutter is another analogy often used to illustrate the relationship
between objects and a class. The cookie cutter is the class and
provides the definition; it specifies the size and shape. The cookies are the
objects created from the cookie cutter class.

For example, an employee class can have name, address, and occupation
properties. Sam Smith and Jessica Jones are both objects from the
employee class. Likewise, a time sheet class can have employee, date, and hours properties and a calculate pay method. Each person’s weekly time
sheet is then an object from the time sheet class.

A specific object created from a class is called an instance of the
class. Each instance can have values for the defined set of properties and
can perform the defined methods. So Sam is an instance of the employee
class, and Jessica’s time sheet for last week is an instance of the time sheet
class.

The set of properties and methods described by a class are often called
class members. A class defines the members, including the actual code to
maintain the property values and perform the methods. Each object that
is an instance of that class can execute the methods and retain values for
each property.

A class itself normally does not maintain state, meaning that it normally
does not have any property values. Nor does it normally execute the class
methods. Instead, the class defines the properties and contains the implementation of the methods that are used by each object created from the
class. Each object has values for the properties and performs the methods.
You do not eat the cookie cutter or fill out a time sheet class. You eat each
cookie and fill out each individual time sheet.

The .NET Framework itself is composed of a set of classes. For
example, the button in the Visual Studio Toolbox represents a Button
class. Each time you add a button to a form, you create an instance of
that Button class. The Button class has specific defined methods, such
as Focus, and properties, such as Name and Text. The Button class
itself does not have a value for the Name or Text properties. Nor can it
have focus. Instead, it contains the implementation of the Name and Text
properties and the Focus method. The Button objects that you create as
instances of that Button class have values for the Name and Text properties
and perform the Focus method.

Code you write normally resides in a class. If you type some
code in a form, your code is in the form’s class. Even if you write code in a
Visual Basic module, the code compiles as a class!

If you have never created a class, the following example may help you
visualize the code for a TimeSheet class.

In C#:

public class TimeSheet
{
    public Employee CurrentEmployee { get; set; }
    public decimal TotalHours { get; set; }

    private DateTime _WeekEndingDate;
    public DateTime WeekEndingDate
    { get
        { return _WeekEndingDate; }
        set
        {
            if (value > DateTime.Now.Date)
                throw new Exception(
                    "Date must be on or before today’s date");
            _WeekEndingDate = value;
        }
    }

    public decimal CalculatePay()
    {
        return CurrentEmployee.HourlyRate * TotalHours;
    }
}

In VB:

Public Class TimeSheet
    Private _CurrentEmployee As Employee
    Public Property CurrentEmployee() As Employee
        Get
            Return _CurrentEmployee
        End Get
        Set(ByVal value As Employee)
            _CurrentEmployee = value
        End Set
    End Property

    Private _TotalHours As Decimal
    Public Property TotalHours() As Decimal
        Get
            Return _TotalHours
        End Get
        Set(ByVal value As Decimal)
            _TotalHours = value
        End Set
    End Property

    Private _WeekEndingDate As DateTime
    Public Property WeekEndingDate() As DateTime
        Get
            Return _WeekEndingDate
        End Get
        Set(ByVal value As DateTime)
            If value > Now.Date Then
                Throw New Exception( _
                "Date must be on or before today’s date")
            End If
            _WeekEndingDate = value
        End Set
    End Property

    Public Function CalculatePay() As Decimal
        Return CurrentEmployee.HourlyRate * TotalHours
    End Function
End Class


The first line defines the class’s scope and name. In this case, the class
is named TimeSheet and is public.

The next set of code defines the private data, called backing fields, and public accessors that provide access to that data. This follows the concept of encapsulation. For example, the private _WeekEndingDate backing field variable contains the value of the time period property. Since this variable is private, it is hidden and cannot be accessed except from within this class. The public WeekEndingDate Property statement implements the get time period and set time period functionality. Any code that needs to set or get the time period uses this public property.

NOTE: The C# code uses auto-implemented properties for the TotalHours and CurrentEmployee. Auto-implemented properties are a short-cut for defining a backing field with its associated accessor. The compiler defines the private backing field for you. You can use auto-implemented properties any time you don’t need extra code, such as validation, in your property statement. (VB is getting auto-implemented properties in VB 10 that is coming with VS 2010.)

By implementing properties using private backing fields and public
Property statements, you can associate code with the setting or retrieval
of the data value. In the WeekEndingDate example, the code that sets the
date validates the date before assigning it.

The code at the end of the class in the preceding example demonstrates
a method—in this case, a function that calculates the pay. In Visual
Basic, methods are implemented with functions or subroutines. In C# the syntax is the same for both functions and subroutines.

To access the properties and use the methods of a class, you normally
begin by creating an instance of the class and storing a reference to that
instance in an object variable. You then use that object variable to get or
set properties and execute methods on the resulting object.
The following code uses the new keyword to create a new object from
the TimeSheet class. It then sets the properties on the object and executes
the CalculatePay method on the object.

In C#:

TimeSheet ts = new TimeSheet();
decimal totalPay;
ts.CurrentEmployee = Jessica; //Jessica is an Employee object
ts.WeekEndingDate = new DateTime(2009, 8, 20);
ts.TotalHours = 51;
totalPay = ts.CalculatePay();

In VB:

Dim ts As New TimeSheet
Dim totalPay As Decimal
ts.CurrentEmployee = Jessica ‘Jessica is an Employee object
ts.WeekEndingDate = #8/20/2009#
ts.TotalHours = 51
totalPay = ts.CalculatePay

The new keyword creates a new instance of the TimeSheet class, and
a reference to that instance is stored in the defined object variable (ts).
Using the object variable and a period, the remainder of the code sets the
object’s properties and calls the method to calculate the pay.

As stated earlier in this section, objects normally maintain state (property
values) and execute methods. The class itself normally does not maintain
state or execute methods. However, .NET does support static
class data and static class methods.

Static class data (also called shared data) is data that the class
retains, independent of any object. Use static class data any time you want
to retain data that is shared between all objects, such as to keep a count of
the total objects created from a class.

A static class method (also called a shared method) is a method
that can be executed independent of any object. Static class methods are
good for utility functions when you don’t need to perform a process on
any particular object. The MessageBox and Debug classes in the .NET
Framework both have static class methods, so you don’t need to create an
instance of the class to use the methods.

NOTE: If you write code in a Visual Basic module instead of a class, all the properties and methods in the module are static. You cannot create an instance from a module.

Building code as individual classes logically separates the code, with
each class defining its own data and implementing its own methods.
Having code organized into logical classes makes finding code for maintenance and enhancements effortless and produces a system that is much easier to extend. It also simplifies testing and debugging, because you can test each class as an independent unit. By using OO, you can manage the complexity of your application.

(Based on an except from "Doing Objects in Visual Basic 2005".)

Enjoy!

What Are Objects?

Filed under: C#,OOP,VB.NET @ 3:42 pm

Objects are things. People, companies, employees, time sheets, and ledger
entries are all types of objects. In object-oriented terms, the word object
is used to describe one specific thing, such as Sam Smith the carpenter at
3322 Main Street and the May 15th time sheet for Jessica Jones.

[To begin with an overview of OO, start here.]

Objects have data associated with them called properties. Sam Smith
has a name, occupation, and address. The time sheet has an employee
name, time period, and hours worked.

NOTE: In object-oriented literature, properties are sometimes called attributes, resources, or even just data.

Objects also do things. The time sheet is filled out, validated, and
submitted for payment. In real life, we fill out time sheets, validate them,
and submit them for payment. In a computer system, the time sheet can
perform these operations for itself. The things an object can do are defined
with methods.

NOTE: In object-oriented literature, methods are also called behaviors,
services, operations, or responsibilities.

Objects can be real-world things, such as an employee or time sheet.
Objects can be conceptual things, such as an engineering process or payroll.
Objects can also be implementation-specific things, such as forms,
controls, and DataSets. The same object-oriented concepts apply regardless
of whether the object is based on the real world, on a concept, or on
the implementation.

Since objects are fundamental to understanding object orientation,
it is important that you can recognize objects and define their appropriate
properties and methods. So take a moment to think about the things
around you. What objects do you see? How would you define their properties
and methods?

Your phone has properties such as color, volume, and mute. It has
methods such as increase volume, decrease volume, turn on mute, turn off
mute, dial, answer, and transfer. An employee has properties such as name,
address, and occupation. An electronic time sheet has properties such as
employee name, date, and hours. It has methods such as calculate pay.

An object’s property values should not be directly accessed by something outside the object. For example, the time period should not be adjusted except through a get time period method, and the employee name would not be retrieved except through a get employee name method. This concept of hiding the internal data is a part of what is called encapsulation and is a key premise of object-oriented programming.

Every object is of a specific type. For example, the object defined as
Sam Smith the carpenter at 3322 Main Street is an employee object type,
and the May 15th time sheet for Jessica Jones is a time sheet object type.
All the objects of a particular type have the same set of properties and
methods.

From a programming perspective, you can define your own object
types using classes. Or you can use the object types provided in the .NET Framework. In either case, you first create an object of the desired type, and then you can set or get the object’s properties and call its methods.

The following code creates an object using the .NET Framework
Timer object type. It then sets the object’s Interval property to define
how often the timer goes off and executes its Start method to start the
timer.

In C#:

Timer myTimer = new Timer();
myTimer.Interval = 1000;
myTimer.Start();

In VB:

Dim myTimer As New Timer
myTimer.Interval = 1000
myTimer.Start()

The new keyword in the first line of code creates a new Timer object
and assigns a reference to that new object to the myTimer object variable.
To access a property or method of the new Timer object, use the object
variable and a period (.) and then the name of the property or method.

NOTE: When you type the object variable name and a period in Visual Studio,
you see a list of the properties, methods, and events that are appropriate for that object. This demonstrates the List Members feature of Intellisense. Intellisense provides auto-completion and display of class documentation within Visual Studio as you are coding.

Everything in .NET can be accessed as an object: forms, strings,
even integers. Check out this code:

In C#:

int i = new int();
string s;
i = 5;
s = i.ToString();

In VB:

Dim i As New Integer
Dim s As String
i = 5
s = i.ToString

The first line creates a new Integer object and assigns it to i. The variable
i is then assigned a value of 5. The last line calls the ToString method of
the Integer object to convert the number to a string.

NOTE: Even though you can use the new keyword to create integers, it is not
necessary and is not commonly done in practice. It is shown in this example to illustrate that you can work with simple data types as objects.

In .NET, an integer and other primitive data types, such as Boolean
and decimal, are called value types. Value types store and pass their contents
by their actual value. Technically speaking, value types are allocated
either on the stack or inline in a structure. A standard set of value types
are built into the .NET Framework, such as integer and decimal. You can
also create your own value types. You do not need to use the new keyword
for any value type.

More complex data types in .NET, such as strings and arrays, are
reference types. Reference types store and pass their contents as a reference to the value’s memory location. Technically speaking, reference types
are allocated on the memory heap. The .NET Framework provides a set of
built-in reference types, such as string and array. Classes that you create are reference types.

.NET automatically creates a boxed value type for each value type when necessary. Boxed value types allow value types to be accessed like reference types (such as the preceding integer example). In addition, boxed value types
allow you to convert value types to reference types. For example, adding
to the preceding code example, you could assign the integer to an object.
This converts the integer value type to an object reference type.

In C#:

object o;
o = i;

In VB:

Dim o As Object
o = i

This conversion of value types to reference types and vice versa is
called boxing. Boxing has a performance hit, so you want to minimize the
amount of boxing in your application wherever possible.

Variables that are value types each have their own copy of the data.
Therefore, operations on one variable do not affect other variables.
Variables that are reference types, such as object variables, can refer to the
same object. Therefore, operations on one variable can affect the same
object referenced by another variable. Check this out:

In C#:

Timer myTimer = new Timer();
myTimer.Interval = 1000;

Timer myTimer2;
myTimer2 = myTimer;
myTimer2.Interval = 500;

Debug.WriteLine(myTimer.Interval); // Displays 500
Debug.WriteLine(myTimer2.Interval); // Displays 500

In VB:

Dim myTimer As New Timer
myTimer.Interval = 1000

Dim myTimer2 As Timer
myTimer2 = myTimer
myTimer2.Interval = 500

Debug.WriteLine(myTimer.Interval) ‘ Displays 500
Debug.WriteLine(myTimer2.Interval) ‘ Displays 500


This code creates a new Timer object, assigns it to the myTimer object
variable, and sets its Interval property to 1000. It then defines a second
myTimer2 object variable, assigns it to the same Timer object, and sets the
Interval property to 500.

Since myTimer and myTimer2 are object variables, they are reference
types. Assigning one object variable to another object variable sets
both variables to reference the same object. Changing the properties
using either object variable makes the changes to the underlying object.
Hence, the sample code results in 500 for both myTimer.Interval and
myTimer2.Interval.

The one exception to this behavior is strings. Even though strings are
a reference type, assigning one string to another string copies the data so
that both strings do not reference the same data. This provides a more
natural use of strings in your application. For example:

In C#:

string employeeName ;
employeeName = "Jessica Jones";

string employeeName2;
employeeName2 = employeeName;
employeeName2 = "Sam Smith";

Debug.WriteLine(employeeName); // Displays "Jessica Jones"
Debug.WriteLine(employeeName2); // Displays "Sam Smith"

In VB:

Dim employeeName As String
employeeName = "Jessica Jones"

Dim employeeName2 As String
employeeName2 = employeeName
employeeName2 = "Sam Smith"

Debug.WriteLine(employeeName) ‘ Displays "Jessica Jones"
Debug.WriteLine(employeeName2) ‘ Displays "Sam Smith"

Even though employeeName2 is assigned to employeeName and then
employeeName2 is changed, employeeName remains unchanged. The
sample code results in the display of Jessica Jones and then Sam
Smith.

Notice also that the New keyword is not required for strings. Strings
were designed as a special case to make it easier and more natural to work with string variables.

Understanding how to create an object and call its properties and
methods is crucial to any development with .NET.

(Based on an except from "Doing Objects in Visual Basic 2005".)

Enjoy!

What is OO?

Filed under: C#,OOP,VB.NET @ 2:27 pm

Today’s world of software design and development is all about managing
complexity. Computer-savvy users want more and more features. Software
products, such as Microsoft Word and Excel, set high expectations. The
business environment requires software to react quickly to shifting corporate
needs. And tools and technologies are changing faster than ever. It is
easy to become overwhelmed by the complexity.

The key to successful software is managing this complexity—and managing
complexity is one of the goals of object orientation (OO).  Object-oriented
means looking at a software system in terms of the things, or
objects, that are relevant to that system and how those objects interact. As
you design and then build your application, you can focus on one object at
a time, temporarily ignoring the complexities of the rest of the system.

OO concepts are used in many professions. For example, when
designing an office, an architect thinks about working spaces, foundations,
frameworks, and plumbing systems. These are the real-world objects. The
architect does not concentrate on the process of pouring the foundation,
hammering nails, or connecting the plumbing, nor on the details of the
data, such as how much concrete or how many nails. These lower-level
processes and details are important but not applicable to the high-level
design of an office building. And without the high-level design, the processes
and data details are irrelevant.

Object orientation does not ignore the data or the process. It combines
the best of a procedure-oriented view (where the focus is on the
process) and a data-centric view (where the focus is on the data) and adds
productivity concepts such as reuse, testability, and, of course, managing
complexity.

Consider a time sheet. Using a data-centric view, the key data elements
are the employee name, date, and hours worked. But just looking at the
data does not provide the full picture of time sheet processing. Using a
procedure-oriented view, the focus is on the process of generating the time
sheet. But this does not consider the bigger picture of how the time sheet
fits into an overall system.

From an object-oriented perspective, the time sheet has data (called
properties) and processes (called methods). It also has relationships to
other objects in the system, such as an employee object, a logging object,
a data access object, and so on.

Thinking about an application in an object-oriented way makes it
easier to break the application into its parts (objects), focus on the most
important aspects of each part, and look at the relationships between those
parts. And since Visual Basic is now a fully object-oriented programming
language, using an object-oriented approach to thinking about your application makes it easier to map these thoughts into object-oriented code.

Excerpt from "Doing Objects in Visual Basic 2005".

For more information on using object-oriented techniques, see the following links:

Enjoy!

August 27, 2009

Building an Alarm Class

Filed under: C#,OOP,VB.NET @ 12:21 pm

The specifics of this class demonstrate how to build an alarm. You can use this class to build an alarm clock application, or to add an alarm feature into your application, similar to the Reminder feature in Outlook.

OR you can just use this class as an example of raising events from a business object or displaying sounds asynchronously.

Build the Alarm class as follows.

In C#:

// Declare a delegate
public delegate void AlarmWentOffHandler(object sender, EventArgs e);

public class Alarm
{
    // Declare an event
    public event AlarmWentOffHandler AlarmWentOff;

    public DateTime? AlarmTime { get; set; }
    private Timer AlarmTimer { get; set; }
    public int SnoozeInterval { get; set; }

    public Alarm() : this(null, 5)
    {  }

    public Alarm(DateTime? timeForAlarm): this(timeForAlarm, 5)
    {  }

    public Alarm(DateTime? timeForAlarm, int minutesToSnooze)
    {
        // Set the properties
        AlarmTime = timeForAlarm;
        SnoozeInterval = minutesToSnooze;

        // Start the timer
        AlarmTimer = new Timer() {Interval = 10000,
                                  Enabled = true};
        AlarmTimer.Tick += CheckAlarm;
    }

    public void Snooze()
    {
        // Reset the alarm by the snooze interval
        AlarmTime = DateTime.Now.AddMinutes(SnoozeInterval);

        // Reset the timer
        AlarmTimer.Enabled = true;
    }

    protected virtual void OnAlarmWentOff(EventArgs e)
    {
        if (AlarmWentOff != null)
            AlarmWentOff(this, e);
    }

    private void CheckAlarm(object sender,
                            EventArgs e)
    {
        // Check whether alarm time has been reached
        if (AlarmTime <= DateTime.Now)
        {
            // Disable the timer
            AlarmTimer.Enabled = false;

            // Raise the event
            OnAlarmWentOff(new EventArgs());
        }
    }
}

In VB:

Public Class Alarm
    Event AlarmWentOff(ByVal sender As Object, ByVal e As EventArgs)

    Private _AlarmTime As DateTime?
    Public Property AlarmTime() As DateTime?
        Get
            Return _AlarmTime
        End Get
        Set(ByVal value As DateTime?)
            _AlarmTime = value
        End Set
    End Property

    Private _AlarmTimer As Timer
    Private Property AlarmTimer() As Timer
        Get
            Return _AlarmTimer
        End Get
        Set(ByVal value As Timer)
            _AlarmTimer = value
        End Set
    End Property

    Private _SnoozeInterval As Integer
    Public Property SnoozeInterval() As Integer
        Get
            Return _SnoozeInterval
        End Get
        Set(ByVal value As Integer)
            _SnoozeInterval = value
        End Set
    End Property

    Public Sub New()
        ‘ Set Defaults
        Me.New(Nothing, 5)
    End Sub

    Public Sub New(ByVal timeForAlarm As DateTime?)
        ‘ Set Defaults
        Me.New(timeForAlarm, 5)
    End Sub

    Public Sub New(ByVal timeForAlarm As DateTime?, _
                   ByVal minutesToSnooze As Integer)
        ‘ Set the properties
        AlarmTime = timeForAlarm
        SnoozeInterval = minutesToSnooze

        ‘ Start the timer
        AlarmTimer = New Timer With {.Interval = 10000, _
                                     .Enabled = True}
        AddHandler AlarmTimer.Tick, AddressOf CheckAlarm
    End Sub

    Public Sub Snooze()
        ‘ Reset the alarm by the snooze interval
        AlarmTime = Now.AddMinutes(SnoozeInterval)

        ‘ Reset the timer
        AlarmTimer.Enabled = True
    End Sub

    Private Sub CheckAlarm(ByVal sender As Object, _
                           ByVal e As EventArgs)
        ‘ Check whether alarm time has been reached
        If AlarmTime <= Now Then
            ‘ Disable the timer
            AlarmTimer.Enabled = False

            ‘ Raise the event
            RaiseEvent AlarmWentOff(Me, New EventArgs())
        End If

    End Sub
End Class

The C# code begins by declaring a delegate for its event. This is not required in the VB code since the delegate is handled for you.

Within the class, the C# and VB code declare an event called AlarmWentOff. This is the event that is generated when the alarm goes off.

The class has three properties:

  • AlarmTime: Time that the alarm should go off.
  • AlarmTimer: A private property that manages the timer for checking the alarm time.
  • SnoozeInterval: The alarm can optionally be set to snooze. This is the amount of snooze time in minutes.

The C# code uses auto-implemented properties and the VB code uses the expanded property syntax. (VB is getting auto-implemented properties in VB 10.)

The constructors for the class optionally define the alarm time and minutes to snooze. The constructor then starts the timer that goes off every 10 seconds. (This can be adjusted as desired. Or the timer interval could be defined as a property of this Alarm class.)

The class has one public method: Snooze. The Snooze method adds the snooze interval amount to the AlarmTime to reset the alarm. It also ensures that the timer in enabled.

Each time the timer goes off, the code checks the current time against the alarm time. If the alarm time has been reached, the code disables the timer and raises the AlarmWentOff event.

This class can be used whenever you need to add an alarm, notification, or reminder to your application. Here is an example of how this class is accessed.

NOTE: It uses a .wav file for the alarm and plays it using the built-in SoundPlayer.

Start by adding this to the top of your code file.

In C#:

using System.Media;

In VB:

Imports System.Media

Then add the following code somewhere in your user interface.

In C#:

Alarm myAlarm;
private void SetTheAlarm()
{
    // Create an alarm object
    myAlarm = new Alarm(DateTime.Now.AddMinutes(1), 1);
    myAlarm.AlarmWentOff +=  AlarmWentOff;
}

private void AlarmWentOff(object sender, EventArgs e)
{
    var player = new SoundPlayer("myFile.wav");
    player.PlayLooping();
    DialogResult replay =
        MessageBox.Show("Wake up" +
                             Environment.NewLine +
                             "Yes to wake up." +
                             Environment.NewLine +
                             "No to snooze.",
                        "Alarm Clock",
                        MessageBoxButtons.YesNo,
                        MessageBoxIcon.Exclamation);
    player.Stop();
    if (replay != DialogResult.Yes)
        myAlarm.Snooze();
}

In VB:

Dim myAlarm As Alarm
Private Sub SetTheAlarm()
    ‘ Create an alarm object
    myAlarm = New Alarm(Now.AddMinutes(1), 1)
    AddHandler myAlarm.AlarmWentOff, AddressOf AlarmWentOff
End Sub

Private Sub AlarmWentOff(ByVal sender As Object, ByVal e As EventArgs)
    Dim player As New SoundPlayer("myFile.wav")
    player.PlayLooping()
    Dim replay As DialogResult = _
        MessageBox.Show("Wake up" & _
                             Environment.NewLine & _
                             "Yes to wake up." & _
                             Environment.NewLine & _
                             "No to snooze.", _
                        "Alarm Clock", _
                        MessageBoxButtons.YesNo, _
                        MessageBoxIcon.Exclamation)
    player.Stop()
    If replay <> DialogResult.Yes Then
        myAlarm.Snooze()
    End If
End Sub

This code defines a variable that references the Alarm class. In a SetTheAlarm method, the class creates an instance of the class, passing in an alarm time and snooze interval.

For testing, this is set to 1 minute from the current time and the snooze is set to one minute. In most cases, you would want to get the alarm time from the user.

When the alarm goes off, this code plays a .wav file using the SoundPlayer provided in .NET. Be sure to change the .wav file name to the directory and file name of a .wav file on your system.

The PlayLooping method of the SoundPlayer is used to play the sound continuously. This method is asynchronous, so the code will continue to the next line.

The example displays a message box, allowing the user to cancel the alarm or snooze the alarm. In either cause, the code calls the Stop method of the SoundPlayer to stop the .wav file. If the user requested to snooze, it calls the alarm’s Snooze method.

Enjoy!

Next Page »

© 2014 Deborah's Developer MindScape   Provided by WPMU DEV -The WordPress Experts   Hosted by Microsoft MVPs