Core concepts in object-oriented programming: What does cookie dough have to do with C#?

Classes are the cookie cutters of OOP. Objects are the cookies.

Classes are the cookie cutters of OOP. Objects are the cookies.

Last time, I highlighted a specific feature of C#. Thanks to everyone who checked it out and kept the conversation going!

This time, I’m discussing general – but core – concepts in Object Oriented Programming (“OOP”). Candidly, our professor, Cecil Phillip assigned the topic. But I’m also responding to feedback from readers who aren’t working in C# yet. So for all of these reasons, let’s step back and take more of a birds-eye view of C#.

Doing things in an object-oriented manner is a way of thinking. And C# is an object-oriented language.

So, while I will illustrate with code examples, my focus will be on the following core concepts:
1) classes; 2) objects; 3) inheritance; and 4) polymorphism.

 

The terms class and object are sometimes used interchangeably. But classes describe the type of objects. And objects are usable instances of classes.

Think of classes like cookie cutters. Objects are like the cookies we cut out with those cookie cutters.

Or think of classes like blueprints. Objects are like the buildings we build from those blueprints.

Takeaway: classes are the templates from which we create objects.

 

Each class can have different class members that include properties that describe class data, methods that define class behavior, and events that provide communication between different classes and objects.

Fields and properties represent information that an object contains. Fields are like variables because they can be read or set directly. A method is an action that an object can perform. A class can have several implementations, or overloads, of the same method that differ in the number of parameters or parameter types. Note: in most cases you declare a method within a class definition. But C# also allows you to add methods to an existing class outside the actual definition of the class.

To create an object, you need to instantiate a class – or create a class instance. After instantiating a class, you can assign values to the instance’s properties and fields and you can invoke class methods.

Inheritance describes the ability to create new classes based on an existing class. Inheritance enables you to create a new class that reuses, extends, and modifies the behavior that is defined in another class. The class whose members are inherited is called the base class, and the class that inherits those members is called the derived class. Notably, all classes in C# implicitly inherit from the Object class, which supports .NET class hierarchy and provides a lot of built-in functionality for all classes.

    // instantiates a class called DrawingObject
    public class DrawingObject
    {
        // implements DrawingObject, with a single method
        // note: the modifier "virtual" indicates to derived 
            // classes that they can override this method        
        public virtual void Draw()
        {

            Console.WriteLine("I'm a generic drawing object.");
        }
    }

    // instantiates a derived class, Line, which inherits 
        // from the base class, DrawingObject
    public class Line : DrawingObject
    {
        // note: the modifier "override" allows a method to 
            // override the virtual method of its base class
        public override void Draw()
        {
            Console.WriteLine("I'm a Line.");
        }
    }

    // instantiates a derived class, Circle, which inherits
        // from the base class, DrawingObject
    public class Circle : DrawingObject
    {
        public override void Draw()
        {
            Console.WriteLine("I'm a Circle.");
        }
    }

    // instantiates a derived class, Square, which inherits 
        // from the base class, DrawingObject
    public class Square : DrawingObject
    {
        public override void Draw()
        {
            Console.WriteLine("I'm a Square.");
        }
    }

Polymorphism – from Greek πολύς, polys, “many, much” and μορφή, morphē, “form, shape” – means many shapes. More specifically, it means that you can have multiple classes that can be used interchangeably, even though each class implements the same properties or methods in different ways.

Continuing with our example, we see polymorphism illustrated by each derived class – Line, Circle, and Square – responding differently to the same “Draw()” method even though each inherits from the same base class, DrawObject.

    public class DrawDemo
    {
        static void Main(string[] args)
        {
            //creates an array to hold four objects of type 
                // DrawingObject.
            DrawingObject[] dObj = new DrawingObject[4];

            // initializes objects in array
            dObj[0] = new Line();
            dObj[1] = new Circle();
            dObj[2] = new Square();
            dObj[3] = new DrawingObject();

            // enumerate through each element in the array, 
                // invoking the Draw() method
            foreach (DrawingObject drawObj in dObj)
            {
                drawObj.Draw();
            }

            // Output:

            // I'm a Line.
            // I'm a Circle.
            // I'm a Square.
            // I'm a generic drawing object.

            Console.ReadLine();
        }
    }

Thanks for reading. I’m grateful for your feedback. And if we haven’t yet, let’s connect!

Now to make some real and metaphorical cookies…

Advertisements

Async and await in C# 5.0: purpose, practical considerations, and links for further reading

At the CS50x Miami Hackathon: answering TF Ricardo’s question about concatenation!

When async was first unveiled, Microsoft’s Eric Lippert explained (video @ 3:32-6:36) why async is such an exciting feature: it is cooperative multi-tasking via code routines implemented using continuation passing style.

Don’t worry – that’s just the teaser. I’m going to break it down into smaller pieces: 1) what problem is it trying to solve; 2) how is it trying to solve this problem; and 3) what issues or resources might you also want to consider.

What problem is it trying to solve?

Latency. Performance bottlenecks. We want to solve a problem, but because of processor cycles we might be waiting for the solution to come back. Sometimes, the laws of physics – e.g. signal travel – cause the latency. Other times, the latency is caused by our problem’s need for so many calculations because it takes a while for a solution to come back.

Before async, people split work into chunks to make efficient use of processors. Put differently, they ran other code that didn’t depend on the result they were awaiting. But as you can imagine, this made code hard to understand, debug, and maintain.

How is it trying to solve this problem?

Async allows you to structure your code in a logical order resembling synchronous code. You annotate your code with the keyword await. That keyword signals that a high latency operation may occur there. Then the compiler takes care of splitting your code into chunks for you. And Windows Runtime takes care of scheduling them all appropriately. Thus, async leverages the asynchronous support in the .NET Framework and the Windows Runtime. And as a result, you get all the advantages of asynchronous programming with a fraction of the effort.

Here is an example of how the code may be used:
MSDN source

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

// Add a using directive and a reference for System.Net.Http; 
using System.Net.Http;

namespace AsyncFirstExample
{
    public partial class MainWindow : Window
    {
        // Mark the event handler with async so you can use await in it. 
        private async void StartButton_Click(object sender, RoutedEventArgs e)
        {
            // Call and await separately. 
            //Task<int> getLengthTask = AccessTheWebAsync(); 
            //// You can do independent work here. 
            //int contentLength = await getLengthTask; 

            int contentLength = await AccessTheWebAsync();

            resultsTextBox.Text +=
                String.Format("\r\nLength of the downloaded string: {0}.\r\n", contentLength);
        }


        // Three things to note in the signature: 
        //  - The method has an async modifier.  
        //  - The return type is Task or Task<T>. (See "Return Types" section.)
        //    Here, it is Task<int> because the return statement returns an integer. 
        //  - The method name ends in "Async."
        async Task<int> AccessTheWebAsync()
        { 
            // You need to add a reference to System.Net.Http to declare client.
            HttpClient client = new HttpClient();

            // GetStringAsync returns a Task<string>. That means that when you await the 
            // task you'll get a string (urlContents).
            Task<string> getStringTask = client.GetStringAsync("http://msdn.microsoft.com");

            // You can do work here that doesn't rely on the string from GetStringAsync.
            DoIndependentWork();

            // The await operator suspends AccessTheWebAsync. 
            //  - AccessTheWebAsync can't continue until getStringTask is complete. 
            //  - Meanwhile, control returns to the caller of AccessTheWebAsync. 
            //  - Control resumes here when getStringTask is complete.  
            //  - The await operator then retrieves the string result from getStringTask. 
            string urlContents = await getStringTask;

            // The return statement specifies an integer result. 
            // Any methods that are awaiting AccessTheWebAsync retrieve the length value. 
            return urlContents.Length;
        }


        void DoIndependentWork()
        {
            resultsTextBox.Text += "Working . . . . . . .\r\n";
        }
    }
}

// Sample Output: 

// Working . . . . . . . 

// Length of the downloaded string: 41564.

 

What issues or resources might you also want to consider?

As you would expect, many in the developer community have discussed async online since it was introduced. And there are many resources you can locate to help you determine whether and when to use it. To that end, I’ve included links above and include a few more below:

I am loving learning about C#, hope that you took something from this, and would be grateful if you would follow my blog and share in this journey with me up The Coding Ladder!

Hello world!

Why, hello world! This is WordPress’s default title for a first post. How fitting. As I learn each new language, printing “hello world!” is always the first task. So I’m keeping this fitting title for my first blog post on The Coding Ladder.

Why name this blog The Coding Ladder? The answer is simple. Coding gives people a ladder of opportunity. I’m grateful to have been part of the 2nd cohort of CS50x Miami. While I may be new to coding, I want to connect with others who love it, grow my skills by teaching about it, and inspire others to love it too.

In “About,” I tell a bit about me and how I came to write this blog.

I hope you’ll check it out, comment, and connect.