Strictly Private: Abstraction and the importance of ‘privacy’

by Paul Curzon, Queen Mary University of London

Celebrities want fame but they also want privacy. They want some things they do known to the public, but not everything. It turns out that privacy is important when writing good code too, and in object-oriented programming the personal body guards that provide it are built-in.

StrictlyLeaderboard

In the last blog post we explored the basics of object-oriented programming by looking at how to make game show judges for the Strictly Come Dancing of the future. Object-oriented programming is centred on the idea of abstraction: hiding information to make a problem (here coding) easier. In particular, it is built around the concept of an abstract data type. You create new types – collections of related values – for your program to use,  but hide their complicated inner details, their representation. We will illustrate the ideas by continuing our Strictly theme and look at how we might keep track of contestants’ scores using objects, and in doing so find out what abstract data types are, and what they give us.

We are going to think of Strictly Come Dancing contestants as objects just as we did with judges. We will create a new type of Contestant for our programs to use. We will then be able to create new Contestants, and record and change their details. However, we will do it in a special way, making those inner details private and only accessible by the privileged parts of our code (a bit like the way real celebrities’ lives are protected from the masses).

Properties of a Strictly contestant

AlexandraGorkaWe need to decide how to represent a contestant. First we ask what properties – what attributes – we need to record about contestants. How will we represent them? In Strictly contestants always come in pairs: a celebrity and a professional, so we will group them together and treat the contestant as the pair. Each person in the pair has a name. They are also given jointly, after they dance, a score from the judges. To keep things simple we will ignore the audience vote. We will also assume they just dance once for each show. Their score is just made up of four individual judge’s scores, but it is the total that matters and appears in the leader board. So that is what we will record. The properties of a contestant can be defined (in a simple pseudocode rather than a real language) as:

DESCRIPTION OF A Contestant:
    CelebrityName: String
    ProfessionalName: String
    TotalScore: integer

CelebrityName, ProfessionalName and TotalScore are the instance variables of the class we are defining. They hold the property values. This says a contestant is defined by the name of the celebrity, the name of their paired professional dancer and their score, which is an integer.

Keep it private

Now we do something that seems a bit perverse at first, but is the key to the power of objects. We mark all those instance variables as being private! They cannot be seen outside the Contestant class we are defining. The representation we just carefully created will be hidden.

DESCRIPTION OF A Contestant:
    PRIVATE CelebrityName: String
    PRIVATE ProfessionalName: String
    PRIVATE TotalScore: integer

Privacy is important to the talent of shows like this! Of course, this form of privacy is nothing to do with the stars’ private lives. Privacy in OOP is all about making the program easier to change in the future, as we will see. What marking them as private specifically means is that the rest of the program (outside the description of a Contestant we are defining) can not see any of these attributes of a contestant directly. We have set up a curtain around the representation of the contestants. We will only allow it to be accessed in carefully controlled ways via methods. In real life you can ask a star for an autograph or a selfie but they won’t go down the pub with you. Their behaviour is controlled. It is as though they come with personal bodyguards that keep all unwelcome advances away – very important in show business it seems for stars, but also for code. Access is strictly controlled to variables marked as PRIVATE. In practice, in compiled languages as least, it is the compiler that does all the checking – it ensures nothing marked PRIVATE is mentioned anywhere it shouldn’t be in the code.

Accessing marks

How then do we access the names and score? We are going to code a set of behaviours – a set of methods – whose job will be to allow those properties to be read and modified, but only in the controlled ways they define. These methods take the place of bodyguards for the code.

For example, we do not want the total score to be set arbitrarily. It MUST always be just the result of adding the four separate judges scores together. Therefore we will write a single method to do this and then enforce that it is used. It will be given the four different judges scores and add them up. No other way will be given to change the total.

So the behaviour we must define for a contestant pair gaining a score is that given four marks, which we will refer to as judge1Mark, judge2Mark, and so on, their sum is recorded. We define a method to do this as part of the description of a Contestant.

TO SetContestantScore:
    GIVEN judge1Mark AND judge2Mark AND judge3Mark AND judge4Mark:
        TotalScore = judge1Mark + judge2Mark + judge3Mark + judge4Mark

Whereas the actual property, TotalScore is private and so cannot be used directly in the rest of the program (just here), the method SetContestantScore is public. It is visible and can be used elsewhere. By setting this method as the only way TotalScore is accessed, we ensure it can ONLY by set by combining four judge’s marks together correctly. This protects the program from bugs caused by programmers getting confused or misunderstanding things elsewhere in the code.

We don’t want to just be able to set the score, we also need a way to access that score too, so it can be displayed on the leader board, for example. We again give a method to access it. By providing this method, we show we are happy for it to be accessed.

TO GetContestantScore:
         RETURN TotalScore

It just accesses the score from the Contestant object and returns it. This seems a little odd at first. Why use a method to do that? As we will see, accessing the values of a type through methods like this makes the program easier to change with less risk of mistakes being introduced. It is a good thing to do even in simple situations like this, just in case we later want to change them.

What’s your name?

What about the contestant’s names? We do the same sort of thing. We want them to be set only when the pairs are put together at the start (in real life with cries of “You were the partner I always wanted”). After being set they should not be changed, so we won’t give a way to change them. We do not want a bug elsewhere to be able to mess with their names so we make it impossible to do. We can build the setting of names in to a method called CreateContestant, say.

TO CreateContestant GIVEN celeb AND pro:
    CelebrityName = celeb
    ProfessionalName = pro
    TotalScore = 0;

We store a given celebrity name (celeb) and a given Pro’s name (pro) in to the corresponding instance variables of the object. We also set the TotalScore Instance variable to 0 as at the point they are created they have no score.

Methods like this that, when executed, create and initialise an actual object of a given class are called constructors. In many languages constructors are by convention called the same name as the type and automatically called as part of creating a new object, so we will do the same and change the name. Actually what they do instead of the above is something more like:

TO CREATE A NEW Contestant GIVEN celeb AND pro: 
    CREATE A NEW OBJECT WITH SPACE FOR THE ATTRIBUTES NAMED ABOVE
    THEN DO THE FOLLOWING
        CelebrityName = celeb
        ProfessionalName = pro
        TotalScore = 0;

We will use this version, called Contestant, that spells out that it creates an object of type Contestant first before setting the values, just to emphasise that constructors are a more complicated kind of method.

Let’s suppose once formed we ALWAYS want to refer to the celebrity-professional couple by combining the names, as in “Alexandra and Gorka”, with the celebrity first. We can enforce this by making the method that returns the name always return it in that form. Again if that is the only method we write, any code using our class can’t get it wrong. We glue the two names together with “ and “ between to make the form as above.

TO GetContestantName:
    RETURN (CelebrityName + “ and “ + ProfessionalName)

Abstract Data Types

At the start we talked about an abstract data type. Where does that come in? An abstract data type is a type that is defined by the things that can be done on values of that type. We have just defined what it means to be a contestant in exactly that way. We have specified that a value – an object – of type Contestant (as seen by the rest of the program) has four behaviours, and only four behaviours. You can

  • Create a contestant by providing the name of the celebrity and of the professional
  • Get the name of the contestant as a couple
  • Set a Contestant’s score as the total of four judge’s scores,
  • Get a Contestant’s score

You can do nothing else with a Contestant as all its inner details are hidden and inaccessible to any code using the class.

Our description above is a description of an abstract data type because it doesn’t say anything about how the names and scores are stored, and because there is nothing else you can do to manipulate the values other than those four actions.

If we put the parts together we get our whole class description for a contestant – the blueprint for a Contestant that can be used to create and manipulate them elsewhere in the program,

DESCRIPTION OF A Contestant:
  PRIVATE CelebrityName: String
  PRIVATE ProfessionalName: String
  PRIVATE TotalScore: integer

  TO CreateContestant GIVEN celeb AND pro:
      CelebrityName = celeb
      ProfessionalName = pro
      TotalScore = 0;

  TO SetContestantScore
    GIVEN judge1Mark AND judge2Mark AND judge3Mark AND judge4Mark:
      TotalScore = judge1Mark + judge2Mark + judge3Mark + judge4Mark

  TO GetContestantScore:
      RETURN TotalScore

  TO GetContestantName:
      RETURN (CelebrityName + “ and “ + ProfessionalName)

Using Contestants

So we have now created a new type of Contestant. How do we use it? We can now write code, for example, to create pairs of contestants as needed:

Pair1 IS A NEW Contestant USING “Alexandra” , “Gorka”

This is using our class blueprint to create our first object of type Contestant. We give it the names of “Alexandra”  and “Gorka”. It calls our constructor, our special method used to make Contestants, creates an empty blank of the object and then sets the CelebrityName to be “Alexandra” and the  ProfessionalName to be “Gorka”. It also sets their TotalScore to 0. Notice here we do not actually refer to any of those variable names. Writing the rest of the code we can forget about all that detail. We do not want or need to know the actual representation. We create more pairs as needed

Pair2 IS A NEW Contestant USING “Aston” , “Janette”
Pair3 IS A NEW Contestant USING “Jonnie“, “Oti”
Pair4 IS A NEW Contestant USING “Susan“, “Kevin”

and so on.

For each pair the program will also need to give them their marks as allocated by the judges eg by calling Pair1’s SetContestantScore method to set Alexandra and Gorka’s scores:

Pair1.SetContestantScore WITH 9, 10, 10, 10

Of course the actual marks will be provided by our judge objects. We do not need to know what happens to these values at this point as long as we trust it was the right thing. For all we know, writing this part of the program, each mark might just have been stored separately.

Similarly we can retrieve the total score when we need it. As long as that one method was written correctly, the right thing will always happen for all pairs. We will get the total (and in the following display it).

DISPLAY Pair1.GetContestantScore ()

We could do a similar thing to get the pair’s names. In the following we get both names and score and put space between the name and the score.

DISPLAY Pair1.GetContestantName() + “  “ + Pair1.GetContestantScore()

If we do this for each pair we will have displayed the leaderboard.

You can do no more …

As those method are the only ways our class provides for the code to access the details of the pairs, when writing the rest of the code, we can’t accidentally introduce bugs, printing the names in mixed up pairs, for example, or missing one of the judge’s scores when we total their marks. Programming in this style helps ensure we rule out the possibility of making these easy-to-make kinds of mistake. This is especially important as our whole program gets larger and larger, perhaps millions of lines of code, and as more people become involved in writing it. Those new people may not understand how we have coded a Contestant, but the point is they do not need to. All they need to know are what the methods we have provided to access it do not how they do it. They are the parts we have made public.

Next episode we will see more about the benefits of the abstract data type idea and so of object-oriented programming. Abstraction, i.e., hiding the implementation, allows us to modify the class implementation and yet the rest of the code still works without any further change.

Catch up with Paul’s other blog posts

 

Strictly Judging Objects

by Paul Curzon and Peter W. McOwan, Queen Mary University of London

CraigRevelHorwoodStrictly Come Dancing, has been popular for a long time. It’s not just the celebs, the pros, or the dancing that make it must see TV – it’s having the right mix of personalities in the judges too. Craig Revel Horwood has made a career of being rude, if always fair. By contrast, Darcey Bussell is far more supportive. Bruno Tonioli is supportive but always excited. Len Goodman was similarly supportive but calm. Shirley Ballas the new head judge will presumably refine her character over time, but seems to be aiming for supportive but strict. It’s often the tension between the judges that makes good TV: those looks that Darcy gives Craig, never mind when they start actually arguing. However, if you believe Dr Who, the future of judges will be robots like AnneDroid in the space-age version of The Weakest Link…let’s look at the Bot future. How might you go about designing computer judges, and how might objects help?

Write the code 

We need to write a program. We will use a pseudocode – a mix of code and English – here rather than any particular programming language to make things easier to follow.

The first thing to realise is we don’t want to have to program each judge separately. That would mean describing the rules for every new judge from scratch each time they swap. We want to do as little as possible to describe each new one. Judges have a lot in common so we want to pull out those common patterns and code them up just once.

What makes a judge?

First let’s describe a basic judge. We will create a plan, a bit like an architect’s plan of a building. Programmers call these a ‘class’. The thing to realise about classes is that a class for a Judge is NOT the code of any actual working judge just the code of how to create one: a blueprint. This blueprint can be used to build as many individual judges as you need.

What’s the X-factor that makes a judge a judge? First we need to decide on some basic properties or attributes of judges. We can make a list of them, and what the possibilities for each are. The things common to all judges is they have names, personalities and they make judgements on people. Let’s simply say a judge’s personality can be either supportive or rude, and their judgements are just marks out of 10 for whoever they last watched.

Name : String
CharacterTrait : SUPPORTIVE, RUDE
Judgement : 1, 2, 3, 4, 5, 6, 7, 8, 9, 10

We have just created some new ‘types’ in programming terminology. A type is just a grouping of values. The type CharacterTrait has two values possible (SUPPORTIVE or RUDE), whereas the type Judgement has 10 possible values. We also used one common, existing type: String. Strings are just sequences of letters, numbers or symbols, so we are saying something of type Name is any such sequence.

Let’s start to describe Judges as people with a name, personality and capable of thinking of a mark.

DESCRIPTION OF A Judge:
    Name name
    CharacterTrait personality
    Judgement mark

This says that each judge will be described by three variables, one called name, one called personality and one called mark. This kind of variable is called an instance variable –  because each judge we create from this plan will have their own copy, or instance, of the instance variables that describes that judge.

All we are saying here is whenever we create a Judge it will have a name, a personal character (it will be either RUDE or SUPPORTIVE) and a potential mark.

For any given judge we will always refer to their name using variable name and their character trait using variable personality. Each new judge will also have a current judgement, which we will refer to as mark: a number between 1 and 10. Notice we use the types we created, Name, Character and Judgment to specify the possible values each of these variables can hold.

Best Behaviour

We are now able to say in our judge blueprint, our class, whether a judge is rude or supportive, but we haven’t actually said what that means. We need to set out the actual behaviours associated with being rude and supportive. We will do this in a fairly simple way, just to illustrate. Let’s assume that the personality shows in the things they say when they give their judgement. A rude judge will say “It was a disaster” unless they are awarding a mark above 8/10. For high marks they will grudgingly say “You were ok I suppose”. We translate this into commands of how to give a judgment.

IF (personality IS RUDE) AND (mark <= 8) THEN SAY “It was a disaster” IF (personality IS RUDE) AND (mark > 8)
THEN SAY “You were ok I suppose”

It would be easy for us to give them lots more things to choose to say in a similar way, it’s just more rules. We can do a similar thing for a supportive judge. They will say “You were stunning” if they award more than 5 out of 10 and otherwise say “You tried really hard”.

TO GiveJudgement:
    IF (personality IS RUDE) AND (mark <= 8)     THEN SAY “It was a disaster”     IF (personality IS RUDE) AND (mark > 8)
    THEN SAY “You were ok I suppose”

    IF (personality IS SUPPORTIVE) AND (mark > 5)
    THEN SAY “You were stunning”

    IF (personality IS SUPPORTIVE) AND (mark <= 5)
    THEN SAY “You tried hard”

A Ten from Len

The other thing that judges do is actually come up with their judgement, their mark.  For real judges it would be based on rules about what they saw – a lack of pointed toes pulls it down, lots of wiggle at the right times pushes it up… We will assume, to keep it simple here, that they actually just think of a random number – essentially throw a 10 sided dice under the desk with numbers 1-10 on!

TO MakeJudgement:
    mark = RANDOM (1 TO 10)

Finally, judges can reveal their mark.

TO RevealMark:
    SAY mark

Notice this doesn’t mean they say the word “mark”. mark is a variable so this means say whatever is currently stored in that judges mark.

Putting that all together to make our full judge class we get:

DESCRIPTION OF A Judge:
    Name name
    CharacterTrait personality
    Judgement mark

    TO GiveJudgement:
        IF (personality IS RUDE) AND (mark <= 8)         THEN SAY “It was a disaster”         IF (personality IS RUDE) AND (mark > 8)
        THEN SAY “You were ok I suppose”

        IF (personality IS SUPPORTIVE) AND (mark > 5)
        THEN SAY “You were stunning”

        IF (personality IS SUPPORTIVE) AND (mark <= 5)
        THEN SAY “You tried hard”

    TO MakeJudgement:
        mark = RANDOM (1 TO 10)

    TO RevealMark
        SAY mark

What is a class?

So what is a class? A class says how to build an object. It defines properties or attributes (like name, personality and current mark) but it also defines behaviours: it can speak, it can make a judgement and it can reveal the current mark. These behaviours are defined by methods – mini-programs that specify how any Judge should behave. Our class says that each Judge will have its own set of the methods that use that Judge’s own instance variables to store its properties and decide what to do.

So a class is a blueprint that tells us how to make particular things: objects. We have so far made a class definition for making Judges. We haven’t made any actual objects so far though – defining a class does not in itself give you any actual objects – no actual Judges exist to judge anything yet. We need to write specific commands to do that as we will see.

We can store away our blueprint and just pull it out to make use of it when we need to create some actual judges.

Kind words for our contestants?

Suppose Strictly is starting up so we want to create some judges, starting with a rude judge, called Craig Devil Droidwood. We can use our class as the blueprint to do so. We need to say what its personality is (Judges just think of a mark when they actually see an act so we don’t have to give a mark now.)

CraigDevilDroidwood IS A NEW Judge 
                    WITH name “Craig Devil Droidwood”
                    AND personality RUDE

This creates a new judge called Craig Devil Droidwood and makes it Rude. We have instantiated the class to give a Judge object. We store this object in a variable called CraigDevilDroidwood.

For a supportive judge that we decide to call Len Goodroid we would just say (instantiating the class in a different way):

LenGoodroid IS A NEW Judge 
            WITH name “Len Goodroid”
            AND personality SUPPORTIVE

Another supportive judge DarC3PO BussL would be created with

DarC3POBussL IS A NEW Judge 
             WITH name “DarC3PO BussL”
             AND personality SUPPORTIVE

Whereas in the class we are describing a blueprint to use to create a Judge, here we are actually using that blueprint and making different Judges from it. So this way we can quickly and easily make new judge clones without copying out all the description again. These commands executed at the start of our program (and TV programme) actually create the objects. They create instances of class Judge, which just means they create actual virtual judges with their own name and personality. They also each have their own copy of the rules for the behaviour of judges.

Execute Them

Once actual judges are created, they can execute commands to start the judging. First the program tells them to make judgements using their judgement method. We execute the MakeJudgement method associated with each separate judge object in turn. Each has the same instructions but those instructions work on the particular judges instance variables, so do different things.

EXECUTE MakeJudgement OF CraigDevilDroidwood
EXECUTE MakeJudgement OF DarC3POBussL
EXECUTE MakeJudgement OF LenGoodroid

Then the program has commands telling them to say what they think,

EXECUTE GiveJudgement OF CraigDevilDroidwood
EXECUTE GiveJudgement OF DarC3POBussL
EXECUTE GiveJudgement OF LenGoodroid

and finally give their mark.

EXECUTE RevealMark OF CraigDevilDroidwood
EXECUTE RevealMark OF DarC3POBussL
EXECUTE RevealMark OF LenGoodroid

In our actual program this would sit in a loop so our program might be something like:

CraigDevilDroidwood IS A NEW Judge 
                    WITH name “Craig Devil Droidwood”
                    AND personality RUDE
DarC3POBussL        IS A NEW Judge 
                    WITH name “DarC3PO BussL”
                    AND personality SUPPORTIVE
LenGoodroid         IS A NEW Judge 
                    WITH name “Len Goodroid”
                    AND personality SUPPORTIVE

FOR EACH contestant DO THE FOLLOWING
    EXECUTE MakeJudgement OF CraigDevilDroidwood
    EXECUTE MakeJudgement OF DarC3POBussL
    EXECUTE MakeJudgement OF LenGoodroid

    EXECUTE GiveJudgement OF CraigDevilDroidwood
    EXECUTE GiveJudgement OF DarC3POBussL
    EXECUTE GiveJudgement OF LenGoodroid

    EXECUTE RevealMark OF CraigDevilDroidwood
    EXECUTE RevealMark OF DarC3POBussL
    EXECUTE RevealMark OF LenGoodroid

So we can now create judges to our hearts content, fixing their personalities and putting the words in their mouths based on our single description of what a Judge is. Of course our behaviours so far are simple. We really want to add more kinds of personality like strict judges (Shirley) and excited ones (Bruno). Ideally we want to be able to do different combinations making perhaps excited rude judges as well as excited supportive ones. This really just takes more rules.

A classless society?

Computer Scientists are lazy beings – if they can find a way to do something that involves less work, they do it, allowing them to stay in bed longer. The idea we have been using to save work here is just that of describing classes of things and their properties and behaviour. Scientists have been doing a similar thing for a long time:

Birds have feathers (a property) and lay eggs (a behaviour).

Spiders have eight legs (a property) and make silk (a behaviour)

We can say something is a particular instance of a class of thing and that tells us a lot about it without having to spell it all out each time, even for fictional things: eg Hedwig is a bird (so feathers and eggs). Charlotte is a spider (so legs and silk). The class is capturing the common patterns behind the things we are describing. The difference when Computer Scientists’ write them is because they are programs they can then come alive!

All Change

We have specified what it means to be a robotic judge and we’ve only had to specify the basics of Judgeness once to do it. That means that if we decide to change anything in the basic judge (like giving them a better way to come up with a mark than randomly or having them choose things to say from a big database of supportive or rude comments) changing it in the plan will apply to all the judges of whatever kind. That is one of the most powerful reasons for programming in this way.

We could create robot performers in a similar way (after all don’t all the winners seem to merge into one in the end?). We would then also have to write some instructions about how to work out who won – does the audience have a vote? How many get knocked out each week? … and so on.

Of course we’ve not written a full program, just sketched a program in pseudocode. The next step is to convert this into a program in an object-oriented programming language like Python or Java. Is that hard? Why not give it a try and judge for yourself?

Catch up with Paul’s other blog posts

 

A decomposed face: What is an object?

Paul Curzon, Queen Mary University of London

Object-oriented programming is an important part of modern programming. The concepts involved are complex though, and if learning to program in this way it is vital to understand at a high level what it is about at the outset. The first concept to get to grips with is just what an object actually is and why we might want to use objects to structure our programs. We will use an example of building an unplugged face to demonstrate.

Learn about: Object-oriented programming, objects, decomposition, simulation, computational modelling

Simulation

Object-oriented programming (OOP) arose from a desire to write programs that simulate things in the real world. Simulation has given a different way of doing science that compliments experiments: simulate the phenomena in a virtual way. The real world is made of objects and the natural way to do this is to think about programming the behaviour of those objects, whether people, cars, ants, photons or cannon balls, separately. Once one ant’s behaviour is programmed, we can then have lots of them – as many as we like –  each following the same rules. From one ant program we can get a whole colony.

If the theory embodied in your program is right, the simulation should match the real world behaviour. If we understand ant behaviour and have programmed it correctly, then our virtual ants should behave like a real ant colony. If they don’t we must inspect our rules and work out what needs to change, and so improve our understanding of ant behaviour. This computational modelling of phenomena of interest is one of the main ways Computational Thinking has changed the way the Sciences are done.

Decomposition

OOP also gives a powerful general way to write programs, from games to airline booking systems. As we will see it is really all about decomposition. It gives a new way of organising a program: breaking it in to parts that can be written separately.

Simulating Emotions

Let’s demonstrate by simulating human expressions on a robot face. Here is a video of a robot doing the sort of thing we are interested in. It doesn’t understand the words spoken. It just reacts to the tone of the person’s voice, giving an appropriate expression. If the voice is angry it looks unhappy. If the person talks softly then it cheers up. If they speak suddenly, it is surprised.

Procedural Programming: Rules for Expressions 

How do you write a program to do that? For each expression you need to write rules that move the mouth, eyes and eyebrows in the right way. You could try and write rules about the whole face. It’s always a good idea, though, to break up a program in to separate parts to make it easy to write. Then you can program and test each on its own. Each is a smaller and more manageable problem.

Here you might decompose the program by different expressions. First you might write a procedure, called Happy, that controlled all the parts of a face to give a happy expression. Once that worked, you might write a procedure called Sad to give a sad face, and then one called Surprise that looked surprised, and so on. Each of these procedures would include instructions about the whole face. In procedural programming the focus is on decomposing the program in to the separate operations, separate procedures, like this.

Objects: Rules for Eyes, Eyebrows and Mouth

Instead of thinking about expressions, another, completely different way to think about decomposing, and so programming, the face is in terms of its individual parts: the objects that make up a face. A face is made of eyes, eyebrows and a mouth (and other things we will ignore for now). We can specify their behaviour separately from the behaviour of the rest of the face. We can work out what eyes do without worrying about eyebrows, mouths or even noses. They can be added later. In effect to simulate a face, we can separately write mini-programs that simulate an eye, an eyebrow and a mouth.

An unplugged face

Rather than write a program we will demonstrate this in an unplugged way as it is the concepts of objects and behaviours that we are interested in understanding here. We don’t want to get bogged down in syntax. First we get volunteers to be our robot. Two people hold eyes, two eyebrows and two the mouth (the bits are made out of Blue Peter technology – card, tube and sticky-backed plastic). Each person represents one of the objects that make up the face.

We have a robot, but it does nothing without instructions. We need to write rules that give the behaviour. Each person needs to be told what to do to control the object they control.

Eyes

Let’s focus on eyes first. Notice we are now working on a much simpler, though similar, problem – worrying abut simulating eyes rather than whole faces. What is their behaviour? Well, our robot eye can be wide open or narrowed. We want the former when it hears a nice or a surprising noise. We want the latter when it hears a nasty noise. We could at this point decompose, writing rules for each expression separately, but its simple enough we will do it all at once.

The behaviour of an EYE object is:

If NICE SOUND then WIDE OPEN

If NASTY SOUND then NARROWED

If SUDDEN SOUND then WIDE OPEN

This is essentially a program for an eye (just written in a language a person can follow). We can come up with these rules completely separately from the instructions for any other object. If we make two eye objects that follow these rules we already have the basics of a face.  We could test it and see if it starts to show the right expressions. Of course we only need one set of instructions for an eye. We can then reuse it whenever we need an eye.

We call the rules for behaviours like this methods, and they are just a form of procedure or function but in an object-oriented context. There is also a distinction between an object and a class.

Our rules for an eye above are really a plan or template for how to build an eye object. It is what we call a class definition for eye objects. We need to create an instance of that class – the actual object – each time we want an actual eye. In our unplugged word of volunteers, creating an instance involves taking a volunteer and giving them each a copy of the eye instructions – they each become eye objects. Our simple face is built of two eye objects – so in our instructions of how to build a face we will need commands to create two such instances of eyes, each separately following the same general rules.

Eyebrows

Having done that and tested it to make sure it does the right thing we can move on to programming other objects – writing their class definitions. Let’s do the eyebrows next. An eyebrow can move UP high or be low DOWN over the eyes. For happy and sad expressions the eyebrows will be in a normal, down position, but we raise our eyebrows when surprised.

The behaviour of an EYEBROW object is:

If NICE SOUND then DOWN

If NASTY SOUND then DOWN

If SUDDEN SOUND then UP

A Mouth

Each side of the mouth also then has a similar rule, where the end of the mouth can turn UP (when happy), or it can turn DOWN (when sad), or the mouth can OPEN wide when surprised.

The behaviour of a MOUTH object is:

If NICE SOUND then UP

If NASTY SOUND then DOWN

If SUDDEN SOUND then OPEN

Building the Face

We now build a face object just by putting together the right bits: two eyes, two eyebrows and a mouth. We create instances of them to make a face. Each part follows its programmed behaviours and what emerges is a face acting like a face: looking happy, sad or surprised.

Details, details

Of course to fully complete the program we need to write instructions as to what UP and DOWN, OPEN, NICE, NASTY and SUDDEN sounds actually are. This is another example of decomposition and linked abstraction given we are ignoring the details of how to code them in this explanation. We ultimately need to write methods to do each of those things.

The Power of Objects

Overall the main way we have decomposed the problem is by thinking of the objects that make up a face and separately programming their behaviours. The face itself might just then be part of a bigger endeavour to make a robot body…what about our body language for different emotions? That might be part of a program to simulate an audience at a concert, which might be part of a city simulation,…It is a natural way to build up large programs from smaller parts.

The idea of objects also has power because they are naturally reusable. Each object can be replicated as many times as needed. Want an alien with three eyes. Just add another eye. Its behaviour is already coded. Want a whole crowd of faces, then just replicate the whole face object. This also naturally scales, at least on the right sort of problem. That is ultimately what it is about, trying to find a style of programming, a form of decomposition, that allows us to write massively large and complicated programs in a way that is possible to do and get right.

Decomposing the problem in to objects in the way we’ve described is only the first step though. Once you have done that, you find other opportunities open open for reusing code in natural ways which leads to more complex concepts like encapsulation and inheritance that give even more benefits.

Catch up with Paul’s other blog posts

 

Two CAS London Teach A-Level Computer Science courses in Autumn 2017

Update 18 September 2017: The A2 Projects with Databases & Python course (pink in the diary image below) is now full but we have spaces on the Object Oriented Programming course at QMUL (blue in the image below). If you’re attending the A2DB course you’ll be able to attend the OOP one as well.

Screenshot 2017-10-13 10.57.40


We have two ‘Teach A Level Computer Science’ courses coming up later this year. Please bookmark this page as it will shortly be updated with details of the earlier course (to be held at Queen Mary University of London in October / Nov). The details of the later course (to be held at King’s College London Waterloo in Nov / Dec) are below. Both cost £100 and free places are available for CAS Master Teachers.

  1. Teach A-Level Computer Science: Object Oriented Programming
  2. Teach A-Level Computer Science: A2 Projects with Databases and Python

Please note that these courses are for in-service teachers who are already confident in teaching computing at GCSE level, Python will be the programming language used.

The course dates are arranged so that it will be possible for teachers to attend both courses.

 

1. Teach A-Level Computer Science: Object Oriented Programming

Find out more and book a place

Course dates

  • Wed 4 October
  • Wed 11 October
    [Break – Wed 18 Oct]
  • Wed 25 October
    [Break – 1 Nov]
  • Wed 8 Nov
  • Wed 15 Nov

Location: Queen Mary University of London
Tutor: Dr William Marsh, CAS London

2. Teach A-Level Computer Science: A2 Projects with Databases and Python

Find out more | Apply for a place

Course dates

  • Week 1 (1 Nov 2017) – Single table databases and sqlite3
    [Break – 8 Nov]
    [Break – 15 Nov]
  • Week 2 (22 Nov 2017) – Foreign keys and relationships
  • Week 3 (29 Nov 2017) – Many-many relationships
  • Week 4 (6 Dec 2017) – Developing a project for A-Level Part 1
  • Week 5 (13 Dec 2017) – Developing a project for A-Level Part 2

Location: King’s College London, Waterloo
Tutor: Dr Sue Sentance, CAS London

For more information please contact Jo (j.brodie@qmul.ac.uk)

Surveying computing teachers – primary programming and micro:bit use in secondary classes

If you’re a Computer Science or Computing teacher at secondary or primary level we’d be very grateful for your input in any of the surveys below please 🙂

PRIMARY TEACHERS

1. Using Design in Primary Programming – Research Project
This survey is run by Jane Waite as part of her research at Queen Mary University of London (one of the two universities which forms the CAS London Regional Centre).

Jane says…

Last year, I started research looking for a magic bullet for teaching abstraction in primary schools. However, I discovered that research requires you to look at one tiny aspect of a big subject in order to gradually build a solid body of evidence. So now I am focusing on one aspect of abstraction, how we use design when teaching programming, and how we might reuse our expertise in teaching writing when we teach programming.

My work builds on research from across the world, but all of it with older pupils. From Israel to the US via Scotland, Netherlands and Germany I am knitting threads of theory and practise together but for teaching younger learners.

If you teach programming to primary children, in school, out of school, formally or informally and have 15 minutes to spare, I would be indebted if you could complete our survey, the link is https://goo.gl/forms/EQFaZvBBPjOeZNin2 or https://tinyurl.com/design-JW

2. Please tell us what you thought of A Bit of CS4FN
abitofcs4fn front cover screenshotSome of you will have subscribed to receive printed copies of our newest version of CS4FN magazine – the mini ‘A bit of CS4FN’ edition for primary schools. We’ve posted them out and would love to know what you think of them. This survey is also from Queen Mary University of London.
Please tell us how you found the magazine and website:
https://bit.ly/abitofcs4fnsurvey

SECONDARY TEACHERS

BBC_MicrobitThe research survey below is from the CAS London team at King’s College London, looking at how teachers are using the BBC micro:bit in their classroom.

TEACHING WITH THE BBC MICRO:BIT
You are invited to participate in a web-based online survey on using the BBC micro:bit in your programming classes. This is a research project being conducted by Filiz Kalelioğlu and Sue Sentance at King’s College London. It should take approximately 10-15 minutes to complete.