Archive for January, 2011

Fame?

I don’t know if you remember me mentioning last week I was filmed in preparation for the Visual COBOL 2010 R3 launch today. Well you can now see me in all my … errr… something! I realise that walking about a kilometre rather briskly in 80% Sydney humidity and being told to sit down and be filmed immediately might make me look a little damp … No, honestly, I’m not breaking out in a cold sweat and boy I wish I’d had time to squeeze in that haircut!  Here I am:

 

Check out the whole launch here

The meek shall inherit?

Sorry for the pause … Making a living can interfere with life at times.

Every COBOL programmer out there knows that the most important thing about Object Oriented Programming is inheritance, right?  To us old procedural programmer’s it just sounds so cool! I remember when I first started reading about inheritance in OOP I thought it was the answer to most of our programming problems.  Increasing complexity of existing code could be handled by simply inheriting code already written without breaking it. Turns out I was wrong … Err, mostly!

By and large it would be a GOOD IDEA if you didn’t design new classes that inherit the classes that you write. Note the qualifications there: by and large as well as that you write! There will be times that you might have good reason to inherit but, resist the urge if you can! You will build a far more flexible and far less complex system if you do. The other qualification was that you write … You will inherit .NET Framework classes all the time. That was what they were designed for, by experts. They provide functionality that it would be foolish to re-write. If you restrict yourself to this discipline you will reduce inheritance nesting to a minimum. Your code will be more performant, predictable and easier to debug. There is nothing more confusing than trying to work out where you are in an inheritance hierarchy that is over head height!

O.K. Now I’ve said what you shouldn’t do, what the hell do you do? You certainly don’t re-write the same functions everywhere. In the .NET world there are two basic methods:  use decomposition and/or interfaces. I will come to interface programming in .NET soon. Today is about decomposition.

Let’s start thinking on the basic school system we’re working on. It’s time to introduce Teachers. On first flush you might think a teacher is just a type of Person that we’ve already defined, so let’s just inherit from the Person class. Wait a minute though … What about the Teachers who are also Parents? What about the Teacher who also is Head of English or also does some school maintenance? Remember under .NET a class can only inherit from one class …

Well, first and foremost the Teacher is a Person who has other attributes or properties, like Position and a collection of Classes they teach (we’ll get to collections and a neat feature called Generics in the next post, but you’ll see a little of them in the code I’ve put together for this post). If we look at the Teacher class:

class-id School.Data.Teacher public.

working-storage section.

01  Teacher-Id       binary-long                        as "Id"             
                     public property with no set.
01  Teacher-Person   type School.Data.Person            as "Person"         
                     public property with no set.
01  Teacher-Position string                             as "Position"       
                     public property with no set.
01  Teacher-Classes  type School.Data.ClassCollection   as "ClassesTaught"  
                     public property with no set.

method-id New.
local-storage section.
procedure division using by value teacherId        as binary-long
                                  teacherPerson    as type 
                                      School.Data.Person
                                  teacherPosition  as string
                                  teacherClasses   as type 
                                      School.Data.ClassCollection.
                                  
    Set Teacher-Id          to teacherId.      
    Set Teacher-Person      to teacherPerson.  
    Set Teacher-Position    to teacherPosition.
    Set Teacher-Classes     to teacherClasses.                        

    goback.
end method.

method-id ToString public override.

procedure division returning returnString as string.

Set returnString to String::Concat(Teacher-Position ", " 
                 Teacher-Person::Title " " Teacher-Person::LastName).

end method.

end class.

You can see we have decomposed a Teacher into an Id, a Person, their Position and their ClassesTaught. Simple to write and simple to understand! We can enhance the underlying logic in the Person class without breaking the Teacher class and similarly do the same for the Teacher class. We can create Unit Tests for the Person and Teacher classes (using a technique called mocking) independent of each other and be confident in the functionality of each without worrying about dependencies.

If you are interested in some of the finer, more technical points of the argument of choosing composition over inheritance you might like to check out this article at StackOverflow (an excellent source of .NET wisdom) or perhaps this article at Wikipedia.

You can have a squizz at the code built so far here.

Horses

Given today’s my daughter’s 9th birthday and on school holidays today she’s getting a treat and (no self interest here) my son and I are taking her to see Tron Legacy at our local cinema. So sorry my planned posting will be appearing a little later as I have to get some work done beforehand … Instead, I thought you might all appreciate some more Eddie Izzard:

Method in my madness?

More like madness in my methods I suspect …

Let’s take a look at the code that acts on our object data in the Person class as it now stands:

method-id "new" public.
local-storage section.
procedure division using by value   personId      as binary-long
                                    lastName      as string
                                    firstName     as string
                                    middleNames   as string
                                    personTitle   as string
                                    birthDate     as type DateTime
                                    personAddress as type 
                                                     School.Data.Address
                                    ifMale        as condition-value.
                                    
    Set Person-Id       to personId.    
    Set Last-Name       to lastName.    
    Set First-Name      to firstName.   
    Set Middle-Names    to middleNames. 
    Set Person-Title    to personTitle. 
    Set Birth-Date      to birthDate.   
    Set Person-Address  to personAddress. 
    Set Person-Male     to ifMale.

    goback.
    
end method.

method-id ToString override.

procedure division returning returnString as string.

Set returnString to String::Concat(Last-Name::ToUpper() ", " 
                                   First-Name " " Middle-Names)

end method.    

We’ll ignore the property methods we discussed recently.

First off, for non-static classes (we’ll get to those soon) every class must have a new method to create new objects or new object instances. This method is and can only be executed once on object creation and is used commonly to initialise the object data and do setup that allows the object to be interacted with. You may have multiple methods called “new” that have different signatures, that is they must be called with different parameters. Thus we might have a new method that infers title from sex and age like:

method-id "new" public.
local-storage section.
procedure division using by value   personId      as binary-long
                                    lastName      as string
                                    firstName     as string
                                    middleNames   as string
                                    birthDate     as type DateTime
                                    personAddress as type 
                                                     School.Data.Address
                                    ifMale        as condition-value.
                                    
    Set Person-Id       to personId.    
    Set Last-Name       to lastName.    
    Set First-Name      to firstName.   
    Set Middle-Names    to middleNames. 
    Set Birth-Date      to birthDate.   
    Set Person-Address  to personAddress. 
    Set Person-Male     to ifMale.
    
    *> If adding 14 years to the person’s birth date is later 
    *> than todays date then the person is under 14 years old
    
    If  birthDate::AddYears(14) > type System.DateTime::Today
        If  Person-Male
            Set Person-Title to "Master"
        Else
            Set Person-Title to "Miss"               
        End-If
    Else
        If  Person-Male
            Set Person-Title to "Mr."
        Else
            Set Person-Title to "Ms."               
        End-If
    End-If.
    
    goback.
    
end method.

Now we can create a valid new instance of Person without supplying the person’s title. I could of course have made the Title set property visible as well but I’ve been fighting hard to make this an immutable class (even though from a design point of view it doesn’t really make sense) so I’m going to stick with it for the time being.

I’m going to go on with one of my bugbears here:

Always override the ToString method on your non-static classes!!!

 

You will notice I have an override in my both my Person and Address classes. If I comment out the ToString override in the Person class and fire up the debugger, let’s see what an instance of the Person class looks like:

ToString1

 

Huh??? “School.Data.Person??? Not very meaningful is it? Try debugging a complex class comprising over 10 other object instances and it becomes increasingly difficult to quickly identify what the hell is going on. You might also notice that my careful naming of my variable to aPerson has been converted to APERSON … COBOL by default is a case-insensitive language. That’s why I litter my public interface with  as “etc” everywhere. Mixed casing is just easier to understand. Full-stop. End-of-argument.

Look what the variable looks like when I un-comment out the code (lovely grammar that, isn’t it!):

ToString2

That’s just from hovering over the variable. If I do a Quickwatch, I get:

ToString3

That’s just a lot easier to quickly take in in a complicated debugging session, especially where you might have an array or collection of many Person instances. An added benefit from all of this is that when you used the good old COBOL DISPLAY verb on an object instance, the object’s ToString method is invoked by default:

ToString4

Look’s a let better than:

ToString5

 

Doesn’t it? The code to display the instances in both cases was just:

Display anAddress.
Display aPerson " and " anotherPerson.

Simple, isn’t it? We’ll get onto some of the other useful things you can do with the ToString method.

Another little aside on this commenting and uncommenting out code … Visual Studio 2010 has two really handy buttons for performing this with a couple of clicks. Select the code you want to comment or uncomment and just click the button:

CommentUncomment

Temporarily off air yesterday …

Sorry for leaving you all hanging yesterday waiting for a new gem … I’d been called to Sydney to participate in a film shoot for a product launch later this month. As the first time I’ve done anything like this, it was certainly an interesting experience. 

Leaving Coffs Harbour airport on a very wet morning, I flew to a warm, humid Sydney to join Celina at Boomerang Productions in Chippendale, not knowing what to expect. For the next four hours I answered the same four questions in increasingly concise terms and with varying degrees of fluency from varying angles … You would think after the fifth time of saying the same sentence you could pronounce the name of your own company correctly, wouldn’t you? It can be a real challenge to shave a rather complex answer of nuance and still answer the question. I came in prepared with what I thought were interesting and complete answers to some interesting questions and had everything shaved back to what will be about two minutes. Lord knows what it will come over like! Celina’s team were fantastic: friendly patient and very professional. You can be the judge on 20th Jan 2011!

After four hours in the studio, Celina dropped me at Sydney Domestic Airport for what I expected to be an uneventful flight back to Coffs … and it was uneventful … until we attempted to land. The very professional pilot made three attempts (we circled Coffs for over an hour). Rain and heavy wind made the airstrip almost invisible. On the fourth we landed and amazingly smoothly at that. Just as well, too! If it hadn’t happened we would have been returning south to either Newcastle or Sydney. After a fairly wild drive home through horizontal rain, I arrived two hours later than planned and will be watching the sky today as the forecasters are predicting possible flooding and we made need diesel for the backup generator given we’re unlikely to see the sun for a week!

Friday …

Everyone needs a pause to gather their thoughts so in the meantime … Enjoy:

Properties or fields?

I finished yesterday discussing how you specify data (sometimes referred to as object state) in objects leading into todays discussion.

Fields are just any old object (data) that is held in either class or instance data. In COBOL terms(err, broadly), Working-Storage or Local-Storage. They can be private or public. Now, private fields are all the rage … Your code will and should contain private fields like:

01 If-Person-Male   condition-value private.
01 Person-Sex       string          private.

 

A quick note here, there are a range of built in types in Visual COBOL 2010.  condition-value is a Boolean, with values either true or false, a simple 88 level if you like.  string is the .NET System.String type.  For a full list of built-in types click here.

Using public fields however is a bit problematic because they give other code the right to alter data in your objects. Your object data can then become inconsistent or corrupt, leading to unpredictable behaviour.  Fields, to use the magic OO buzz-word, break encapsulation. For a quick user-friendly definition of encapsulation check out here,  but Wikipedia provides a more complete description.

Properties are a way for you to expose your object data in a controlled way. Properties are essentially, under the covers, a .NET shortcut to two methods or functions: get_propertyname and set_propertyname. So:

01 Person-Id        binary-long              as "Id"             
                    public property with no set.

will generate two methods: get_Id and set_Id that return an integer (binary long) and take as parameter an integer respectively.  The interesting additional point about this statement is the with no set. This means that the class does not expose the set method for the property as public. This property can be viewed by external code, but only the objects internal methods can alter this property’s value. If you make all of a class’s public property’s only have public get methods and go one step further by not allowing the object to change those properties other than at the point of creation, then the object is described as immutable. Immutable objects are a good idea as they always guaranteed to be in a self-consistent state and are inherently thread-safe, i.e. they can be safely accessed by multiple threads after created. Not every class can be immutable but try … It will pay off in the long run!

The neat thing about property’s is that they can make behaviour look like data and transform a view of data to another type.  Let’s look at an example by adding to the Working-Storage:

01 Person-Male      condition-value          as "Male"           
                    public property with no set.

Now if we add lower in the code (The complete code for viewing in context can be found here):

method-id get property Sex.
procedure division returning Return-Value as string.
    
    If  Person-Male
        Set Return-Value to "Male"
    Else
        Set Return-Value to "Female"
    End-If.

end method.

method-id get property Female.
procedure division returning Return-Value as condition-value.
    
    If  Person-Male
        Set Return-Value to false
    Else
        Set Return-Value to true
    End-If.

end method.

We’ve now defined two extra get property’s Sex and Female. Sex returns a string based on the Male (Person-Male) property: “Male” if it is true or “Female” if it is not. We could take it further and return “Boy” or “Girl” if the person was younger than 12 years of age. Neat, eh?! The Female property is effectively the inverse of the Male property as (by and large!) you can’t be both male and female. If we weren’t trying to make our Person class immutable we could provide a set method for Female like:

method-id set property Female.
procedure division using by value Input-Value as condition-value.
    
    If  Input-Value
        Set Person-Male to false
    Else
        Set Person-Male to true
    End-If.

end method.

 

We can thus ensure that the internal state of the Person object is entirely consistent.

A final point about property’s … If you choose to use public property’s instead of public fields, your class will automatically support data binding. We’ll get on to data binding later in this series, but believe me – you want it!