## Wednesday, December 16, 2009

### Liskov's Substitution Principle

Liskov's Substitution Principle (LSP) is one of the five software design principles. What programming languages you know, you should know these five principles written below :

LSP is first mentioned by Barbara Liskov in 1987 conference keynote. This principle is about relation between subclasses and base classes. We can say strong behavioral subtyping. When you read the principle, you will find something similar with Open Close Principle.

If function in base class is modified because of that new derivative of the base class is created. You shouldn't need to change function which is placed in base class.

Key Principle
Functions that use pointers or references to base classes must be able to use objects of derived classes without knowing it.

Violation of Liskov's Substitution Principle
I will write a best known example; Rectangle and Square. You can think of that Square is a kind of  special rectangle. Then the square can be inherited from Rectangle class.

```public class Rectangle
{
protected int _Width;
protected int _Height;

public void SetWidth(int width)
{
_Width = width;
}

public void SetHeight(int height)
{
_Height = height;
}

public int CalculateArea()
{
return _Height * _Width;
}
}

public class Square : Rectangle
{
public void SetWidth(int width)
{
_Width = width;
_Height = width;
}

public void SetHeight(int height)
{
_Height = height;
_Width = height;
}
}
public class Program
{
public static void Main()
{
Rectangle r = GetNewRectangle();
r.SetHeight(5);
r.SetWidth(10);

Console.WriteLine(r.CalculateArea());
// Output : 50 instead of 25
}
private static Rectangle GetNewRectangle()
{
return new Square();
}
}```
The square class which is derived from Rectangle class assumes that width is equal with the height. When Square is used in context where Rectangle class is expected, unexpected behavior may occur, because the dimensions of the square can not be set independently.

For further information you can download pdf file written by Robert C.Martin.

## Sunday, December 13, 2009

### Single Responsibility Principle

Single Responsibility Principle (SRP) is one of the five software design principles. What programming languages you know, you should know these five principles written below :

Purpose / Reason
Each class or module should be responsible only one task. For instance, if you have one Employee class to update Employee information, calculate salary and tax. You have more than one reason to modify Employee class. I mean, when you need to change algorithm of calculating salary or tax, you have to change same class. In our purpose, you have only one reason to change class or module.

Key Principle
There should  never be more than one reason for a class to change.

Implementation
For instance, you have one Employee class which is responsible for calculation salary and tax, modify Employee information and sending hours reports to managers.

```public interface IEmployeeManager
{
void SendHourReports();
Money CalculateSalary();
double CalculateTax();
void UpdateEmployee(Employee employee);
void CreateEmployee(Employee employee);
}```
As you see Employee class has more than one task to perform. Instead of designing Employee class like that, it's better to separate similar functionalities into three classes. Look at good example.

Good Example :

```public interface ISalary
{
Money CalculateSalary();
double CalculateTax();
}

public interface IReport
{
void SendHourReports();
}

public interface IEmployeeDatabase
{
void UpdateEmployee(Employee employee);
void CreateEmployee(Employee employee);
}```

I divide Employee class into three different classes which are ISalary, IReport, IEmployeeDatabase . Because, Employee class actually has three main functionalities :

• Salary functionalities
• Employee report s
• Database behaviors
Summary
If a class has more than one responsibility, then there will be more than one reason to modify class or module. Preventing this, you need to be able to separate classes or modules into more than one classes or module. Otherwise responsibilities become coupled and change is a manifest through a change in a responsibility among the classes or modules.

## Wednesday, December 9, 2009

### How to Investigate Disk Bottleneck

On previous entry, i explained how to determine that you have enough ram on your server. Today, i will tell you about how to examine disk bottleneck. For this purpose, you need monitor a few performance counters :

• PhysicalDisk : Average Read Queue Length
• PhysicalDisk : Average Write Queue Length
• PhysicalDisk : Disk Transfer / sec
• PhysicalDisk : Idle Time
• PhysicalDisk : % Disk Time
I admit that, it is usually difficult to understand exact meaning of counters. But anyway, i will try to explain with the values what they should be.

Average Read Queue Length indicates how many system request are waiting for disk access. This value should be less than 2

Average Write Queue Length indicates average number of write requests that are queued. This value should be less than 2

Disk Transfer / sec shows the rate or read and write operations on disk. If it is greater than 25 disk I/O per second, you have poor response time. This value of the counter should be below 25.

Idle Time indicates idle time of your disk. Normally, value of the counter should be greater than %20

Disk Time is the percentage of elapsed time that the selected disk drive was busy servicing read or write requests. If it is more than %50, it indicates a disk bottleneck

Beside these counters, you can check following counters to determine whether it's a bottleneck.
Average disk seconds/read and average disk seconds/write need to be below around 12ms.

## Tuesday, December 8, 2009

### How to Determine Enough RAM in Your Server

In this entry,i explain how to determine whether your server has enough ram to perform operations prosperously.  For this aim, you should monitor some counters using performance monitor tool. There are three main counters to check wheter RAM size is enough.

Memory\Pages/sec
This counter is a general indicator of how often the system is using the hard drive to store or retrieve memory associated data. If number of pages per second exceeds 50 per paging disk, it indicates downward trend. You can create a trigger which notify you when it's  greater than 50.

Memory\Available Bytes
This counter indicates remaining memory after nonpaged pool allocations,
paged pool allocations, process' working sets, and the file system cache have all taken their piece
If the counter is greater than 10% of actual RAM, you are on safe side, you are away from risk zone.

This counter is another good indicator of a memory shortage. The counter shows that how often the system is reading from disk. A "sustained" value over 5 page/sec  is "often" a strong indicator of a memory shortage. You may see more than 5 page/sec, but you don't have to be  worry about that because temporarily, it can be more than 5 page/sec.

Click for more performance counters explain

## Sunday, December 6, 2009

### Open Closed Principle

Open Closed Principle (DIP) is one of the five software design principles. What programming languages you know, you should know these five principles written below :

• Open Close Principle (OCP)
In this column i will explain Open Closed Principle.

Purpose/Reason

The reason to use open closed principle is to add new features without changing existing software entities. Especially in enterprise application, due to marketing conditions, softwares need to be changed. In order to reduce time, cost and risk for implementation new features, you should consider how to expand software easily. Open closed principle is one of the five answers written above.

Key Principle
Open Close Principle states software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification.

Implementation
Suppose that, you have two different database products which are MySQL and Oracle. In order to connect right database, you built a DatabaseManager to decide that which database product is used to connect. Here is the solution which is not recommended.

```public class DatabaseManager
{
public void Connect(Database d)
{
if (d.DBType == 1)
ConnectMySQL((MySQLDB)d);
else if (d.DBType == 2)
ConnectOracle((OracleDB)d);
}

public void ConnectMySQL(MySQLDB db)
{
// connect
}

public void ConnectOracle(OracleDB db)
{
// connect
}

}

public class Database
{
public int DBType;
}

public class MySQLDB : Database
{
public MySQLDB()
{
base.DBType = 1;
}
}

public class OracleDB : Database
{
public OracleDB()
{
base.DBType = 2;
}
}```

For instance, yesterday, your manager said that, we need to support Microsoft SQL database product. For this implementation, you need to modify almost all classes. But if you cared open closed principle before, you wouldn't need to change all classes. Let's see good example about how it should have built.

Good Example :

```public abstract class Database
{
public abstract void Connect();
}

public class DatabaseManager
{
private Database db;
public DatabaseManager(Database db)
{
this.db = db;
}

public void Connect()
{
this.db.Connect();
}
}

public class MySQLDatabase : Database
{
public void Connect()
{
//connect MySQL
}
}

public class OracleDatabase : Database
{
public void Connect()
{
//connect Oracle
}
}```
If you had built your database manager like above, you wouldn't have needed to modify all classes. The only thing you should do is add new MicrosoftSQL class into current situation.

```public class MicrosoftSQL : Database
{
public void Connect()
{
// connect Microsoft SQL
}
}```
Summary :
As you see, this principle should be applied software application which is most likely to be modified or added new features into current situation. Otherwise, your software application has more abstractions between classes and this occurs more complication in your code.

## Tuesday, December 1, 2009

### Interface Segregation Principle

Interface Segregation Principle (DIP) is one of the five software design principles. What programming languages you know, you should know these five principles written below :
In this column i will explain Interface Segregation Principle.
Purpose / Reason
The reason to use ISP is to prevent getting interface "fat". Fat in this subject means that unused methods and properties are still exist and it makes developers to force implement them. For instance, when you need to change obese interface, you will likely have to modify all codes which are unrelated with the obese interface. Another term of fat interface is "polluted interface". Having an interface pollution may occur uninvited exception in runtime.  To prevent this disadvantage, we should separate fat interfaces.

Key Principle
Clients shouldn't be forced to depend upon interfaces that they don't use. *

Implementation
For this case we have two examples, one of them is bad, another is a good example. For these example, i use animal world. As you know each species has different abilities, such as flying, swimming. Some abilities are common, such as eating, sleeping.
In order to clarify ISP, i starts with bad example.

```public interface IAnimal
{
void Fly();
void Eat();
void See();
void Swim();
}

public class Dog : IAnimal
{
// Fly couldn't be implemented
public void Fly()
{
throw new NotImplementedException();
}

public void Eat()
{
Console.WriteLine("Dog is eating");
}

public void See()
{
Console.WriteLine("Dog is seeing");
}
// Swim couldn't be implemented
public void Swim()
{
throw new NotImplementedException();
}
}

public class Bird : IAnimal
{
public void Fly()
{
Console.WriteLine("Bird is flying");
}

public void Eat()
{
Console.WriteLine("Bird is eating");
}

public void See()
{
Console.WriteLine("Bird is seeing");
}
// Swim couldn't be implemented
public void Swim()
{
throw new NotImplementedException();
}
}

public class Fish : IAnimal
{
// Fly couldn't be implemented
public void Fly()
{
throw new NotImplementedException();
}

public void Eat()
{
Console.WriteLine("Fish is eating");
}

public void See()
{
Console.WriteLine("Fish is seeing");
}

public void Swim()
{
Console.WriteLine("Fish is swiming");
}
}```
For this example, IAnimal is an interface and Fish, Bird and Dog classes are derived from IAnimal interface. Although some methods are common in these classes, such as See(), Eat(); however, there are some methods that shouldn't be implemented. For Bird class Swim() method shouldn't be implemented by Bird. Because Bird cannot swim.

Suppose, for example, you need to add Walk() functionality, your interface IAnimal is getting fat. Also classes which implement IAnimal interface have method which is never used.

It seems work and can be built if we use this bad solution. But in runtime, exception can be occurred.

Good Example :
Here is the solution. We need to separate common used method and create new interface for these. Look at following code example :

```public interface IAnimal
{
void Eat();
void See();
}
// interface for living in air
public interface IAnimalAir
{
void Fly();
}
// interface for living in sea
public interface IAnimalSea
{
void Swim();
}

public class Fish : IAnimal, IAnimalSea
{
public void Eat()
{
Console.WriteLine("Fish is eating");
}

public void See()
{
Console.WriteLine("Fish is seeing");
}

public void Swim()
{
Console.WriteLine("Fish is swiming");
}
}

public class Dog : IAnimal
{
public void Eat()
{
Console.WriteLine("Dog is eating");
}

public void See()
{
Console.WriteLine("Dog is seeing");
}
}

public class Bird : IAnimal, IAnimalAir
{
public void Eat()
{
Console.WriteLine("Bird is eating");
}

public void See()
{
Console.WriteLine("Bird is seeing");
}

public void Fly()
{
Console.WriteLine("Bird is  flying");
}
}```
Summary I know, it's really difficult to forecast the interface which was written whether can be expanded in future. Don't concern about next requirements. Just create your interface layout, after that, if you need to add new functions into the interface, you should think about whether you will separate the interface into different interfaces.