Feeds:
Posts
Comments

Archive for May, 2010


[tweetmeme source=”aabdulmoniem” only_single=false]

We have discussed in our previous post the decorator pattern’s role, and giving a very detailed illustration about it. Also, we have discussed its design varieties and clarified when to use each design and why.

Today, we will complete our discussion about decorator pattern. We will talk deeply about different examples from the real world cases to give you more deep understanding of this pattern. Also, we will discuss when to use this pattern in real world situations.

We will demonstrate first a simple example and then move on to a more complicated ones and more variations.

1 – Example: Use Case Diagram Tool

Use case diagram is one of the fundamental diagrams of the unified modeling language (UML).  We use the use case diagrams to describe all the use cases a user can interact with within an application.

Here, we will start to build a simple (Really, it is a very simple, just for demonstrations purposes) use case diagram tool.

If we look more thoughtfully into the available shapes that can be drawn in a use case diagram, we will find them to be 3 main shapes:

  1. Actors.
  2. Use cases.
  3. Arrows (which represent relationships between actors, or between use cases or between actors and use cases).

But a more deep look, we will find that each shape has a different look in a different situations.

As described in the following diagram, some of the variations that could be applied to any shape during drawing process of use case diagrams:

The challenge here that we want to build an application that covers all the variations available and with an ability to add more shapes in futures in case of any updates happens to UML.

Here comes the magic of the decorator pattern. Let’s get started:

Analyzing the last diagram shows us that we have 3 main shapes with different variations. Variations means here decorators which can be applied to different shapes to show us the right final shape.

More analyzing, we are noticing that we have some kind of hybrid decorators like for example, dotted line with a tag. In fact, they are two decorators tag decorator and dotted line decorator.

Let’s first start with one shape and then we will elaborate on this.

IShape interface and Actor class:

IShape Interface:

public interface IShape
{
     Bitmap Draw();
}

Actor Class:

public class Actor : IShape
{
     public Bitmap Draw()
     {
         Bitmap image = new Bitmap(200, 200);

         using (Graphics graphics = Graphics.FromImage(image))
         {
              using (Pen blackPen = new Pen(Brushes.Black))
              {
                   // Drawing head
                   graphics.DrawEllipse(blackPen, 100, 20, 20, 20);

                   // Drawing backbone
                   graphics.DrawLine(blackPen, 110, 40, 110, 80);

                   // Drawing arms
                   graphics.DrawLine(blackPen, 110, 55, 130, 55);
                   graphics.DrawLine(blackPen, 110, 55, 90, 55);

                  // Drawing legs
                  graphics.DrawLine(blackPen, 110, 80, 130, 100);
                  graphics.DrawLine(blackPen, 110, 80, 90, 100);
              }
         }

        return image;
    }
}

If we try now to use this class with a windows forms application in .NET for example you will write just like the following code after dragging a picture box into the form:

Actor actor = new Actor();
pictureBox1.Image = actor.Draw();

Run the project, you will see:

Now we need to add some sugar, so let’s add a decorator called TagDecorator which will be responsible for adding tags (titles) to any shape.

Here is the class diagram (following the guidelines of decorator patterns):

TagDecorator Class:

public class TagDecorator : IShape
{
     private IShape _shape;
     private string _tag;

     public TagDecorator(IShape shape, string tag)
     {
          _shape = shape;
          _tag = tag;
     }

     public Bitmap Draw()
     {
         // Getting the actor shape without tags
         Bitmap image = _shape.Draw();

         // Writing the tag under the actor shape
         using (Graphics grahpics = Graphics.FromImage(image))
         {
              grahpics.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias;
              StringFormat stringFormat = new StringFormat
              {
                   Alignment = StringAlignment.Center,
                   LineAlignment = StringAlignment.Center
              };
              grahpics.DrawString(_tag, new Font("Times New Roman", 12), Brushes.Black, new RectangleF(10, 110, 200, 20), stringFormat);
         }

         return image;
     }
}

Let’s try to draw this decorated actor to the form. So we will write this code:

Actor actor = new Actor();
TagDecorator actorTag = new TagDecorator(actor, "User");
pictureBox1.Image = actorTag.Draw();

And see the output:

Now let’s make things more complicated, I will just give you the concepts and let you try to implement them.

What if we want to add more shapes, simply we will use the following diagram:

What about more decorators?!

Go, and try to build you own diagramming tool.

2 – Real World Examples

Now we will demonstrate some real world examples may be we are using in a daily basis but we don’t know.

In a very good article by Rob Pierry, he discussed when a decorator pattern has been used within .NET. He Said:

“Any useful executable program involves either reading input, writing output, or both. Regardless of the source of the data being read or written, it can be treated abstractly as a sequence of bytes. .NET uses the System.IO.Stream class to represent this abstraction. Whether the data involves characters in a text file, TCP/IP network traffic, or something else entirely, chances are you will have access to it via a Stream. Since the class for working with file data (FileStream) and the class for working with network traffic (NetworkStream) both inherit from Stream, you can easily write code that processes the data independent of its origins. Here’s a method for printing out some bytes from a Stream to the console:

public static void PrintBytes(Stream s)
{
     int b;
     while((b = fs.ReadByte()) >= 0)
     {
         Console.Write(b + " ");
     }
}

Reading a single byte at a time is typically not the most efficient way to access a stream. For example, hard drives are capable of (and optimized for) reading continuous blocks of data from the disk in a big chunk. If you know you are going to be reading several characters, it is better to read a chunk from the disk all at once and then consume the chunk from memory byte by byte. The Framework includes the BufferedStream class for doing just that. The constructor for BufferedStream takes as the parameter whatever stream you would like buffered access to. BufferedStream overrides the main methods of Stream, such as Read and Write, to provide more functionality. Since it is still a child class of Stream, you can use it the same as any other Stream (note that FileStream includes its own buffering capabilities). Similarly, you can use System.Security.Cryptography.CryptoStream to encrypt and decrypt Streams on the fly, without the rest of the application needing to know anything more than the fact that it is a Stream.

This ability to dynamically attach new functionality to objects transparently using composition is an example of the Decorator pattern”.

This is valid also for Java developers as well as far as I know in java.io namespace.

Let’s also demonstrate a more general real examples:

Here are four ways the Decorator pattern is used in the real world (Excerpt from C# 3.0 Design patterns):

  • As our small example illustrated, the Decorator pattern fits well in the graphics world. It is equally at home with video and sound; for instance, video streaming can be compressed at different rates, and sound can be input to a simultaneous translation service.
  • At a more mundane level, decorators abound in the I/O APIs of C# as illustrated.
  • In today’s world of mobile devices, web browsers and other mobile applications thrive on the Decorator pattern. They can create display objects suitable for smaller screens that include scroll bars and exclude banners that would be standard on desktop display browsers, for example.
  • The Decorator pattern is so useful that there are now actual Decorator classes in .NET 3.0. The one in System.Windows.Controls “provides a base class for elements that apply effects onto or around a single child element, such as Border or Viewbox.”

3 – When to use?

When you have:

  • An existing component class that may be unavailable for subclassing.

Or When you want to:

  • Attach additional state or behavior to an object dynamically.
  • Make changes to some objects in a class without affecting others.
  • Avoid subclassing because too many classes could result.

4 – Finally

At last, we have finished demonstrating this pattern. Our next one is Proxy pattern. So, be with us 🙂

Advertisements

Read Full Post »


[tweetmeme  source=”aabdulmoniem” only_single=false]

Hello! Back again, it has been a while from our last review on this great book, Software Estimation.

We have already reviewed the first part of the book which discusses the critical concepts about software estimation.

Now, we are moving on to another stage. This book now turns to a discussion of detailed estimation techniques that can be applied to specific estimation problems.

This chapter is just an introduction to lay out the ground for the upcoming chapters which will discuss specific techniques.

What I have learned?

  • There are many considerations you have to take into account before choosing the right estimation technique to your specific problems.
  1. What is being estimated?
    • Do you have features, and you want to  estimate schedule and effort?
    • Do you have budget and development time frame, and you want to estimate how many features can be delivered?
    • In this book, estimating size refers to estimating the scope of technical work of a given feature set—in units such as lines of code, function points, stories, or some other measure. Estimating features refers to estimating how many features can be delivered within schedule and budget constraints. These terms are not industry standards; I’m defining them here for the sake of clarity.
  2. Project Size
    • Small: <= 5  total technical staff. Best estimation techniques is “bottom -up” techniques based on estimates made by individuals who will do the job.
    • Large: >= 25 people lasts for 6 to 12 months or more. Best estimation techniques are in the early stages, the best estimation approaches tend to be “top-down” techniques based on algorithms and statistics. In the middle stages, a combination of top-down and bottom-up techniques based on the project’s own historical data will produce the most accurate estimates. In the later stages of large projects, bottom-up techniques will provide the most accurate estimates.
    • Medium: 5 to 25 people and last 3 to 12 months. They have the advantage of being able to use virtually all the estimation techniques that large projects can use and several of the small-project techniques, too.
  3. Software Development Style
    • For purposes of estimation, the two major development styles are sequential and iterative. Industry terminology surrounding iterative, Agile, and sequential projects can be confusing. For this book’s purposes, the primary difference between these kinds of projects is the percentage of requirements they define early in the project compared to the percentage they define after construction is underway.
    • Evolutionary prototyping: Iterative.
    • Extreme Programming: highly iterative.
    • Evolutionary delivery: normally practiced as iterative.
    • Staged delivery: Sequential.
    • Rational Unified Process (RUP): Sequential.
    • Scrum: Iterative from multi-sprint point of view.
  4. Development Stage
    • Early: On sequential projects, the early stage will be the period from the beginning of the project concept until requirements have been mostly defined. On iterative projects, early refers to the initial planning period.
    • Middle: It is the time between initial planning and early construction.
    • Late: Refers to the time from mid-construction through release.
  5. Accuracy Possible
    • The accuracy of a technique is a function partly of the technique, partly of whether the technique is being applied to a suitable estimation problem, and partly of when in the project the technique is applied.

      Some estimation techniques produce high accuracy but at high cost. Others produce lower accuracy, but at lower cost. Normally you’ll want to use the most accurate techniques available, but depending on the stage of the project and how much accuracy is possible at that point in the Cone of Uncertainty, a low-cost, low-accuracy approach can be appropriate.

  • Most of the remaining chapters in this book begin with tables that describe the applicability of techniques in the chapter. Here’s an example:
Applicability of Techniques in this Chapter—SAMPLE
Group Reviews Calibration with Project-Specific Data
What’s Estimated Size, Effort, Schedule, Features Size, Effort, Schedule, Features
Size of project – M L S M L
Development Stage Early—Middle Middle—Late
Iterative or Sequential Both Both
Accuracy Possible Medium—High High

Read Full Post »


[tweetmeme source=”aabdulmoniem” only_single=false]

Another new feature in C# 4.0 is covariance and contravariance. Really, I will let you in this post with those two nice videos which explains well what is this new feature. This video is made by Eric Lippert divided into two parts. Enjoy!

How Do I: Use Covariance and Contravariance in VS 2010 Part I?

How Do I: Use Covariance and Contravariance in VS 2010 Part II?

I really do like the new feature because it didn’t break the main theme of C# that is strongly typed language.

Also, I like the semantics behind the in and out keywords when used in this new feature.

Finally, I don’t have to cast each element in IEnumerable sequence coming from LINQ to return a sequence of some related class, it will be done for me at compile time out of the box! Great!

Read Full Post »


[tweetmeme  source=”aabdulmoniem” only_single=false]

I have just finished a Manning Book titled “jQuery in Action”. I am here just to share my opinion with you about this book.

Really, it gives me a good starting point in jQuery commands and utility functions. Also, it demonstrated many practical examples to test the core API of jQuery. So, I think it is a good start for beginners who need to know what is the jQuery?!

Also, it gives me a very high level of the plugin capability in jQuery and introduced me with some famous plugins like forms plugin, UI plugin,  Live query plugin, and dimension plugin.

But IMHO, I think it is just suitable to give you highlights about the core API of jQuery and it doesn’t stand as a jQuery reference at all. So, if you  are expecting when you read this book to be a jQuery guru then you are wrong.

Also, I have missed practical examples on the interaction of jQuery with ASP.NET and how we can use them efficiently together. The book didn’t mention ASP.NET altogether because it is focusing on the core API.

So, it is a very basic jQuery book in my opinion suitable to learn how to write jQuery scripts and some basic concepts to give you a starting point to read more advanced materials.

Read Full Post »


[tweetmeme  source=”aabdulmoniem” only_single=false]

The VS 2010 debugger has a some great new capabilities like Intellitrace (historical debugging), the new parallel/multithreaded debugging capabilities, and dump debugging support.

For now we will demonstrate some new tiny usability improvements in VS debugger.

1 – Break Points Labels

Suppose that we have a windows application with one form and two buttons on it. We have also two click event handlers and a constructor. Then we added three break points one in the constructor and one in each click handler.

Open the break points window from Debug -> Windows -> Breakpoints. You will see the following:

As we can see, we can’t distinguish these three break points from each other by just looking into the break points window. VS 2010 comes with a new capability “Breakpoints Labels” which allows you to attach label/labels to each break point. See the following steps:

1) Right-click on any breakpoint

1) Right-click on any break point

2) Add label

2) Add label

3) See the new labels attached to the breakpoints

3) See the new labels attached to the break points

Filtering and Searching by labels:

Enable/Disable break points by label:

This gives you an advantage to disable some break points you don’t want to break while debugging which share some common label (behavior, position … etc).

2 – Import / Export break points

This capability allows you to import/export break points to XML files to share them with another team member or to attach them in a bug work item in TFS for example.

3 – Pinned Data Tips

Using this feature, VS 2010 allows you to better track values while you are in debugging session or even you are not.

I will just enter a debugging session, and just hover over any variable I want to track.

You can pin this value for later tracking, also you can add some comments, and for sure you can un-pin it at any time:

We can also Import / Export these data tips as the breakpoint for later share:

One great feature, is that you have the ability to see what is the last value of a specific variable in the last debugging session even if you are not in a debugging session! WOW! Close the debugging session, and look at the screen shot:

That’s it. I think that VS has added some very great capabilities to its powerful debugger. Happy debugging!

Read Full Post »


[tweetmeme source=”aabdulmoniem” only_single=false]

Old versions of VS like 2008 was really painful when trying to navigate from an interface method to its implementation. Now, as we have seen a lot of improvements in navigability in VS 2010, we have been introduced with a very cool new window called: “Call Hierarchy”.

Only you have to right-click on any name you want to trace its call hierarchy and click on “View Call Hierarchy” like the following screen shot:

VS 2010 will handle the rest. It will open a new dockable window for you titled: “Call Hierarchy”

Lets examine some features of this window:

1 – Calls to and Calls from:

As you can see, you can investigate all the called paths from the chosen method or all the called paths to the chosen method.

2 – Call sites

You can click on any call path from the left side of the window to see all the call sites on the right window plus you can navigate to the chosen call site if you want by double clicking on any call site.

3 – Navigate to the call from or call to paths:

You can also navigate to the call path by clicking any code path from the left window.

4 – Filtering call hierarchy:

You can filter the call hierarchy by solution, project and document as shown in the following screen shot:

Now, let’s see more complex scenarios when trying to navigate for virtual or interface methods.

Suppose that we have a class Employee and Manager both are implementing an interface IHuman and inheriting from a class Person. Let’s see these four types:

Person class:

public class Person
{
     public string Title { get; set; }
     public string FirstName { get; set; }
     public string LastName { get; set; }

     public string FullName
     {
         get
         {
             return Title + " " + FirstName + " " + LastName;
         }
     }

     public Person()
     {
     }

     public Person(string title, string firstName, string lastName)
     {
          Title = title;
          FirstName = firstName;
          LastName = lastName;
     }

     public virtual void PrintInformation()
     {
          Console.WriteLine(FullName);
     }
}

IHuman interface:

public interface IHuman
{
     void Talk(string talking);
     void Eat(string food);
}

Employee class:

public class Employee : Person, IHuman
{
     public string Salary { get; set; }

     #region IHuman Members

      public void Talk(string talking)
      {
           Console.WriteLine("I am saying: " + talking);
      }

      public void Eat(string food)
      {
           Console.WriteLine("I am eating: " + food);
      }

      #endregion

      public override void PrintInformation()
      {
           base.PrintInformation();
           Console.WriteLine(Salary);
      }
}

And Manager class:

public class Manager : Person, IHuman
{
     public string DepartmentName { get; set; }

     #region IHuman Members

     public void Talk(string talking)
     {
          Console.WriteLine("I am saying: " + talking);
     }

     public void Eat(string food)
     {
         Console.WriteLine("I am eating: " + food);
     }

     #endregion

     public override void PrintInformation()
     {
          base.PrintInformation();
          Console.WriteLine(DepartmentName);
     }
}

As you can see that Employee and Manager classes override the PrintInformation method which is a Person virtual method. Also, they implement the two methods Talk and Eat of IHuman interface.

Now let’s play with the call hierarchy feature from the Person class. Right-click on the PrintInformation method in the Person class and choose the “View Call Hierarchy” menu item. See the next screen shot:

As you can see, we can navigate to all the overrides from this window very easily and forgetting about the hassle of Find or Find All References!

Let’s switch to the IHuman interface and see what is the call hierarchy of the Talk method:

Really, pretty neat!

Read Full Post »


[tweetmeme source=”aabdulmoniem” only_single=false]

Continuing talking about searching and navigation improvements in VS as we did before. Another improved and a very good feature is the “Navigate To” dialog box to navigate through code in our solution.

All you have to do is to use the key combination (CTRL + ,) to open this new dialog. See the following screen shot:

You can use the search text box to write one of the following:

  1. Any part of any name you want to search about.
  2. Pascal case of any name you want to search about like (CP) will give you any result has two words separated by Pascal convention like (ChangePassoword) or (ChangeCurrentPassword) or (CCP) will return you (ChangeCurrentPassword) only.
  3. Type two or more words separated by space to indicate that you want any type has all these words.

By selecting any search result automatically VS will take you to the code file containing this search result.

Pretty good!

Read Full Post »

Older Posts »

%d bloggers like this: