Monday, September 24, 2007

Design Principles and Patterns

Several hours ago I started to read Head First Design Patterns. Although I am only several chapters into the book my understanding of patterns is already broadening. As I read Head First Design Patterns I am increasing my "programmers vocabulary". This means that will be able to speak more fluently with other software developers. Rather than going into a verbose conversation about the details of a solution I can simply spew out the name of a design pattern.

Head First Design Patterns has enlightened me as to why design patterns are important. A common misconception is that patterns are nothing more than using object oriented design principles. Not all design patterns are obvious, even those who are well versed in object oriented programming may not be able to reproduce many of these design patterns. By understanding design patterns you can jump right to creating proven solutions that work. Needless to say good OO skills are always necessary. After all OO principles are the basis upon which design patterns are built upon on.

Here are a few design principles that I have been introduced to.

  1. Take what varies and encapsulate it, so it does not affect the rest of your code.

  2. Program to an interface not to an implementation.

    The one misconception with this design principle is that you must use an interface. In fact this principle refers to using a super type in place of a concrete type. Hence, you could replace the world interface for super type. Program to an super type not to an implementation.

  3. Favor composition over inheritance.

  4. Strive for loosely coupled designs between objects that interact.

  5. Classes are open for extension, but closed for modification.

Sunday, September 23, 2007

The Often Forgetful but Important Value Type

More often than not we take the little things for granted. Value types are one of the many unappreciated heroes of the .Net Framework. Value types are used on a daily basis without ever giving a second thought to performance or impact. The following post aims to characterize and explain what a value type is.

There are three categories of value types

  1. Built in types
  2. User defined types (Structures, Struct)
  3. Enumerations

General Guidelines for all value types

  • Value types contain their data directly.

  • Value types are stored in an area of memory known as the stack. The stack allows for variables to be created, read, updated and removed quickly during runtime with minimal overhead.

  • When you assign between value types the data is copied from one variable to the other. For example

    Int32 AdamsAge = 24; //Stored at memory address 1
    Int32 YourAge = age; //Stored at memory address 2

    YourAge = 30;

    AdamsAge will remain as 24.

    Thus an assignment between value types stores the data in two different areas of memory on the stack. This contrasts the behavior of reference types.

  • All value types are derived from System.ValueType.

  • All types are derived from System.Object. This means that methods may be called on value types.

  • Value types have an implicit constructor. Thus, a deceleration unwittingly instantiates the type automatically. The new keyword does not have to be included as you do with classes. The default value is usually 0 or null. As a rule of thumb you should always assign a default value.

  • As of .Net 2.0 the Nullable type is available. Nullables allow you determine if a variable has been assigned or not. A nullable type is an instance of System.Nullable. System.Nullable is a structure.

    For example boolean values may now have three states true, false, null(not selected).

    Syntax

    Nullable<bool> isVisible= null;
    bool? isVisible = null;

    A Nullable variable has the following additional properties HasValue and Value.

    For more information regarding Nullables please read the following article MSDN.


1. Built in Types

The general guidelines above apply to all built in types. Built in types are base types provided by the .Net Framework. Built in types are used to build other types. The most common types are:

  • Char
  • Boolean
  • Int32
  • Double
  • Decimal
  • DateTime
  • String Yep, that's right string is not a value type. String is in fact a reference type.

2. User Defined Types

A structure is a composite of other value types. Structures behavior is almost identical to that of a class. An example of a simple structure would be a point on a grid. The point type contains two integers X and Y. X being the horizontal location and Y being the vertical location.

The point structure could be created as follows. As you can see this point structure is very simple.

public struct Point

{

   int x;

   int y;

}

The following point structure is much more complex and offers more value. This example exposes a constructor and several methods to change the X and Y coordinates of the point.

public struct Point {

    private int x;

    private int y;

 

    public Point(int x, int y) {

        this.x = x;

        this.y = y;

    }

 

    public int X {

        get { return x; }

        set { x = value; }

    }

 

    public int Y {

        get { return y; }

        set { y = value; }

    }

 

    public void MoveUp() {

        Y += 1;

    }

 

    public void MoveDown() {

        Y -= 1;

    }

 

    public void MoveLeft() {

        X -= 1;

    }

}

Getting in the spirit of test driven development here are a few tests to illustrates how this structure works.

[TestFixture]

    public class PointTest {

        private readonly int xStartPos = 8;

        private readonly int yStartPos = 9;

        private Point point;

 

        [SetUp]

        public void SetUP() {

            point = new Point(xStartPos, yStartPos);

        }

 

        [Test]

        public void Should_Move_Down_Once() {

            point.MoveDown();

            Assert.IsTrue(point.Y == yStartPos - 1, "Should have moved the y axis down by one(Y-1).");

        }

 

        [Test]

        public void Should_Move_Down_Twice() {

            point.MoveDown();

            point.MoveDown();

            Assert.IsTrue(point.Y == yStartPos - 2, "Should have moved the y axis down by two(Y-2).");

        }

 

        [Test]

        public void Should_Move_Down_Up() {

            point.MoveUp();

            Assert.IsTrue(point.Y == yStartPos + 1, "Should have moved the Y axis up by one(Y+1).");

        }

 

        [Test]

        public void Should_Move_Left() {

            point.MoveLeft();

            Assert.IsTrue(point.X == xStartPos - 1, "Should have moved the X axis left by one(X-1).");

        }

    }

structures usually are more efficient than classes. A structure should meet the following criteria.
  • Logically represents a single value.
  • Has an instance size less than 16 bytes.
  • Will not be changed after creation.
  • Will not be cast to a reference type.

3. Enumerations

Enumerations allow you to assign values to symbols. The primary benefit of enumerations is to improve code readability. Instead of passing an arbitrary number into a method one can pass in a meaningful symbol. The following is an example of an enumeration.

 

public enum CarManufacturers { Honda, Acura, BWM, Audi, Mazda, Hyundai, GM }

 

public class Car {

    private CarManufacturers manufacturer;

    public Car(CarManufacturers manufacturer) {

        this.manufacturer = manufacturer;

    }

 

    public CarManufacturers Manufacturer {

        get { return manufacturer; }

    }

}

 

//We can now easily check the manufacturer of a car

 Car car = new Car(CarManufacturers.Honda);

 

 if(car.Manufacturer.Equals(CarManufacturers.Honda))

    Console.Write("Honda");

 

Thursday, September 13, 2007

JP Boodhoo is in the house!

Thats right, over the last few weeks the great JP Boodhoo himself has been doing a little consulting work for MediaLogic. Although JP has a very busy schedule he has managed to make a few appearances at our office. His spirit and energy for software development is remarkable. Watching him create a solution before your eyes is like a work of art. I now find myself inspired to work even harder at my goals. JP has introduced and clarified many topics in only a few short sessions. His knowledge and enthusiasm has acted as a catalyst that has brought out the best in our team.

Thanks JP!

Wednesday, September 12, 2007

My Goals

Goals goals goals... That seems to be the focus these days. A number of .Net developers who are in the limelight(JP Boodhoo, Justice Gray, Scott Hanselman) have taken a brave step forward and committed to their goals in public forum. I to have decided to do the same. The following is a List<IGoal> of goals.

  1. Become more proficient at test driven development.

  2. Expand my knowledge of domain driven design.

  3. Become more proficient with resharper.

  4. Watch DnrTv

  5. Continue to read all those wonderful blogs that I have listed on my sidebar.

  6. Learn and appreciate the time that I get to spend with JP Boodhoo. That's right JP Boodhoo has been doing consulting work for MediaLogic. He has provide our team with lots of great insight and knowledge.

  7. Learn how to write a Nant script. I've seen a Nant script or two but never created my own.

  8. Learn more about continuous integration. MediaLogic should have a CI box soon.

  9. Expand my knowledge of design patterns. More importantly I need to expose myself to as many solutions as I can. By being aware of more than one solution to a problem I will be able to select the best solution for a problem rather than trying to adapt the problem to the solution.

  10. Read books
  • Domain Driven Design By Eric Evans

  • Head First Design Patterns

  • Patterns of Enterprise Application Architecture By Martin Fowler

  • Re-read Test Driven Development by Kent Beck

  • The Pragmatic Programmer By Andrew Hunt

  • Code Complete by Streven McConnell

  • MCTS 70-536 and 70-528

  • Framework Design Guidelines by Krzysztof Cwalina and Brad Abrams

  • The Elements of C#

  • CLR via C#

As you can tell this list is very lengthy. Fortunately many of these goals are related to one another. In order to conquer these goals I will have to devise some type of routine. As long as I can stick to some type of schedule I should be able to complete these goals without a problem. A wise friend of mine recently enlightened me to the idea that perfection can achieved through consistency. For example, If I were consistently sad one could say that I have achieved perfection at being sad. Instead of striving for perfection aim for consistency. Thanks Mista Mo