It’s about programming

November 2, 2008

Strategy Pattern

Filed under: Software Design and Documenting — Lakmal @ 1:09 pm

Strategy Pattern (also known as the policy pattern), Simple and useful, it’s a very simple pattern I went through. Even though it’s simple it is gaining great weight to best coding practices.

Official Definition

“Define Family of Algorithms, encapsulate each one, and make them interchangeable. Strategy let’s algorithm vary independently from client that use it”.

Why we need pattern like this

If you see how horrible lengthy if else statements or switch statements, that is one of the reason where strategy pattern come to the screen. Normally a program is such a sequence of Logical Operations; here operation itself might be simple algorithm. In Object Oriented Programming, we have classes and inside a class we are having methods where we writing particular sequence of operations to achieve some business aspect. In business flow, to take the decisions to getting invoke some operations in execution sequence, are doing at run time according current state. So there you need If-else statements or switch statement to manage that.

Every programmer should dream to write their code as a story, Code reviewers would love to give best comments on that definitely.

This is such simple story which might love to read by especially maintenance people, they won’t be having any harm to understand this. Business process too explaining in method itself, no one need to go back and see use cases and all when maintenance are doing on the code. In Such a business workflow, we might be having more than this if-else statements or lengthy switch statement. Yes, suppose we wrote the logic as nice readable story, but still it’s having too many lengthy logical statements.

Here is Context class where actually Calculation business aspect implementations is been used.

While having such switch statements in the business logic implementations, you are taking risk of frequently changing when new business aspect is asked to be added to the flow. Suppose in this case, someone is asking to added another Calculation Operation into the business logic and then you need to do two things primarily

  1. Add new Item into the enum
  2. Add new case
    statement into the switch statement

With this example it seems no any harm to do that, but when business scenarios getting large, you might be having bit complex business flows. Same thing can occur in lengthy if-else statements too. This is the place where Strategy Pattern comes to the screen. Basically it will allow you to add new business aspect to the business workflow or change existing business aspect in flow, without touching existing business workflow. With that you won’t need to add new item to emun and add new case statement to the switch.

Strategy Pattern

If you have written the business logic as a good readable story which itself explain the Algorithm associated with it clearly, and then it is the time to think about Strategy Pattern to enhance code design to support future changes. Identify the Algorithm is extremely vital with this pattern and extract Algorithm signature into an Interface is the second step. Then Client will only couple with Algorithm Interface and burry implementation details into derived classes. Then Client won’t be having any harm on adding new derived classes to extend the business and or change derived classes on requirement changes. Here is the check list you might help to identify and do stuff.

  1. Identify an Algorithm that client need to access.
  2. Code signature for that algorithm in an Interface.
  3. Burry alternative implementation details in derived classes.
  4. Clients of the algorithm couple themselves to the Interface

Calculation Interface

Just interface Operation need to be done to achieve particular business aspect. Particular calculation should implement ICalculation interface and implement Calculate Method

By implementing ICalculation Interface, implicitly we implement calculate method and it’s subject to that particular Calculation. Here it’s Add two values and return result back. Then Calculation class would look like this with new method

And Context class (Calculation User class) is going to be like this

Implementation is looking great after new method than earlier. But advantage is not only that, suppose you need to Use another Calculation in the context. Then

  1. You don’t need to touch Calculation Business workflow implementations. It means don’t need to changes Calculation class or ICalculation Interface.
  2. Just need add another Calculation Operation class like “Modulation” while implementing it ICalculation interface.
  3. In the “UseCalculation” Method, you can use instance of newly created class to achieve new Calculation Operation in existing system without changing main business workflow.

Found good Diagrams explaining concept well

Here we can remind one another such important concepts in design pattern like “Program to interface and not to an implementation” and “Open for extension and close for modification”. Implicitly it has been followed by us on this. Here we concern only business logic implementation and not on Context implementation where Business Logics are been used. Our main concern should be on securing business logic from ambiguous implementations.

Conclusion

Strategy Pattern might have been followed by us without knowing even it’s the Strategy Pattern. This posting was about mentioning things bit clearly.

Resources

Head First Design Patterns

http://en.wikipedia.org/wiki/Strategy_pattern

http://jeremyjarrell.com/archive/2007/10/28/64.aspx

http://www.dofactory.com/Patterns/PatternStrategy.aspX

http://www.developer.com/tech/article.php/3683091

http://davidhayden.com/blog/dave/archive/2005/07/01/1875.aspx

http://www.primaryobjects.com/CMS/Article70.aspx

http://blog.cumps.be/design-patterns-strategy-pattern/

http://sourcemaking.com/design_patterns/strategy

 

Regards

Lakmal Kankanamge

 

October 12, 2008

Encapsulate what varies from what stay same……

Filed under: Software Design and Documenting — Lakmal @ 9:16 am

Encapsulating is all about how you arrange you implementations throughout classes and methods in a particular system implementation. And further on this, It’ about

  • How you arrange your class structure
  • Deciding your class structure and which responsibilities are going to assign each other class
  • How you control access to each and every classes, methods, properties and variables
  • And etc..

Design Principle

“Identify the aspect of your application that vary and separate then from what stays same.”

It’s like this, suppose some aspect of you application is changing with new requirements, then it’s obvious you got behavior that need be pulled out and separated from all the stuff that doesn’t change. Other way round it’s like, take parts that vary and encapsulate them, so that later you can extend or alter the parts that vary without affecting that don’t.

Almost all the Design patterns are coming save this concept. All patterns provide a way to let “some part of a system vary independently of all other parts”.

 

.NET Generics Advancing Factory Method Pattern

Filed under: Software Design and Documenting — Lakmal @ 6:20 am

Factory, the word itself says you can make something which is belonging to particular sort. The responsibility of Factory is to produce products without warring about materials it needs to produce products. But the important thing is, factory might need not only to produce same product all the time, instead it might be responsible for produce products which are belonging to particular purpose, group and etc. The key thing is having relationship between them.

Recently we used Factory Method pattern with our development and this about sharing how we came to decision to use it and more.

Our Application, it’s calling Absence Module and it is simply about viewing, modifying, adding and saving Absence Records. Absence record is like two time records (it is having start time and end time). In addition to that it is having more than those properties and now it’s not time to talk about them.

Above mentioned Absence Records are viewing in Five Different views called Day, Week, Month, Year and Detail. And the most important things related with them are

  • They are using Same Absence Record list to view
  • All views are sharing same WebSchedularInfo (this is type of class which exist in Infragestics .NET UI component class library’s Outlook components) in web application and CalenderInfo object in Win app.

All views are depends on mentioned two properties. This is the Interface; we were using to create views

Here we have been using Two Generics types which are respectively for WebSchedularInfo/CalenderInfo and UserControl/Control. The purpose of this is to support this interface for both win and web implementations.

Same type of implementation class is having in Win application too.

Initialize factory to provide Absence Views

Step 1

Step 2

From now onwards _viewprovider will provide views which are well-matched in web environment.

Even though this is just simple use of Factory Method pattern, it has been used power of Generics to extend scope to be covered in implementation level.

Regards

Lakmal Kankanamge

October 11, 2008

.NET Generics extends OOP

Filed under: Software Design and Documenting — Lakmal @ 8:43 am

Inheritance and Runtime Type binding

OOP it’s a well known programming technique, all most all the Programming languages have released their OOP version. Inheritance, Polymorphism, Encapsulation and abstraction are building blocks of it.

Inheritance – Apart from reuse of common behavior and attributes, it’s partially support runtime type dynamic type binding too.

Let me explain it’s like this….

Suppose you have Class called “Vehicle” (As UsuallyJ).



In addition to that there are two classes and which are sub classes of “Vehicle” class




Here is the “VehicleUser” class



Vehicle type refernce veriable is getting assined a value according the User need. It’s a run time decision and it means object of Which class is going to be assigned to variable v, is decided in run time.

.NET Generics

Generics, the word itself give meaning like below in real workd

It simply means something that is not tied to any sort of brand name”

.NET support templates called Generic, define a method or class with one or more methods, specifying the data type as a replaceable element. By convention we used T As generic Type Notation and when the method or class is used, need to indicate Generic type T and compiler will use that information for generate a new, unique method or class on that type. In .NET framework, you can see Generic Collections.

List<int32> int32Collection = new List<in32>();

List<string> stringCollection = new List<String>();

List<Car> carCollection = new List<Car>();

Use generics……



With one class or method implementation, we can have more than one Generic types like this….



Conclusion

With two concepts mentioned, what I was trying to make some similarities between them, is runtime Type binding. With first example (Vehicle Example), vehicle object can be assigned into the object of one its sub class. But with generic, you don’t need to worry about the Type you are going to work as Generic Type. Still what I can see is generic is extending the OOP usage and it’s making wide OOP.

Regards

Lakmal Kankanamge.


October 9, 2008

Installshield Setup Silent Installation

Filed under: Installshield — Lakmal @ 9:30 am

First time got to work with Installshield is two years ago. It’s Installshield 8 and now they have released Installshield 11 too. It was bit complex subject when I started to work with this. Especially with custom operations. We needed to do custom Operations like Update files, Copy files, hide some features according the license you provide, prompt user to enter some installation info and etc, and in the mean time of Setup is been getting installed.

There were two options I especially concerned on this

  • Write Custom Action – Custom Action can be Installshield Script Function, EXE or DLL. You can achieve your required operation through the one of these and make place for that custom action Execution Sequence.
  • Capture Installation event and handle it to do required operation. This implementation is doing in Installshield Script.

Latest thing I was trying to discover is how we can do Silent Installation with Installshield Setup. Here it is the step I followed to achieve Silent Installation.

 

  1. Create Response file.

Setup.exe -a /r /f1″C:\Program Files\MyInstallation\mysetup.iss”

 

Use above mentioned command to execute you setup.exe with stated arguments. Afterwards it will prompt Setup wizard dialog, then you need to follow the steps to install setup successfully. Those steps will be written to “mysetup.iss” file located in “C:\Program Files\MyInstallation” folder. After followed steps successfully, you will be having Response file to be followed up in Silent installation.

 

Response file content would be like this

 


  1. Run Silent Installation

    This is the step you run the silent installation.

    Setup.exe -s -a /s /f1″C:\Program Files\MyInstallation\mysetup.iss”

    This will install setup.exe according to the Response file.

     

In our case I needed to programmatically edit this response file (mysetup.iss) to achieve some customization. For an example we replaced “C:\Program Files\Tempus” with the user selected Installation directory.

 

Regards

Lakmal

October 7, 2008

AJAX says “Hello World”

Filed under: .NET,Web Development — Lakmal @ 2:34 pm

AJAX is an new technique and not an new programming language. Basically it is using XMLHttpRequest Object to deal web server.

XMLHttpRequest

XMLHttpRequest is a JavaScript object that was created by Microsoft and adopted by Mozilla. You can use it to easily retrieve data via HTTP. Despite its name, it can be used for more than just XML documents.

First step of Implementing Simple AJAX application is to initiate XMlHttpRequest Object. Different Browsers are supporting deferent scenarios to create XMLHttpRequest Object. In internet Explore it’s using ActiveXObject while other browsers used built in JavaScript Object called “XMLHttpRequest”

This code snippet is fixed for all AJAX implementation and it will provide XMLHttpRequest object.

And the second step is to initiating “onreadystatechange” property of XMLHttpRequest object. It’s about how you handle response from the server for the Request which we are sending through XMLHttpRequest object.

This property is simply function pointer and it should be assign Function which we handle Server Response.

In the mean time of Server Request processing, XMLHttpRequest object will having five different states. And those are explaining object current Request processing state.

0 The request is not initialized
1 The request has been set up
2 The request has been sent
3 The request is in process
4 The request is complete

And state 4 is the request processing complete state and that why I have checked it within the function. If state is 4, response text is written to HTML document controller property.

And the third step is to open request object and send to the server.

“open” method accept three argument and those are accordingly Request Sending Method, URL of server side script and third one is whether request is going to process Asynchronously.

In addition to this we need to write server side script to say “Hello World” to the Response of Client Request.

In my case it’s an ASP.NET back end and it doesn’t matter which language you used in server side implementation. What you need to do is just write “Hello World” to Server response back to Client browser.

Hey, I’m happy I got the right response without much effort.

Regards

Lakmal

September 28, 2008

AJAX, It is been changing the Web Experience

Filed under: Web Development — Lakmal @ 12:01 pm

Even though the key point of saving our precious time is learning things rapidly and unmistakably, last few weeks was not quit successful on subject of ascertaining something new. But the good thing is I experienced new era of web applications. Simply it means I went though few AJAX driven web sites (Especially www.facebook.com ) and enjoyed their performance, especially in server request processing. It’s obvious thing that users hate to make new server request because of the time it might take to deliver processed request back to the browser. I was been experiencing that from the date where I made my first web request.

Now it has come time to change your mind and get rid of fake fear of making new web request. AJAX made the change. There are few competitors for AJAX.

Adobe Flex

Adobe Flex is a collection of technologies released by Adobe Systems for the development and deployment of cross platform Rich Internet Applications based on the proprietary Adobe Flash platform. A component based tool that you can use to develop apps that run using the Flash Player or Adobe Air. Adobe Flex Builder™ software is an Eclipse™ based IDE for developing Rich Internet Applications.

JavaFX

JavaFX is a highly productive scripting language that enables content developers to create rich media and content for deployment on Java environments. JavaFX is a declarative, statically typed programming language. It has first-class functions, declarative syntax, list-comprehensions, and incremental dependency-based evaluation. It can make direct calls to Java APIs that are on the platform. Since JavaFX is statically typed, it has the same code structuring, reuse, and encapsulation features such as packages, classes, inheritance, and separate compilation and deployment units, that make it possible to create and maintain very large programs using Java technology. Using the JavaFX language it is possible to create GUI using swing GUI components. This document gives a description of the JavaFX programming language.

Silverlight

Silverlight is a browser plug-in that that extends the web development experience far beyond the limitations of plain HTML and JavaScript. Being a Microsoft product, you might expect it to work best (or only) on Windows and Internet Explorer. So you may be pleasantly surprised to know that it works equally well on Windows and on the Mac, and it also works equally well on the Firefox and Safari web browsers. Since Silverlight is a client side technology, it doesn’t matter what backend server software or platform you’re running – even Apache/Linux will do just fine.

Java Applet

Java applet is probably the first well known thing concerning Java Programming language. Java came into the community with Applet. Applet was helping Java to be distributed among the community. I see lots of similarities between Java Applet and AJAX driven web applications. But why Java Applet was not well distributed with regards to AJAX, is very important

à Java Applets need Java Runtime Environment to be run- But AJAX, it’s not depend on particular technology

àDesigning Good Web UI is bit challenging with Java Applet- But with AJAX, it won’t make any disturb on UI design.

àJava Applets is bit Java Specific thing. Therefore Applet was not popular among the non java technical people.

àEtc……

August 18, 2008

Abstraction is achieved using encapsulation.

Filed under: Software Design and Documenting — Lakmal @ 2:34 pm

Abstraction is about good use of encapsulation. Suppose there is a Button in an application called “View Accounts”, user can only use that button to see “Accounts”. Once he pressed that button he will be viewed with set of “Accounts”. And important thing is button users were not involved with “Accounts” List processing and he just used button to list the “Accounts”. “Account” List processing is hidden from the user.

This is a one example of Abstraction. The users of this class will only see Method “ListAccounts” and they won’t see account processing method call “GetAccounts”. There is no public variable to temper class state by the users.

class AccountProcess

{

public void ListAccounts()

{

List<string> accouts = GetAccounts();

//View Accounts

}

/// <summary>

/// Encapsulate Account process part by making this method private. And it’s only

/// possible to use in this class. Out side users won’t see this.

/// </summary>

/// <returns></returns>

private List<string> GetAccounts()

{

List <string> accouts = new List<string> ();

//Process System to extract Account List

//Return Account List

return accouts ;

}

}

Using Interfaces

This is an example of achieving Abstraction using Intefaces.

interface IAccountServiceProvideer

{

void ListAccounts();

// And so on and so on…….

}

class AccountProcess : IAccountServiceProvideer

{

#region IAccountServiceProvideer Members

void IAccountServiceProvideer.ListAccounts()

{

List<string> accouts = GetAccounts();

//View Accounts

}

#endregion

/// <summary>

/// Encapsulate Account process part by making this method private. And it’s only

/// possible to use in this class. Out side users won’t see this.

/// </summary>

/// <returns></returns>

private List<string> GetAccounts()

{

List <string> accouts = new List<string> ();

//Process System to extract Account List

//Return Account List

return accouts ;

}

}

class AccountUser

{

public void UserAccounts()

{

IAccountServiceProvideer accountsServiceProvider = new AccountProcess();

// Here AccountUser call will only see ListAccounts Method

accountsServiceProvider.ListAccounts();

}

}

It’s not possible to hide all the Object from the users. To use an object part of it’s Data should be revealed. To provide this access Abstraction is used. While Abstraction provide access to a specific part of the Object, Encapsulation hides information which Object user don’t need to see.

Abstraction defines conceptual boundaries of an Object and Those boundaries defers that Object from another. Encapsulation hides complexity of object from it’s users.

Regards

Lakmal

OOP Concepts………….

Filed under: Software Design and Documenting — Lakmal @ 12:26 pm

Object Oriented Programming

All the Design Patters are finally based on OOP techniques. History of OOP began with first OOP Supporting Language called “Small Talk”. After that it was introduce bunch of OOP supported languages and most of procedural oriented languages (Like C++,VB and so on and so on) also came with their OOP version. Classes and Objects are the main artifact of the OO Programming.

What is an Object?

Object always represent Real or Unreal thing. Or whatever it is having Sate and Behavior. As example of object, you can take yourself as Objet of Type Human being.

What is a Class?

We can say it’s a template of what we are generating objects. It’s Model of the state and Behavior of Objects.

class Employee

{

//State Associated with Employee class. In C# it can be represent using Properties and Instance variables

//But in java you can use Instance Variables

private int _employeeID;

private string _employeeName;

//Constructor

public Employee(string name, int id)

{

_employeeID = id;

_employeeName = name;

}

// This is bahaviour particular Employee object is having.

public bool SaveEmployee()

{

//Employee saving is implemented here

}

// As same as saving, Returning employee name is also a behaviour of

//Particular Employee Object is having

public string getEmployeeName()

{

return _employeeName;

}

}

OOP Concepts

Gods of Object Oriented Programming are Abstraction, Inheritance, Encapsulation and Polymorphism

Abstraction

Abstraction defines conceptual boundaries of an Object. I did read lots of definitions of Abstraction but I can’t remember any of them at all. According my experience, Abstraction is way to remove associations of object behavior with actual details behind the scenes which implement that object that object behavior. Abstraction is something like Principle or quality. Abstraction is achieved through the encapsulation.

For Real world example, suppose when you go to a bank for change a check and You just giving your check to bank assistant and they will do processing for change check, that on their side, but you don’t know what’s happening inside banking process. You just do only hand over your check to bank assistant and Check processing processing is hidden from you.

For an example, one way we can achieve this through Base class with virtual methods and each derived methods implement behavior behind that abstraction. Another way to achieve Abstraction is using interfaces. All most all the OOP languages are supporting Interfaces.

How I would remind it as that it allows class user to look at and use a class  without tempering it’s internal implementation. The well implemented class will be having private State variables and public Methods to interface it’s Functionalities.

Inheritance

It’s about Sharing Common State and Behavior through the common Base class. Different Types of objects might be having common state and behavior, so we encapsulate those common behaviors into separate base class.

Take a look at this BankAccount class. It’s having method (Behavior) called “GetBankNmae()” its implementation is common for all Types of Bank Accounts. But It differs iplemetations of Method call “CalculateAccountBalance()” from several Account type to type.

class BankAccount

{

//State of bank account object

private string _accountBalance;

private string _bankName = “Sampath Bank”;

// Behaviour which is common through out the all the bank accounts

public string GetBankNmae()

{

return _bankName

}

//Behaviour which are not common for all the bank accounts

public double CalculateAccountBalance()

{

// Here Calculating Account balance is depend on its account type.

//each Account types are having several interst rates

return 0;

}

}

Encapsulate what varies

Encapsulate what varies, so we can encapsulate balance calculating process into Each SubBankAccount classes.

class SavingsAccount : BankAccount

{

public double CalculateAccountBalance()

{

//Then you would know what’s the exact rate of savings account and

// from that easilly calculate Account balance

}

}

Encapsulation

“The process of hiding all the details of an object
that do not contribute to its essential characteristics; typically,
the structure of an object is hidden, as well as the implementation of
its methods. The terms information hiding and encapsulation are usually
interchangeable.”

This is a definition for Encapsulation which I got from a book. Encapsulate is Technique you can use.

Regards

Lakmal

August 15, 2008

Design Patterns Give More Confidence to the Developers

Filed under: Software Design and Documenting — Lakmal @ 9:19 am
In Norway

In Norway

What’s a Pattern In software Engineering?

People might be having several definition for this, But for me it’s a not only re use of best proven experience, but Nice Looking Code, Well Understandable, No nightmare maintaining, Greater Extensibility of implementation and so on and so on. If I say briefly that what design pattern for me, it is a great learning. It’s definitely will be changing, the way of you think about particular implementation than you did in past.

The way I would think before applying particular pattern to my development

Applying design patterns in better way in you code is about understanding of Brininess components in the system that is to be developed. Patterns allows you to

Decoupling – Decoupling between what, Might Be Two Business Components, Two UI Components and so on and so on.

Extensibility of implementation in future – Yes we know by experience, developing Of business system not going to end with first Release. It’s always Customer will be coming up with New Requirements, Extending and Changing of currently implemented requirements and so on and so on.

Maintainability – It’s about changing and extending current Implementations.

More Readable – This is the most favorable thing for me (but might not for you), because I was struggling with messed up code in recent pass.

And so on and so on.

So therefore before applying a particular pattern, you should think about that what patterns would allow you to do with that. Get better understanding of what each and every pattern allows you to do with it. Then try to map them with your issues.

Steps to follow before applying patterns

1) Understand Patterns well

In programming, you would be having bunch of ways to implement something that the place where you need to apply well proven best implementation practice (Or Design Pattern). It means, it’s not a must to apply design patterns in development, but if you do so, it will bring you lots of advantages.

Keep Patterns and its meaning in your mind

Normally it’s difficult to find a pattern after you identified the issue. According my experience, normally you wouldn’t find any issues with development other than you are having good Programming practices in your mind. In that mood, we are not bothered about Decoupling, Extending and so on and so on. So then better keep in mind, OOP practices and concepts, Design Patters and their applicability and so on and so on.

Think more and more before applying patterns.

Not allow to become anti pattern that the pattern you applied. It’s about experience and expertise that you take right decision at once. According my short experience, I made bunch of wrong decisions, but I was fortunate to understand them and made them correct.

Pattern Expiring

In future, can it be miss match that your pattern applied with development? Yes it can be. Again it means you were not properly aware of real Business Requirements, their growing and changes can happen. Refactoring might be the solution for this, In experience we know refactoring gives us lots of burden.

Regards

Lakmal

Next Page »

Create a free website or blog at WordPress.com.