What is an Object?

Much present day commercial software development - probably the majority of it - claims to be object oriented, and at the centre of object oriented software is the object. So, what is an object? Unfortunately, the word object seems to have joined the ranks of the buzzwords. It seems to have become one of those terms that gets banded about, without its users ever stopping to ask themselves if they really know what one is. This has resulted in a lack of design discipline that I believe has strongly contributed to the poor design of many software systems. In the remainder of this article, I will give my answer to the question that its title poses.

To get to the answer, we need to step back and think about why we use objects. I’d say it’s because they enable us to represent concepts from the real world in software. These concepts might be real life things that we import from the problem domain, or things that exist only in the computer solution, for example a message receiver or a process. An object exhibits a set of operational semantics representing a concept in an abstract form. I will refer to these semantics collectively as the object’s type. It follows that a type is an abstraction of a real world concept in a software design model.

Types are therefore the role players in software designs, and they play their roles by assuming responsibilities. A type has closely related responsibilities that are grouped together to collectively make up the role played by the type. Now, having said all that, the original question was: what is an object? The above discussion leads to the following definition:

  • An object is a physical manifestation of a type, that executes the responsibilities of that type

The understanding of what an object actually is only serves as a starting point for using objects effectively in software design, but I also think it is is an essential starting point. This article is rather brief because it has a very narrow scoped, its purpose being to provide an answer to a very basic question. I hope to follow up with more broadly scoped articles fairly soon.

A Very Simple Introduction to Unit Testing

The idea of unit testing is to write code that automatically tests other code, and that can be executed repeatedly. It has grown in popularity over the last few years, its profile having been raised by the test-driven development (TDD) practised within the agile development community. Note that unit testing is not, in itself, test driven development – the latter being a development which is more than unit testing, and that employs unit testing as part of it. This article offers an introduction to unit testing, aimed at less experienced programmers.

To start off with, here is a very simple example class:

    class bank_account
    {
    public:
        bank_account();  // Initially, balance() == 0

        long balance() const;

        void deposit(unsigned int amount);
        void withdraw(unsigned int amount);

        //...
    private:
        long balance_;
    };

This class is basically my C# BankAccount class from my Updating Object Properties While Respecting Encapsulation article, and before going any further there are a couple of points I would like to note about this class:

  • Here I’ve rewritten it in C++. I’m going to use C++ as my programming language for this article. This is because, as part of its C heritage, C++ has the assert macro – and although assert wasn’t originally intended for unit testing, it makes a simple but effective tool for doing so without the need to look outside the language’s standard library. In Java and C# there are unit testing frameworks – Junit and Nunit respectively – that the respective communities have adopted as their standard, but nevertheless one has the overhead of acquiring, setting up, and learning to use an external library. Not having to look beyond the programming language’s standard library helps to keep things simple. If you can read Java/C# you should have no difficulty following the code examples even if you’ve never seen C++ code before; note that the expression assert(x) halts the program with an error message if the expression x evaluates to false.
  • I’m not pretending this is a production standard class: the version shown is no more than an illustrative fragment, the use of long and unsigned int types to represent money is certainly not best, and there is no overflow or underflow checking.

Moving on, the next thing to do is construct the unit tests. I’m going to describe this by building up a set of tests a step at a time.

The first thing to do is write a skeleton C++ main() function (main() is the C++ function that is automatically called when the program is run – note that in C++ functions do not have to be members of classes). This skeleton function simply creates an instance of bank_account and checks that its initial state, with balance() returning zero, is correct:

    #include "bank_account.hpp"
    #include <cassert>

    int main()
    {
        bank_account test_account;
        assert(test_account.balance() == 0);
        return 0;
    }

We compile and run this, and find it runs without any problems, so it’s time to add another test. Let’s see what happens when we make a deposit and see if balance() returns what we would expect:

    #include "bank_account.hpp"
    #include <cassert>

    int main()
    {
        bank_account test_account;
        assert(test_account.balance() == 0);

        test_account.deposit(12);
        assert(test_account.balance() == 12);

        return 0;
    }

Again, when we compile and run this we find it runs without any problem, so we can move. The next step is to make a withdrawal, and check balance() still returns what we would expect:

    #include "bank_account.hpp"
    #include <cassert>

    int main()
    {
        bank_account test_account;
        assert(test_account.balance() == 0);
        test_account.deposit(12);
        assert(test_account.balance() == 12);

        test_account.withdraw(12);
        assert(test_account.balance() == 0); // balance() should now be back to zero

        return 0;
    }

This compiles without a problem, but when the program is run things do not go as smoothly as with the previous steps. Instead of running without error, the program produces an error message saying that assert() failed, and citing the line of the last assert() as being the problem. So far balance() has not let us down, so this suggests the implementation of withdraw() is the problem – and a look at the code reveals a simple mistake:

    void bank_account::withdraw(unsigned int amount)
    {
        balance_ += amount; // Oops! This should be a decrement.
    }

The data member balance_ is being incremented when it should be decremented, so this is fixed, and the unit test now runs smoothly once again.

That completes the step by step illustration of the development of a set of unit tests, and brings this article to a close. This example is contrived and very, very simple, but it does show the points I want it to show. In particular, several times I have encountered unit testing being objected to because of the time overhead it adds to development. However, in reality, it pays for itself with interest. The kind of error shown above is a good example of one that would have been far harder to track down had it not been tested in isolation. In real world development, one needs to think carefully about what needs to be tested, and the above example certainly does not show a complete set of tests. For example, typically, a production class would need unit tests to check it produces error conditions correctly. Even so, a reasonable set of unit tests can usually be designed fairly straightforwardly, and it’s surprising just how many mistakes can be detected just by ensuring code is executed in isolation!

Update

February 5th, 2009.

I’ve now writen a follow up article entitled Pros and Cons of Using the C assert Macro for Unit Testing in C/C++.

Updating Object Properties While Respecting Encapsulation

This article is a follow-up to my previous article Accessing Object Properties While Respecting Encapsulation. In that article I looked at making object properties accessible while respecting encapsulation. In this article I will look at how to design operations on objects in order to update property values while respecting encapsulation – that is, without resorting to the all too common “setter” (otherwise known as a “set” method).

By the end of my previous article we had the following:

        class Circle
        {
            public uint Radius
            {
                get { return radius_ ; }
            }

            // ...

            private int x_centre, y_centre;
            private uint radius_;

            // ...
        }

I used this fragment of a C# class to make the point that our approach should be to decide what properties we want to make publicly readable, and then decide how we’re to implement them; If the implementation just happens to be returning a data member, then that’s fine – but that is a private matter for the class.

Moving on, it seems reasonable that users of this class would also want to be able to update the size of the circle. Therefore, should we make it possible to assign to the Radius property? The answer is simple - NO! How then, can we make it possible to update a Circle object’s size?
To understand this, it is worth stepping back and looking at what we actually get from object oriented programming. In this case, I’m thinking specifically of how objects help us to represent the real world. With this in mind, when tempted to make an object property “settable”, we should stop for a minute and think about what we really want to achieve – and what we want to achieve is not the setting of the Radius property, but the resizing of the Circle object. Therefore, we should endeavour to say just that by having a Resize() method. The class now looks like this:

    class Circle
    {
        public uint Radius
        {
            get { return radius_ ; }
        }

        public void Resize(uint new_radius)
        {
            radius_ = new_radius;
        }

        // ...

        private int x_centre, y_centre;
        private uint radius_;

        // ...
    }

Here is a sample usage code fragment:

    class UsesCircle
    {
        static void Example(Circle the_circle)
        {
            uint new_radius = 42;
            the_circle.Resize(new_radius);
             //...
        }

        //...
    }

By designing the class’ operations with the real world in mind, once again we have code that speaks to its reader in more natural manner, and once again it achieves this simply by bearing in mind how the operation would be expressed in English. Looking back for moment, let me point out the question posed above: how can we make it possible to update a Circle object’s size? It is worth noting how simply asking the right question provided a strong clue to its answer!

Moving on, I now want to leave my Circle class example for the time being, and move on to emphasise another important point: there are many cases where it would actually be ridiculous to make a property value explicitly “settable”! My favourite example is a class to represent a bank account. First, just to strengthen the point, let me show this done the wrong way:

        class BankAccount
        {
            public long Balance
            {
                get { return balance_; }
                set { balance_ = value; }
            }

            // ...        

            private long balance_;

            // ...
        }

The point is this: do you know of a bank that will let you set your balance? If so, please get in touch and let me know which one! Real world bank accounts allow the user to do the following:

  • Query their balance
  • Make deposits
  • Make withdrawals

Therefore the operations on the BankAccount class should reflect this. Here is a fragment illustrating the design done sensibly:

        class BankAccount
        {
            public long Balance
            {
                get { return balance_; }
            }

            void Deposit(uint amount)
            {
                balance_ += amount;
            }

            void Withdraw(uint amount)
            {
                balance_ -= amount;
            }

            // ...        

            private long balance_;

            // ...
        }

Note that BankAccount could dispense with its Withdraw() method, and instead allow Deposit() to accept a negative amount. Which is the most natural approach rather depends on the application area in which BankAccount is being used, and it serves to illustrate the existence of alternatives.

That bring this matter to a conclusion. This article and its predecessor have, out of necessity, presented quite simple examples. Sadly, in reality and in practice, software development is far from simple. However, I hope the two articles will contribute to the clearing up of misunderstandings that appear to remain all too common.

Accessing Object Properties While Respecting Encapsulation

Despite object oriented programming having been mainstream for well over a decade now, there are still concepts associated with it that are sources of confusion for its practitioners. It seems to me that, unfortunately, easily available guidance is still in short supply. One source of problems is this: how should an object should make information about itself available to its client code while respecting the principle of encapsulation? Sadly, all too frequently, encapsulation is abandoned in favour of “get/set” methods that are effectively just public data members in disguise.

It is quite possible for objects, in their public interfaces, to share information about themselves with their client code while respecting encapsulation. It is my goal in this article to show how this can be done, and in doing so, to clear up some of the misunderstandings surrounding encapsulation in this respect.

Let’s start with an example, let’s design a Circle class. Normally, when designing a class, the first thing I would think about is its public interface methods, and for illustration purposes I’m just going to pick on one method: one to return the circle’s radius. Here is a C# code fragment showing this:

    class Circle
    {
        public uint Radius
        { 

            ...
        } 

        ...
    }

This is saying that, as a design matter, circle has a property called Radius. Here property is a critical word. In their public interfaces, objects expose properties - that is, pieces of information about themselves which client code can read. Client code can now read a circle’s radius as follows:

    class UsesCircle
    {
        static void Example(Circle the_circle)
        {
            uint radius = the_circle.Radius;
        }
        ...
    }

Now before we move on, there are a couple of things I would like to draw attention to:

  • My examples in this article are in C#, and C# supports properties as a language feature. In languages that don’t directly support properties – C++ for example – then simple value returning methods are typically used instead
  • I have deliberately avoided using the name GetRadius in favour of Radius – I believe this is closer to how it would be expressed in English, and is therefore a more natural naming
  • You may be wondering: what about updating Radius? Well, you can’t directly update it, and sorry, but (in the interests of keeping this article down to a reasonable length) I’m deferring the explanation of that until part 2

Time now to think about how to implement the Circle class. The obvious way is to store both the centre point and the radius as data members: that would mean the Radius property would just return the radius data member, as you might expect. However, just to make a point I’m going to do things a little differently: I’m store the centre point, nothing different there, but rather than store the radius I’m going to store the diameter of the circle. Here’s a fragment of the implementation:

    class Circle
    {
        public uint Radius
        {
            get { return diameter_ / 2; }
        }

        ...

        private int x_centre, y_centre;
        private uint diameter_;

        ...
    }

Obviously the Radius property must now do a simple division, and return half the radius. As I said above, I’ve done it this way to make a point: this is possible because the Radius property encapsulates its implementation!

Now let’s re-implement the class using a more obvious approach: storing the radius as a data member:

    class Circle
    {
        public uint Radius
        {
            get { return radius_ ; }
        }

        // ...

        private int x_centre, y_centre;
        private uint radius_;

        // ...
    }

Now we’re back to having the Radius property just returning the value of a data member. However the point is this: the interface was designed to make the radius property readable, and it just so happens that the chosen implementation is one that returns the value of a data member! The idea is supported by the simple fact that – as illustrated above – alternative implementations are possible. As a further example, the circle could store its centre and two circumference points, although the calculation needed in Radius’s implementation would be slightly more complicated. Note in passing that this encapsulation is underpinned by keeping member data private.

When designing a class, programmers need to effectively put themselves on the outside and look inwards. That is, consider what interface is required - including readable properties - and then move inside the class and consider how to implement them. This is the way of encapsulation. This is a very different thing to the all too common approach of simply exposing a data member through a public property!

I hope this article has helped to clear up some misconceptions and misunderstandings. It is far from the end of the story. I still have to deal with how to design in cases where properties can be updated, and no doubt this is not the only unanswered question. I hope to write up part 2 soon.

In an Agile World, XP Can Mean Extreme Prejudice

The agile approach to software development is all the rage these days. This must be a good thing because when handled well, the flexibility agile methods afford makes for much greater cost effectiveness, for example:

  • Changes in the business requirements can be handled right up to the very late stages of development
  • Iterative development, and the production of the product so far at the end of each iteration, aid the picking up of misunderstandings and/or need for changes to the specification

However, I fear that – like many things in software development – the agile approach is frequently misunderstood. Just as worrying is the anecdotal evidence that it is being abused, in that the meaning of “agile” is being twisted in order to justify chaotic development.

Here are some examples, the first two being examples of the former, and the third being an example of the latter:

Example 1

In the article More Than Coding Mistakes At Fault In Bad Software, the author Alexander Wolfe says:

"That waterfall model was replaced by a process (and I use that word loosely) where the modus operandi was to cram in as many features as possible before the shipping cut-off date, and then fix the problems in beta. (Sure, I know time pressures mean waterfall wasn’t rigidly adhered to, and also that it had deficiencies, leading to the 1980s flowering of alternatives like agile-development and object-oriented programming. But at least we had a model.)"

The final sentence of the above quote - "But at least we had a model" - suggests to me that this author does not view agile development as exemplifying any model at all. I guess there is much scope here for a (semantic) debate over what model means in this context. To me it is clear that, while agile processes vary, there is a core model that they all adhere to - albiet quite different from the waterfall model. Sorry, no further explanation here, but I’m aiming to pick this up in a future article. In passing, I’m rather baffled by this author’s characterisation of object-oriented programming as an alternative to the waterfall model. Object-oriented programming is orthogonal to the waterfall model. Actually it is orthogonal to the development process model/mindset per-se.

Example 2

A few years ago I was working in a development group where the manager had been reading about extreme programming (XP). He proceeded to dismiss it as "licensed hacking". This was based on the XP doctrine of anyone being able to refactor code as they saw fit. He had great difficulty grasping the fact that XP practitioners take for granted, as part of their development culture, practices that he could not even envisage using. For example, two such practices are test driven development and the ongoing peer review of code (via pair programming). Unfortunately, this manager was not open to modifying his opinion – he knew what he was talking about!

Example 3

I have been quite lucky with the development groups I have worked in, in that I have not personally worked in one where the agile approach is being twisted to justify chaos. However, the following did come up in an interview:

The manager of the development group proudly told me that the (C++) development group had gone agile and were developing in two week iterations. However, I quickly discovered they were not doing any test driven development – or even any unit testing for that matter. Further, they frequently had to work long hours, or even overnight towards the end of iterations, in order to get all the functionality expected from that iteration into the product. It seemed that pushing functionality forward into a later iteration was not acceptable.

Actually the above was in a telephone interview and I declined the offer of moving on to a face-to-face interview! Also that’s the only example from my own personal experience, I have come across several similar ones in conversations with other developers.

Finally

Unfortunately, examples of the abuse of agile development such as that last example only serve to strengthen the prejudices borne out by the first two examples. Right now, I’m afraid I don’t have any suggestions as to what the genuine agile development community can do to - over and above what is already being done - to change this.

?>iMaleSpectrumPass Mobile Milf Videos diflucan online All Girl Mobile Flomax online iMuscleMen Asian Parade Milf Seeker cartoonreality His First Huge Cock Rookie Guys justcartoondicks kamagra portugal Pure Anime hot muscle dudes Tranny Seducers Gay College Sex Parties Ebony Shemale Mobile Shes My Ex PV Trannies Housewife Porn Videos PV Strips 3DS Max 8 OEM3Q 3GP Video Converterdownload acdsee manager 2009 oemred eye remover pro 1.2cheapest windows vistacheapest windows vista ultimatecheap AutoCAD 2009Vision Backup Enterprisecheap Macromedia ColdFusionnero photoshow 5 downloadadobe photoshop cs oemcoldfusion mx 7 downloadkamagra sildenafil citratekamagra generic viagraorder caverta onlinecaverta 100buy cavertatadaliscasodex 50 mg tablet