The Abstract Factory Pattern

I’ve worked in a project where I implemented an API based on an international standard called SCORM (it stands for Shareable Content Object Reference Model). It was developed to be used by e-learning systems and courses. While implementing the API, I needed to model some classes for the data types supported by SCORM version 1.2, keeping in mind that they have some common attributes and specific validation methods. There are 15 different types, and all that classes (one for each type) in my diagram was bothering me.

Considering that all the classes derive from an abstract class named ScormObject, I’ve had the idea of using the Abstract Factory Pattern. By doing this, I was able to put all that related validation code together into one “factory” class, turning the old classes into static subclasses inside the factory. This new class, named ScormObjectFactory, has methods for creating all the 15 types.  I’ve started coding the class as below (note that in this project I’ve used Java):


/**
 * <p>Factory of ScormObjects, following the Abstract Factory pattern</p>
 *
 * @version 1.1
 */

public class ScormObjectFactory {

  private static final int CMIIDENTIFIER = 1;
  private static final int CMIBLANK = 2;
  private static final int CMISTRING255 = 4;
  private static final int CMISTRING4096 = 8;
  private static final int CMIINTEGER = 16;
  private static final int CMISINTEGER = 32;
  private static final int CMIDECIMAL = 64;
  private static final int CMITIME = 128;
  private static final int CMITIMESPAN = 256;
  private static final int CMIVOCABULARY = 512;
  private static final int CMISCORE = 1024;
  private static final int CMIAUDIO = 2048;
  private static final int CMISPEED = 4096;
  private static final int CMITEXT = 8192;
  private static final int CMIFEEDBACK = 16384;
}

Then, I’ve written a subclass for each one of the types. The code below is from the CMIIdentifier type implementation.


/**
  * <p>This class extends ScormObject representing the CMIIdentifier type,
  * and does the specific validation of this type.</p>
  *
  * @version 1.1
  */

private static class ScormObjectCMIIdentifier extends ScormObject {
  public ScormObjectCMIIdentifier() {
   super();
  }

 /**
   * <p>Checks if the info value is a valid CMIIdentifier.
   *
  * @return Returns true if the value is a valid CMIIdentifier.
   */

  public boolean validate(String info) {
    if( info.indexOf(” “) != -1 || info.length() > 255 || info.compareTo(”") == 0 )
      return false;
    else
      return true;
  }
  public int getDataType(){
    return CMIIDENTIFIER;
  }
}

Note that each type has its own implementation of the validatemethod. Finally, I create methods to turn the types public through the application code. See the example below for the CMIdentifier subclass.

public static ScormObjectCMIIdentifier createCMIIdentifier(){
  return new ScormObjectCMIIdentifier();
 }
 

Now, I can use the type anywhere in the code by calling the ScormObjectFactory.createCMIIdentifier method.

Comments (1)

The Singleton Pattern

As I already said, I like to study patterns that make common tasks easier. The Singleton pattern was the first that I got to know. It can be used when you need to ensure that some class has only one instance, providing a known method to give access to it.

I frequently use this pattern when I want to have a global configuration class in a project. This is a Config class example that I have used in one of the .NET projects I developed:

Now I can access this class from anywhere in the code by using Config.Instance(). When I call this reference for the first time, all the data will be loaded by the private constructor, called by the Instance() method, and in the subsequent calls the unique instance will always be returned.

Comments (1)

Design Patterns for .NET

Since my undergraduate course, I’ve always been interested in design patterns. In the university I used to study the GoF design patterns using Java, but since I’ve been working with Microsoft technology it would be good to have some examples using C# that don’t simply ‘translate’ the code examples originally written for Java. It would be great if someone consider finding some advantages of the C# language to use in the patterns implementation.

While googling a little bit I’ve found this site and bookmarked it forever. It has an example C# code implementation for each one of the GoF patterns and includes some .NET 2.0 optimized code (available for the Singleton pattern). The site additionally includes the UML diagram for each pattern, that helps me to remember about the patterns that I don’t use frequently and to rewrite the code examples to fit better in my needs.

Comments (1)

Finding references in Visual Studio – an annoying behavior

A good tool from Visual Studio 2005 is the “Find all references” in the context menu. However, it has a annoying behavior in a common situation within my project.

Suppose I have the A, B and C classes that implements the I interface, and that interface has declared a method named “save”. Now, I want to know where in my code the method C.save() is called, and usually I would right-click the method name in the method definition at the C class and use the “Find all references” tool. However, if I do this, the Visual Studio tool will find all the references of any “save()” method of the project, even of the A or B classes.

The best behavior of this tool would be finding only the references of the “save()” method called from instances of the C class.

Leave a Comment

A 3-tier model

While developing my custom issue management system I have made an effort to make a 3-tier model, and here it is:

  1. Persistence: database related code.
  2. Business: code related to the system’s business logic such as entity operations (Users, Issues, Projects, relationships and so on), transition control (things to do when the state of an issue changes), access control (login, logout).
  3. Interface: all code behind classes.

There are some project principles that I tried to follow in the model:

  • Keep cohesion in classes: each class should deal with only one subject.
  • One way communication between layers: the communication must occur only in a top-bottom way, assuming that the Interface is on top and the Persistence is on bottom. This means that Interface classes can use Business classes, but Business classes cannot use Interface classes. This is important because I can change the entire Interface layer without worrying about the Business and Persistence classes.

I’ve decided not to use stored procedures, but dynamic SQL instead. This decision made me think about where’s the best place to store the SQL statements: the persistence layer classes or the business classes?

My opinion is that the classes from the business layer are the best place, and this is all about “subject”. If I create a class to store the statements in the persistence layer I’ll have a BIG class with code related to the whole system, dealing with many different subjects. This is often seen as a bad property of a class, that ideally should deal with only one subject to keep it easily maintainable.

By keeping the SQL statements in the business layer I’ll put these codes in the related classes. For example, the UPDATE statement that updates an user record in the database will be placed in the save() method of the User class. By doing this, I’ll not make the User class deal with a new subject since the above SQL statement is all about users.

Comments (2)

Refactoring with Visual Studio 2005

I have started worrying about systems maintenance while working on my first BIG project, a virtual “classroom” for an e-learning solution. A great idea when dealing with this subject is to know more about refactoring, a technique that lets you change your code (with the purpose of getting it more simple or easier to understand) without changing its external behavior. The refactoring discipline has some common techniques that are well known like the “extract method”, that consists on identifying a source code snippet that is commonly used along the software and put it inside a new method.

The Visual Studio 2005 has the new “Refactor” feature, that help us implement some of the most used refactoring techniques. It is very simple to use: all you need to do is select the part of the code that you want to refactor and right-click and select the “refactor” submenu. This is shown below:

Refactor submenu

I think I don’t need to talk about renaming =) But this is very useful, much better than the old find-and-replace way.

You can use the extract method refactoring when you have a code snippet that is commonly used along the software code, resulting in duplicated logic. All you need to do is select the part of the code that represents this snippet and right-click selecting the Refactor >> Extract Method option. Then you define a name for the new method and click OK. You must take care about some issues:

  1. If the code snippet is used elsewhere, you will have to go there and change the code manually do use the new method.
  2. Visual Studio will pass the scope variables used by the code snipped automatically to the new method. So, it’s a good practice to be more careful with side effects dealing with these variables, specially if the method will be used somewhere else.

The encapsulate field option generates code for the get and set handlers of a given class field. This is useful, but would be better if the generated code was placed in a default #region snippet, resulting in a well organized code.

Look at the code below.

public class Car
{
   private int power;
   private string model;
   private string manufacturer;
}

If we right click at each field and select Refactor >> Encapsulate field, the result will be this:

public class Car
{
   private int power;

   public int Power
   {
      get { return power; }
      set { power = value; }
   }
   private string model;

   public string Model
   {
      get { return model; }
      set { model = value; }
   }
   private string manufacturer;

   public string Manufacturer
   {
      get { return manufacturer; }
      set { manufacturer = value; }
   }
}

However, the code does not look good… It would be better if the generated code looked something like this:

public class Car
{
   private int power;
   private string model;
   private string manufacturer;

   #region Field access methods
   public int Power
   {
      get { return power; }
      set { power = value; }
   }
   public string Model
   {
      get { return model; }
      set { model = value; }
   }
   public string Manufacturer
   {
      get { return manufacturer; }
      set { manufacturer = value; }
   }
   #endregionregion
}

I did not use the other options of the Refactor submenu, but as soon as I use them I’ll post something about.

Leave a Comment

Dot Net Hungry

A few weeks ago, I’ve started my first solo .net project. It’s a issue management system with workflow functionality for keeping track of issues regarding to some projects of an IT company. These are the main requirements:

  1. Must control issues by project and customer.
  2. The users from the customers can only see the issues related to themselves (they can’t see all the issues from the project).
  3. Transition control: the system must do some tasks when the issues state change in a flexible manner. Eg.: when some issue status change from <any> to closed, the system must send an e-mail notification to the customer or user that created it.
  4. All issue information must be filtered for customers: they can’t see technical related information (this is important only for the tech staff), even in the system or e-mail notifications.
  5. And something more that justity the development of a customized system and don’t adopting a popular issue management system like BugZilla! or Scarab (the company was using this system before the new one).

There are two main objectives with this project: the first, I always wanted to develop a project that uses workflow concepts, and the second, I was wating for a chance to increase my .NET knowledge.

So, let’s see what happens!

Comments (1)

The blog name

At this time I’ll not talk about development =)

I’m here only to thank Igor Ramadas for suggesting me a name for this blog.

Thanks!

Comments (2)