Thursday, 7 July 2011

The abstractions ....

The Direction and types...

namespace MarsRover
{
abstract class Direction
{
public abstract Direction GetLeft();
public abstract Direction GetRight();
public abstract Position GetNext(Position pos);
}

class East : Direction
{
public override Direction GetLeft()
{
return new North();
}

public override Direction GetRight()
{
return new South();
}

public override Position GetNext(Position pos)
{
pos.X++;
return pos;
}

public override string ToString()
{
return "East";
}
}

}


The step and steps....

namespace MarsRover
{
abstract class Step
{
public abstract Position GetPosition(Position position);
}

class LeftRotation : Step
{
public override Position GetPosition(Position position)
{
position.Direction = position.Direction.GetLeft();
return position;
}
}

class Move : Step
{
public override Position GetPosition(Position position)
{
return position.Direction.GetNext(position);
}
}
}

namespace MarsRover
{
abstract class Plateau
{
public abstract bool IsPositionOutOfRange(Position pos);
}

class RectPlateau : Plateau
{
readonly int x;
readonly int y;

public RectPlateau(int x, int y)
{
this.x = x;
this.y = y;
}

public override bool IsPositionOutOfRange(Position pos)
{
return ((x < pos.X) || (y < pos.Y))
? true
: false;
}
}
}

Check the class diagram


Few classes:

Controller - The main class: with all the I/O

using System;

namespace MarsRover
{
class Controller
{
public static void Main(String[] args)
{
try
{
Plateau plateau = Factory.CreatePlateau("5 5");
Rover rover = Factory.CreateRover("1 2 N");
String instruction = "LMLMLMLMM";
Position pos = Process(plateau, rover, instruction);
Console.WriteLine("Rover position is " + pos.X + " " + pos.Y + " " + pos.Direction);

rover = Factory.CreateRover("3 3 E");
instruction = "MMRMMRMRRM";
pos = Process(plateau, rover, instruction);
Console.WriteLine("Rover position is " + pos.X + " " + pos.Y + " " + pos.Direction);
}
catch (Exception ex)
{
Console.WriteLine("Exception occurred" + ex.Message);
}
Console.ReadKey();
}

public static Position Process(Plateau plateau, Rover rover, String instructions)
{
foreach (char instruction in instructions)
{
rover.ProcessStep(Factory.CreateStep(instruction));
if (plateau.IsPositionOutOfRange(rover.Position))
{
throw new PositionOutOfRangeException("The Rover is out of Plateau.");
}
}
return rover.Position;
}
}
}



The Factory: All the creations happen here.


using System;

namespace MarsRover
{
class Factory
{
public static Plateau CreatePlateau(String dimensions)
{
try
{
String[] split = dimensions.Split(new[] {' '});
int side1 = Int32.Parse(split[0]);
int side2 = Int32.Parse(split[1]);
return new RectPlateau(side1, side2);
}
catch (Exception ex)
{
throw new InvalidInputException(string.Format("Failed to create Plateau from give dimensions:{0}. Exception is {1}", dimensions, ex.Message));
}
}

public static Rover CreateRover(String coordinates)
{
try
{
String[] split = coordinates.Split(new[] {' '});

int side1 = Int32.Parse(split[0]);
int side2 = Int32.Parse(split[1]);
string hint = split[2].Trim();

Direction direction;
switch (hint[0])
{
case 'N':
direction = new North();
break;
case 'E':
direction = new East();
break;
case 'S':
direction = new South();
break;
case 'W':
direction = new West();
break;
default:
throw new InvalidInputException("Invalid direction specified.");
}

Position pos = new Position(side1, side2, direction);
return new Rover(pos);
}
catch (Exception ex)
{
throw new InvalidInputException(string.Format("Failed to create Rover from give coordinates:{0}. Exception is {1}", coordinates, ex.Message));
}
}

public static Step CreateStep(char instr)
{
switch (instr)
{
case 'L': return new LeftRotation();
case 'R': return new RightRotation();
case 'M': return new Move();
default:
throw new InvalidInputException(string.Format("Failed to create step from given instruction: {0}" + instr));
}

}
}
}

Thursday, 20 January 2011

Sample problems for application design...!

Take few sample problems and will apply the design basics and eventually understand different patterns solving them....
Here are couple of ploblems found on net....please try it for yourself and share the solution .. I will be posting the my solutions tomorrow.

MARS ROVERS


A squad of robotic rovers are to be landed by NASA on a plateau on Mars.
This plateau, which is curiously rectangular, must be navigated by the
rovers so that their on-board cameras can get a complete view of the
surrounding terrain to send back to Earth.

A rover's position and location is represented by a combination of x and y
co-ordinates and a letter representing one of the four cardinal compass
points. The plateau is divided up into a grid to simplify navigation. An
example position might be 0, 0, N, which means the rover is in the bottom
left corner and facing North.

In order to control a rover, NASA sends a simple string of letters. The
possible letters are 'L', 'R' and 'M'. 'L' and 'R' makes the rover spin 90
degrees left or right respectively, without moving from its current spot.
'M' means move forward one grid point, and maintain the same heading.

Assume that the square directly North from (x, y) is (x, y+1).

INPUT:
The first line of input is the upper-right coordinates of the plateau, the
lower-left coordinates are assumed to be 0,0.

The rest of the input is information pertaining to the rovers that have
been deployed. Each rover has two lines of input. The first line gives the
rover's position, and the second line is a series of instructions telling
the rover how to explore the plateau.

The position is made up of two integers and a letter separated by spaces,
corresponding to the x and y co-ordinates and the rover's orientation.

Each rover will be finished sequentially, which means that the second rover
won't start to move until the first one has finished moving.


OUTPUT
The output for each rover should be its final co-ordinates and heading.

INPUT AND OUTPUT

Test Input:
5 5
1 2 N
LMLMLMLMM
3 3 E
MMRMMRMRRM

Expected Output:
1 3 N
5 1 E
==========


SALES TAXES

Basic sales tax is applicable at a rate of 10% on all goods, except books,
food, and medical products that are exempt. Import duty is an additional
sales tax applicable on all imported goods at a rate of 5%, with no
exemptions.

When I purchase items I receive a receipt which lists the name of all the
items and their price (including tax), finishing with the total cost of the
items, and the total amounts of sales taxes paid. The rounding rules for
sales tax are that for a tax rate of n%, a shelf price of p contains
(np/100 rounded up to the nearest 0.05) amount of sales tax.

Write an application that prints out the receipt details for these shopping
baskets...
INPUT:

Input 1:
1 book at 12.49
1 music CD at 14.99
1 chocolate bar at 0.85

Input 2:
1 imported box of chocolates at 10.00
1 imported bottle of perfume at 47.50

Input 3:
1 imported bottle of perfume at 27.99
1 bottle of perfume at 18.99
1 packet of headache pills at 9.75
1 box of imported chocolates at 11.25

OUTPUT

Output 1:
1 book : 12.49
1 music CD: 16.49
1 chocolate bar: 0.85
Sales Taxes: 1.50
Total: 29.83

Output 2:
1 imported box of chocolates: 10.50
1 imported bottle of perfume: 54.65
Sales Taxes: 7.65
Total: 65.15

Output 3:
1 imported bottle of perfume: 32.19
1 bottle of perfume: 20.89
1 packet of headache pills: 9.75
1 imported box of chocolates: 11.85
Sales Taxes: 6.70
Total: 74.68
==========

Tuesday, 11 January 2011

Basics of software design

What are the characteristics of good design? How can we identify the gaps in design? How to review other designs? We shall try to find answers to those questions.
The fowling characteristics are considered to be adhered in a good design.

• Strong cohesion
• Loose coupling
• No redundancy
• Testability of all the features by itself.

Strong cohesion

In computer programming, cohesion is a measure of how strongly-related the functionality expressed by the source code of a software module is. Cohesion of class/method is about having single responsibility and fulfilling it. It is not about how strongly they are related to each other.

Loose coupling

In computing and systems design a loosely coupled system is one where each of its components has, or makes use of, little or no knowledge of the definitions of other separate components.
The coupling can be observed in the code wherever (as class variables, method parameters or return types or method variables) class is accessed from other class. Worst form of coupling is one class accessing base type and sub type of a class hierarchy). Except while constructing the object, everywhere else the base type should be used.

let us continue...

Basic terminology of software design

Here are the cryptic definitions and what they mean in your code?

Abstraction

A concept or idea not associated with any specific instance. It is an emphasis on the idea, qualities and properties rather than the particulars (a suppression of detail), It is simplifying complex reality by modeling classes appropriate to the problem, and working at the most appropriate level of inheritance for a given aspect of the problem.
Abstraction can be implemented via Abstract Class/Interface. In both cases, abstract behavior needs to be implemented by the extending/implementing classes. However the catch is we shouldn’t use the implementing class name anywhere in the code except in creation. If the extending/implementing class used as parameter to methods, variable in other classes then note that you are not abstracting it. I will be posting various examples in later, please pay attention to this.

Abstract class x
{
method();
}

Interface x
{
method();
}

Class Y: (extends/implements) x
{
Method()
{
Do something;
}
}

Do not refer Y anywhere in the code except while creation.
Always
X x = new Y();
x.method();

If there is code like below then Y is not abstracted.

Class Z
{
Y y;
Or
OtherMethod(Y y)
Or
Y OtherMethod()
}

Let us continue ...

Understanding software design Vs. Designing software applications

The design principles are least applied by most of the software professionals. The series of post on software design basics are targeted towards bridging the gap between understanding software design and designing software applications. It covers the following aspects

• Basics terminology of software design
• Basics of software design
• Design patterns
• Sample applications using these patterns