Back To Basics

Here the other day, I got the question: ”How do I become a good developer? (OOP)”…

My reply…… Know your patterns!

It’s hard to write a blog post on basic object design and OOP without writing about the analysis aspect of OOP. Even still, I do not explain about Use case analysis, Domain models etc. even though these are equally important for the development process.

When starting to develop applications, nobody has all the ideas in their heads at first. It’s a combination of experience and knowledge of the basic patterns that make the application come to life. The more experience the developer has, the more of the “design” goes on by reflex and inside the head, and thus faster. Just a little note here: The fact that the design comes by reflex and goes on inside the head of the developer is also a downfall! If you’re not able to document the process of your work, you have failed in designing it properly! The software you’re designing should be documented to an extend that another developer can pick up the code and develop on it further with easy understanding of what is going on. That’s my humble opinion.

There are many details to developing, and in this blog post I don’t go into detail about the Unified Process, Scrum or any other iterative analysis & design development processes, even though these processes are at the heart of Object Oriented Programming. Actually, to be a good developer, the first question you need to answer is – What is Object Oriented Programming? And thereafter you can throw yourself at object design patterns.

There are many ways to answer what OOP is, but here is my version:

OOP is a way to create an abstraction of real life, a way to model objects so that the software is maintainable and manageable. You do this to be able to divide complexity into smaller pieces to make a better overview. E.g. If you are working on an airplane, then you model the necessary pieces only to be able to have a better overview. There is no need to model the outside of the plane, if the software only revolves around the inside of the plane.

This is done by following the three fundamental pillars of OOP:

  1. Encapsulation
  2. Inheritance
  3. Polymorphism

Encapsulation – A way to hide complex functionality from other objects, and that way it is also used to protect data and methods/functions in a class from being accessed. E.g. If a person walks up to an elevator and pushes the button to get to another floor, then that person is shielded from the “physical” things such as cables, cogs etc. and from the “software” things such as algorithms etc.

Inheritance – Enhances code reuse, by letting a programmer inherit from a class, and further build upon this class in own code. E.g. A developer made a class called Animal, and you want to utilize the functionality of this class, but still define your own functionality. You could then inherit from Animal into your own Dog class, and utilize the functionality inside Animal, while further defining your own in the Dog class. This also forms the basis for polymorphism.

Polymorphism - Makes it possible to access objects of different types through one reference variable. This makes that the same method/function name can have different implementations.

This is not necessarily adequate but it is a step in the right direction, and I urge you to read more about the pillars of OOP.

Basic patterns of object design

Now we enter the realm of object design, and it is here we find some basic patterns that assist the developer in creating an application that lends itself to the pillars of OOP, and makes the design strong and maintainable. Please keep in mind that these patterns are the basic of OOP so there’s no magic going on here. I’ll start by listing some of the patterns and follow up with a short explanation and a question you should ask yourself when applying the relevant pattern.

  • Creator
  • Information Expert (Expert)
  • Low Coupling
  • Controller
  • High Cohesion

There are more than mentioned above, but the listed patterns provide the stepping stones for object design. Patterns I won’t mention here are:

  • Polymorphism
  • MVC (Model View Component) *
  • Pure Fabrication
  • Indirection
  • Protected Variations

* When you follow the basic of the mentioned pattern principles, you should end up with the result of the MVC pattern.

When an understanding of the six mentioned patterns are in place, I urge you to read up on the last basic patterns. There might be more basic patterns out there, but the before mentioned are the ones I feel are necessary to understand object design.

The nine patterns listed are all part of the “GRASP Pattern” Which stands for General Responsibility Assignment Software Patterns. I know that it should be called “GRAS Patterns” but the emphasis is on the importance of the developer does “GRASP” the concept and therefore the name.

Creator

The most common thing in software development is the creation of objects, and here there are some principles surrounding who should have the responsibility of creating the object.

Question: Who should be responsible for creating a new instance of the class?

Answer: Let class Two create class One if:

  • Class Two contains Class One or Compositely Aggregates Class One **
  • Class Two “records” Class One
  • Class Two uses Class One to a large extend
  • Class Two contains the initializing data for Class One (Which makes it an Information Expert in regards to creating Class One)

If more bullets fit, go for the first – Contains or Compositely Aggregates.

E.g. when having to create a chess game, which object should create the chess-piece instance, ChessBoard class or Dice class? Well, the ChessBoard and ChessPiece classes have a Compositly Aggregates relationship, and therefore ChessBoard would be best.

** Composition: Imagine that you have a Chess board (Composite) which contains Chess-Pieces (Parts) then the Chess-board (Composite) is always responsible for creation and deletion of its Chess-Pieces (parts). An instance of the part (Chess-Piece) belongs to only one composite (Chess-board) instance at a time. And last but not least, the part (Chess-Piece) must always belong to a composite (Chess-board), meaning that cannot exist a Chess-Piece if there is no Chess-board. This is the core meaning of Composition.

Information Expert

When developing software, there may be thousands of classes that require thousands of responsibilities to be fulfilled. These responsibilities should be assigned to make the code easier to understand, maintainable and lend itself towards code reuse.

Question: What is the principle of assigning responsibilities to objects?

Answer: Assign the responsibility to the class that has the Information necessary to fulfill the responsibility.

The important thing here is to start out by clearly stating the responsibility! E.g. who should be responsible for knowing the total amount of chess-pieces?

Do note that this could involve many classes in order to get the information needed. E.g.

Design Class

Responsibility

Sale

Knows sale total

SalesLineItem

Knows line item subtotal

ProductDescription

Knows product price

To fulfill the responsibility of knowing the sale’s total you need to assign responsibility across several classes, which is also known as partial Information Experts collaboration.

Low Coupling

In development of OO applications it is as mentioned before important to have low dependencies among the objects, so that changes to an object doesn’t effect a long range of objects, and to enhance the ability of code reuse. Low Coupling is a way to “measure” how strong one object is depended (has knowledge of or relies) on other object. High Coupling is very undesirable because it forces local changes due to changes in related classes, makes code reuse almost impossible due to the high degree of dependency, and it makes the code harder to understand. All of this strives directly against the pillars of OOP.

Question: How to support low dependencies, low impact on changes and high code reuse

Answer: Make sure to assign responsibilities so that coupling is low, and always use this principle to consider alternatives.

one

Above image shows BookStoreRegister creating both BookStoreSale and Payment. But in reality there is no need for BookStoreRegister to have any knowledge of Payment.

two

Instead, using the principle of Low Coupling, let BookStoreSale have the knowledge of a payment, and minimize the dependencies among the objects.

Controller

This is a very comprehensive pattern principle, and I will only briefly describe it, but encourage you to read more elsewhere.

A controller - sometimes also referred to as a Facade – is the first object after the UI and is responsible for receiving or handling operations (input events). The overall meaning with this principle lies in, that the GUI classes should not have any knowledge of the data handling classes in the system (and the classes should not have any dependencies on the GUI classes. In short, you should be able to apply new GUI classes to a system without affecting the data handling classes.

Question: What first object after the UI layer should receive and coordinate (forward messages) a system operation?

Answer: The responsibility should be appointed to a class of one of the following choices:

  • It is a model of the overall “system”, or a “root object”.
  • It represents a use case scenario.

Often you would invent a class especially for the purpose, and they are often identified by the name ending on Handler (or Session for web development). (IMAGE THREE)

three

The job of this Controller class is not to handle the events, but merely to foreward the messages to the correct classes. Usually there are several controller classes in a system, and controller classes are often grouped to forward messages to multiple objects at a time. Just be aware of bloated controllers!

When talking about controller pattern principles, there are some things you should dig deeper into that I will not go into here:

  • Boundary objects
  • Entity objects
  • Command patterns
  • Pure Fabrication

High Cohesion

When designing objects, High Cohesion is a measure of how focused the responsibilities are within an object (keep it simple stupid). A class shouldn’t do too many unrelated things, or do too much work! This would yield low cohesion, which makes the classes; hard to understand, hard to reuse, hard to maintain, and make them dependent and highly affected to changes elsewhere in the system.

Question: How to keep objects focused, understandable and maintainable?

Answer: Assign responsibility to honor High Cohesion.

This pattern principle is highly affected by the before mentioned patterns, but in general the aim should be on yielding Low Coupling and High Cohesion when designing these objects.

The patterns listed in this blog post are only a small corner of the heart of OOP. But it should give the basic knowledge of object design. This blog post is only intended as an appetizer towards OOP and object design, and does not provide full justice to the subject. Please use this post as a short appetizer and go explore more on this fascinating subject.

I can recommend this book for reading - Object Oriented Software Engineering Using UML, Patterns, and Java - written by Bernd Bruegge & Allen H. Dutoit.

Currently rated 1.5 by 4 people

  • Currently 1.5/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Posted by: AllanJP
Posted on: 11/3/2010 at 3:36 PM
Categories: Programming | Basics
Actions: E-mail | Kick it! | DZone it! | del.icio.us
Post Information: Permalink | Comments (1) | Post RSSRSS comment feed

Open House event for DTU students

!cid_image001_jpg@01C9E9E0

microsoft-logo

20-04-2010 at Microsoft Development Center Copenhagen, Frydenlunds Allé 6, Vedbæk 2950

Are you studying at DTU? Do you want to know what we are developing at Microsoft Development Center Copenhagen and which career opportunities we can offer you as a student or as a graduate? Then visit our Open House Event on April 20 from 15.30 – 18.00. We have lots of exciting stuff on the agenda and there will also be time for pizza, networking and fun coding challenges. First prize in the coding challenge competition is an XBOX, but who knows, you might even end up with a job offer.

To make it easy for you to visit us, we have booked a bus that will pick you up at the parking lot in front of Building 101 at DTU at 15.00 and take you back at 18.00.

We look forward to seeing you on April 20!

Sign up here

Program

15.30 Introduction to Microsoft and Microsoft Development Center Copenhagen, Charlotte Mark, Managing Director

- These are the products we develop, Kim Ibfelt, Director of Program Management 
- Development methods, Michael Nielsen, Director of Engineering

16.20 Meet Henrik Metzger, Software Development Engineer

16.30 Meet Aida Seifi Labrosse, Software Development Engineer in Test

16.40 What I look for in a candidate, Christian Heide Damm, Senior Development Lead

16.55 Career opportunities at Microsoft, Scott Simmons, Staffing Lead

17.10 Microsoft Student Partner Program, Martin Esmann, Academic Developer Evangelist

17.20 Closing, networking, pizza and coding challenges

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Posted by: AllanJP
Posted on: 3/26/2010 at 10:18 AM
Categories: Programming | Velkommen | Microsoft
Actions: E-mail | Kick it! | DZone it! | del.icio.us
Post Information: Permalink | Comments (0) | Post RSSRSS comment feed

Attending Tech ED Berlin 2009

TechED

“All my bags are packed, I’m ready to go……”

I’m am very exited to get to Tech ED Berlin 2009 (which is now sold out!). I’ve been trying to wrap my head around what track and sessions I should attend, because there are MANY! to chose from. As a person I believe it’s importent to focus on the fact that this is a unique opportunity to evolve your knowledge. Therefore I have chosen to expand my choice of sessions to not just include areas of immediate focus, but to also include areas of common interest.

I spend a few hours on the track & sessions page, figuring out pros and cons on sessions that unfortunately collided on day and hours. But I think I hit an amazing agenda for the entire week:

TechEd Europe Keynote - Welcome to the New Efficiency
Enabling Rich Business Clients with Windows Presentation Foundation
Top 10 Design Mistakes Made By Web Developers and How to Avoid Them
Windows 7 Demo Mania
Embedding Windows 7 into Devices
Tips and Tricks for Building High Performance Web Applications and Sites
Pumping Iron: Dynamic Languages on the Microsoft .NET Framework
F# for Parallel and Asynchronous Programming
Microsoft Visual Studio Team System 2010 Team Foundation Server: Become Productive in 30 Minutes
Unit Testing Best Practices
The Windows API Code Pack: How Managed Code Developers Can Easily Access Exciting New Windows Vista and Windows 7 Features
Windows 7 and Windows Server 2008 R2 Kernel Changes (*PDC at TechEd)
Windows 7: The Power Management Workout!
Building High Performance Parallel Software
Windows Embedded: "Demos Only"
Parallel Computing for Managed Developers
Achieve new levels of desktop optimization with Intel Core™ 2 processors with vPro™ technology and Windows* 7
Case of the Unexplained... Windows Troubleshooting with Mark Russinovich

The one session that I look really forward to is Windows 7 and Windows Server 2008 R2 Kernel Changes!! I’ve been following the discussion on the internet, and following the videos from Channel 9 on Windows 7.

The official note on the session leaves me with the impression that this is going to be really good:

“This session goes beneath the hood of Windows 7 and Windows Server 2008 R2 to describe and demonstrate the key changes in the kernel. Topics include: scalability improvements such as removal of the global scheduler lock, support for more than 64 logical processors, and user mode scheduling, virtual service accounts, core parking and timer coalescing for power efficiency, trigger-started services, core architecture changes to modularize Windows ("Minwin") and more.”

And the embedded part with demo’s are also something to be looking forward to:

“This demo-packed session presents all sorts of devices, tools, and technologies used in today's and tomorrow's embedded projects. If you want to learn how Windows Embedded can be used to build stunning devices or if you are just a geek, you can't miss this session.”

And yes, I’m a geek!

I’m really looking forward to this mix of Desktop, embedded, web technology and architechture sessions. And not forgetting all the demo presentations that makes this Tech ED a must-see event.

Appart from all of these sessions, I will be on the lookout for the expo areas, where I will get a chance to have a look at what all other developers are doing right now.

I’m also loking forward to meeting all the other Microsoft Student Partners from all over the world. And this will ofcourse introduce them to my network, and me to theirs.

If you find the subjects listet above interesting, then I will attempt to blog on every single one of them, and hopefully provide you with awesome pictures from the whole event. If you find subjects of interests missing in my list, I will suggest that you have a look at some of the other Microsoft Student Partner blogs. We are well represented at the Tech ED event, and maybe they will attend more convenient subjects. You can find links to there blogs on the left column.

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Posted by: AllanJP
Posted on: 10/31/2009 at 5:14 PM
Tags:
Categories: C# | Embedded | F# | FMOD | IronPython | OS | Programming | Tech ED | Velkommen | Windows 7
Actions: E-mail | Kick it! | DZone it! | del.icio.us
Post Information: Permalink | Comments (0) | Post RSSRSS comment feed

Win a book on IronPython or F#

Here is a little contest that will run for 14 days (until the 29-09-2009), where every developer should have a chance of winning!

The Contest has ended, and the winner was Yoni Holman! Congratulations!

I?ve created 7 questions, in different programming languages such as C#, F#, Ironpython, C++, Java and off course the well known and liked true or false. The questions are designed to give a number of points, where the maximum number of points given can be read in the text of the assignment. The rules are simple, the one with the highest score on points, will win. Points will be given for correctness and effort. An assignment might give 6 point, but if not entirely correct, it will be given some points for effort.

What can you win?

The winner gets Office 2007 Student version, and gets to choose one of two books ? Foundation of F# or IronPython in Action - and the runner-up gets the book that the winner did not choose.

FSharp ironpythoninaction OFF2007STUKEY

What to do now?

If you want to try out for the books, all you have to do is:

  • Leave a comment on this blog-post (in case that when you submit, and your assignment gets in my spam-mail-box, I?ll know to look for it here if its not in my usual mailbox.
  • Submit your answers (as a txt file) to my mail address (ajp at clug.dk)
  • Everyone is allowed to solve all the questions (if you can), or just some of them.
  • When mailing me, please leave ? if you have ? your Twitter name, and I will also post the winner and runner-up on twitter (if the winner and runner-up has a Twitter name).

Here are the questions

Question number 1.

6 point

The following code compiles and runs without problems, but everything is not as it should be. When a user enters the input as shown below, what is the output? And more important, why is the output as it is?

#include <iostream>

using namespace std;

char string1[2]; char string2[2]; char string3[7]; char string4[7];  char string5[8];

int main (){
    cout<< "\n Read 1. text (length 2)";
    cin>> string1;
    cout<< "\n Read 2. text (length 2)";
    cin>> string2;
    cout<< "\n Read 3. text (length 7)";
    cin>> string3;
    cout<< "\n Read 4. text (length 7)";
    cin>> string4;
    cout<< "\n Read 5. text (length 8)";
    cin>> string5;
    cout << "\n 1.: "<< string1;
    cout << "\n 2.: "<< string2;
    cout << "\n 3.: "<< string3;
    cout << "\n 4.: "<< string4;
    cout << "\n 5.: "<< string5;
    return 0;
}

Read 1. text (length 2) - F#
Read 2. text (length 2) - C#
Read 3. text (length 7) - ASP.NET
Read 4. text (length 7) - IronRuby
Read 5. text (length 8) ? IronPython

Answer:

1. F#C#ASP.NETIronRubIronPython
2. C#ASP.NETIronRubIronPython
3. ASP.NETIronRubIronPython
4. IronRubIronPython
5. IronPython

In C++ the strings are null terminated. This means that space must be preserved for null termination character. In the assignment above, the null character is overwritten, and therefor the output is as shown.

This example does have some issues regarding compiler dependencies, and yes this was also part of the assignment ;-)

Question number 2.

9 point.

The following is an application made with the .NET Micro Framework, but the code is missing two lines! The missing parts are an Output port, and an Input port. Implement these two line to complete the code.

using System;
using Microsoft.SPOT;
using Microsoft.SPOT.Hardware;

namespace MicroFramework
{
   public class Light
   {
     public static void Main()
     {
       Cpu.Pin pin = Cpu.Pin.GPIO_Pin1;
       Cpu.Pin switch = Cpu.Pin.GPIO_Pin2;
       //missing line
       //missing line

       while (true)
       {
         YourOutputPort.Write(YourInputPort.Read());
       }
      }
     }
}

Answer:

OutputPort YourOutputPort = new OutputPort(pin, false);
InputPort YourInputPort = new InputPort(switch, false);

Question number 3.

3 point.

The following code is F#, and it represents an array. Finish the code, so that every item in the array is printed out to the screen.

#light
let colors = [| "Blue"; "Green"; "Yellow"; "Black"; "White"; "Red"; |]

//iterate over the array, and print out the items within the array.

Answer (There are multiple ways of doing this) :

for color in colors do
    print_endline color

Question number 4.

4 point.

The following code is an array written in C#. create a LINQ query that selects the items that are less than 15 and do this:

  1. Using standard LINQ query
  2. Without the use of keyword "var" (without implicit typing).

int[] numbers = {5, 2, 10, 12, 16, 35, 20, 100};

//Create query

//iterate and print out items

Answer:

1.
var query = from i in numbers where i < 15 select i;

foreach(var i in query)
  Console.WriteLine("Number: {0}", i);

2.  
IEnumerable<int> query = from i in numbers where i < 15 select i;
foreach(int i in query)
  Console.WriteLine("Number: {0}", i);

Question number 5.

6 point.

Implement a function in IronPython that takes one parameter, and calculates and returns the Fibonacci series. Then call your function with the number 200.
shown here in pseudocode:

FibonacciFunction(aNumber)

calculate fibonacci

return number

call function
print output

Answer:

def fibonacci(number):
        result = []
        a, b = 0, 1
        while b < number:
             result.append(b)
             a, b = b, a+b
        return result

fib = fibonacci(200)   
fib

Question number 6.

8 point.

The following code is in Java, and it is a sorting algorithm. Two lines are missing, and you are to implement the missing lines.

public class HeapSort
{

    public void heapSort (int [] A)
    {
        printArray(A);
        makeHeap(A);
        printArray(A);
        for (int i = A.length-1;i >0 ;i--)
        {           
            int temp =0;
            temp = A[i];
            //Line missing
            A[0] = temp;
            reheap(A,0, i-1);
            printArray(A);
        }
    }
    public void makeHeap(int [] A)
    {
        for (int j = ((A.length / 2)-1);j>=0;j--)
        {
            reheap(A, j, A.length-1);
        }
    }
    public void reheap(int [] A, int current, int last)
    {
        int leftChild = 2* current +1;
        int rightChild = 2* current +2;
        int largest;
        int tempA=0;
        if (leftChild <= last && A[leftChild] > A[current])
        {
            largest = leftChild;
        }
        else
        {
            //Line missing
        }
        if (rightChild <= last && A[rightChild] > A[largest])
        {
            largest = rightChild;
        }
        if (largest != current)
        {
            tempA = A[current];
            A[current] = A[largest];
            A[largest] = tempA;
            reheap (A , largest, last);
        }
    }
    public void printArray(int [] A)
    {
        System.out.print("Array: ");
        for (int i = 0; i < A.length ; i++)
        {
            System.out.print( A[i] + ", ");
        }
        System.out.println("\n");
    }
    public static void main(String[] args)
    {
        int A [] = {10,23,75,24,98,87,27,11,34,28,17,13,31,37};
        HeapSort heap = new HeapSort();
        heap.heapSort(A);

    }

}

Answer:

A[i] = A[0];
largest = current;

Question 7.

Each correct answer will give 1 point each. (max point is 21).

In this assignment you should answer "true" or "false" to the following questions:

  1. IronPython is the .NET version of Python.
  2. IronPython is a functional programming language.
  3. There is nothing called IronRuby from Microsoft.
  4. IronPython does not work in a web browser.
  5. IronPython is a dynamic programming language.
  6. IronPython can interact with the C# programming language.
  7. IronPython is an OpenSource language.
  8. F# is a dynamic programming language.
  9. F# does not work with WPF (Windows Presentation Foundation).
  10. F# only works with math and formulas.
  11. F# works with Windows Forms.
  12. F# only runs on Windows Computers.
  13. F# is an OpenSource language.
  14. C# is the only programming language in .NET family.
  15. C# can only be used on Windows computers.
  16. The .NET MicroFramework is used for embedded systems.
  17. ASP.NET is a Java version of PHP.
  18. ASP.NET can only be used on Windows computers.
  19. ASP.NET, C#, F# and Silverlight all run on Linux.
  20. Moonlight on Linux is the same as C# on Windows.
  21. Mono is the same as F# on Windows.
Answer:

1. true
2. false
3. false
4. false
5. true
6. true
7. true
8. true
9. false
10. false
11. true
12. false
13. true
14. false
15. false
16. true
17. false
18. false
19. true
20. false
21. false

The text in small print

Everyone from every country is allowed to participate in this contest. The winner and runner-up will be notified by me personally, and I will personally send the books to their home address. If the winner and runner-up will allow it, their names will be posted on this website after I have talked to them.

All I can say now is good luck, and I hope you find this fun :-)

Currently rated 3.0 by 2 people

  • Currently 3/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Posted by: AllanJP
Posted on: 9/15/2009 at 6:48 AM
Categories: C# | IronPython | Programming | F# | Contest
Actions: E-mail | Kick it! | DZone it! | del.icio.us
Post Information: Permalink | Comments (9) | Post RSSRSS comment feed

IronPython is TechTalk

Get an introduction to Python on the .NET Platform, from Harry Pierson.

At the Microsoft development center copenhagen... (sorry guys, this one is in Denmark)

About Harry Pierson
Harry Pierson is a Senior Program Manager on the Visual Studio Languages team, primarily focused on IronPython. A ten year Microsoft veteran, Harry has worked all over the company from Microsoft Consulting Services and Architecture Evangelism in the field to being an architect in Microsoft IT. He has been writing his blog DevHawk (http://devhawk.net) for just over six years and has written articles for MSDN and CoDe Magazines.

He will be talking at variuos universities around Denmark, I just don't have the dates yet, but for more information look here http://www.computerworld.dk/blog/studblog/1931?cid=6&a=cid&i=6&o=1&pos=2

 

 

 

Currently rated 3.0 by 1 people

  • Currently 3/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Posted by: AllanJP
Posted on: 8/24/2009 at 7:04 AM
Tags:
Categories: Programming
Actions: E-mail | Kick it! | DZone it! | del.icio.us
Post Information: Permalink | Comments (1) | Post RSSRSS comment feed