Fog Creek Software
Discussion Board




OOP paradigm shift

I'm programming computers (microcontrollers too) for about 15 years. Always with procedural languages.

Last months I resolved to learn C#. I understand the concepts (inheritance, polymorphism, etc) but I can't apply it ! I always think the procedural way.

Is it really difficult to do the shift ? Can anyone recommend a book or net resource to help this ? The problem isn't the language itself, but how to change my mind. Maybe it is an IQ issue ?

thanks in advance

Augusto
Tuesday, May 06, 2003

There's a big difference between knowing it in theory and being able to apply it (Which is why U.S. education is lacking, but that's a different rant...). It doesn't mean you are incapable, just that you don't know.

I was a victim of this for a while as well: I'd learned C (my first language) almost entirely from modifying games (written in pure C). Then, some time later, I tried to write Swing apps in Java and was sooooo confused, because not only does it use "structs with access privlidges" (classes), but it actually takes advantage of OO stuff in a way that both is useful and requires programmer knowledge of what they are trying to accomplish. A moment of enlightenment when I finally realized what they were meant to do; I finally understood the purpose of the composite design pattern.

I think a good introduction to OO is the Gang of Four book: Design Patterns. It's a bit old, but it doesn't focus on code or technologies, just theory. I like it because they go through and explain some solutions to common problems, explaining the problem and solution in a clear and readable manner. I'm sure someone else will have a better suggestion, but I do suggest getting around to the GoF book at some point regardless.

I think it's really hard to get into a new way of thinking (and that's what switching to OO is). I posted a question on that topic myself a while back, in fact. The consensus seemed to be that there's no shortcuts, just learn more and apply what you know and eventually you'll get it.

The only way I've found to make learning something like this easier is to read books. And then apply you you learn. Twice, at least. In the wise paraphrasing of Fred Brooks: "Build one to throw away. You're going to anyway."

Keep kickin' at it, it'll go eventually 8-}

Mike Swieton
Tuesday, May 06, 2003

Also, a person's transition to OOP is usually gradual. I started writing Java, instead of C, two years ago. My code started off very procedural, using classes to store related methods in a single file. Over time, my code is becoming more and more object oriented. Even today, an OOP purist would probably find stuff to complain about in my code.

Keep in mind that OOP is a tool to help you write better code. Only use inheritence, for example, if it makes your code more readable and maintainable.

Julian
Wednesday, May 07, 2003

> Is it really difficult to do the shift ? Can anyone
> recommend a book or net resource to help this ? The
> problem isn't the language itself, but how to change
> my mind. Maybe it is an IQ issue ?

I had the same problems back in the past: did lots of procedural / structured programming, but not OO programming, and altough I understood the OO mechanisms, I didn't know how to use them.

Get a book which contains an example of how to implement an OO application.

The one I read (lots of years ago) was "The Tao of Objects". I don't remember the name of the author, and the book is now certainly extremely old, but, at the time (long before Java, and design patterns) it taught me exactly how to design an OO program.

It was not a comprehensive book, and maybe not even a well-written book, but it got me to make the first steps towards OO development.

Maybe you can get a similar book today.

"The Tao of Objects" book is now extremely outdated.

Michael K.
Wednesday, May 07, 2003

Whenever I think or talk OOP I use a car. I don't know if this will work, but what the heck...

Instead of thinking of your program as a series of paths, think of it as a "thing" - instead of flowcharting your way through
1) Get Keys
2) Is door locked?
3) Get in car
4) Put key in ignition
...etc...

Think of the car as just being there, made up of pieces. If you want the door open, then
Car.Door.Open();

If you want the engine to start, then
Car.Engine.Start();

One of the major benefits of OOP is that you don't have to prethink every possible path - you just have to design the things that are acted on, and the actions.

In terms of, say, Excel, you have
Application.Start();
Worksheet.Create();
Worksheet.Rows.Add(1-10000);
etc.

This is vastly simplified of course, but maybe it'll give you the toehold you need?

Philo

Philo
Wednesday, May 07, 2003

If you're programming devices (you mention microcontrollers), then likely you are dealing more with procedural models anyhow.  What avantage do you expect OOP to provide?

Take the lowly ethernet driver.  Yes, an ethernet controller is an object, and network drivers follow a pattern of absraction common to all ethernet devices.  But what exactly would you do with a polymorphic ethernet device?  What would you do with a polymorphic wave soldering machine?  A box handler or automated test stand?

Would these objects self assemble themselves into an assembly line?  Maybe in the Terminator movie.  Truth is, static hardware assemblies can be expressed as objects, but there is not much inherent gain.

Some will say:  but there is clean abstraction and data hiding.  That was a choice which could/should be made without polymophism - which is the true measure of crossing the OOP boundary.  In fact, for a device driver to be reentrant, it forces an object like design on the driver and on the operating system. 

Anyhow, bottom line is don't waste time trying to smash OOP design down the throat of what may be a truly procedural problem in the first place.

Nat Ersoz
Wednesday, May 07, 2003

the tao book was gary estminger.

yes it is (too) outdated to be of use now

Karel
Wednesday, May 07, 2003

My suggestion to start using objects is to start easy. Perhaps just start making a few small objects with some properties.

The real trick in making the change is to start with one small thing. For example, while VB is not OOP, I certainly do use class objects. I actually think that using a few objects in VB is a great start to get the mind “thinking” in  a opp way. The problem is WHEN, and WHY should you use a object?

Generally, I use and create a class object when the process, or "thing" I am dealing with starts to become very complex. For example, if my application has a screen to edit a patient, then you don’t need to create patient object. On the other hand, if you need to execute several "processes" on a patient, then a object starts to be come handy. If the process on the patient is simply you entering a last visit date, and then some report gets printed, then you can set-up a button and some code to do this. When you find that you need a lot of code AND data to complete a certain procedure, then a class object start to make sense.

Hence, if for example you have a complex booking system that allocates doctors to that patient, or you have to schedule certain tests that requires booking to special rooms then a booking object, or a patient object can really start to pay off. In fact, in this case..I would concentrate on creating a booking object.

In other words, when you need code that brings together both a bunch of data, and a bunch of code procedures then a object starts to make sense. Since booking people for limited time on a cat scan machine, or special type of "procedure" room can start to get very complex, then a booking object can "bring" the whole mess back down to a earth like manageable task.

Remember:
    there is nothing in a object that cannot be done by standard coding approaches.

It is just that things start to get real messy after a certain amount of complexity. In addition, the other advantage of a object is that you can have more than one instance of the object. This is really critical for certainly kinds of user interface. I have a tour booking system, and I created a tour booking object. Each tour object has a zillion things. The hotel name, the type of rooms at this hotel. The room rates for the particular season.  How many rooms available. How many tour buses available. How many seats on each tour bus. Name of the tour bus company. How many corporate bookings are holding seats, but not yet used.

As you can see, the above list gets quite long. Each of the above "how many" questions is fact a bunch of code and sql queues to grab and calculate the results. So, when you find you need code AND A BUNCH of data, then starting to use objects will make sense.

Lets assume we have a booking record for a customer. Ok, lets use standard non object code to display the Tour name. And also, lets display the Hotel name. For sure, in when dealing with relational data, the hotels list is a separate table, and so is the tours.

Lets say the user is booked to tourID of 222 (this number just the simple internal autonumber “key” for that tour). To get the hotel name for this booking, in standard VB code, I would have to do the following.

dim rstTour            as recordset
dim rstHotel          as recordset
dim lngTourid        as long
dim lngHotelId      as long
set rstTour = currentdb.openrecordset("select * from tblTours where tourid = " & lngTourId )

ok...so now we have the tour, lets display the tour name

msgbox "tour name = " & rstTour!TourName

now display the hotel name. The hotel name of course is simply a hotelID in the tour record

lngHotelId = rstTour!Hotel
set rstHotel = currentdb.openrecordset("select * from tblHotels where hotelID = " & lngHotelId)

msgbox "hotel name = " & rstHotel!HotelName

You can see what pain it is to just get the tour name, and the hotel name. We have to deal with two related tables, build two queries, declare two recordsets. Man, what a pain!  This is nuts!

We also could also perhaps use a query that is a relational join to reduce the above code. However, there is a lot of additional things we need when working with the tour. Now extend the above to include the room type description (another table), the room rates (another table, and complex looking to a seasonal pricing system). Grab the bus?

Heck...this is becoming a night mare to simply display a few things about the users booking. Now, lets do all of the above with a class object.

These properties of the object are actual ones that I use:

dim myTour as New clsRides
myTour.TourId = lngTourId

At this point, I can retrieve, and ask virtually anything I want about his tour. So.

myTour.TourName      returns the name of the tour

myTour.HotelName        returns the name of the hotel

myTour.HotelSpace    returns the space allocated in the hotel

myTour.HotelRooms    returns the number of rooms in this tour

myTour.HotelRoomsUsed returns the number of rooms used.

I will stop at this point, but to get the above simple answers with regular coding methods will require at least 50 lines or more of code? Yikes!!

Is not the above incredibly easy? Hey, lets get the space remaining in the tour:

myTour.HotelSpaceRemain

How nice and easy it is to get the hotel space remaining. Note only that, but inteli-sense works for all of the above..so I don't even have to remember all the names of subroutines/code as I type. And to get number of people on the bus for this tour..?

myTour.InBusTotal

Here is the code for above example InBusTotal:

Public Property Get InBusTotal() As Integer
  InBusTotal = 0
  If m_rstBusList.RecordCount > 0 Then
      m_rstBusList.MoveFirst
      Do While m_rstBusList.EOF = False
        InBusTotal = InBusTotal + Nz(m_rstBusList!InBus)
        m_rstBusList.MoveNext
      Loop
End If
End Property

Now, if you look at the above property of the object, you will notice that a recordset m_rstBusList is already loaded. In other words, when I create and set the myTour = "tour id", then all of the recordsets for bus company, hotels. rates etc gets loaded into the object. Hence, the above code as a result is MUCH better then just writing a stand alone subroutine called "in bus total". Since, a stand alone routine would have to still load up a very complex query into the recordset. I don't have to do that since the class object is a collection of those reocrdsets (data) and routines to give me the "things" I need to know about a tour. The more you add code to the class object, the more it simplifies the application. When you don't use a object, the more code (more features) you write, the worse your application will get!

Anyway, you can see that the whole thing just becomes such a pain to code simple questions about a tour. Create a tour object, and virtually anything you need about that tour is ready made at your finger tips.

To try and code that without object would be EXTREMITY difficult.

Futher, as mentioned, you can have more then one instance of the object active. If look down in the following web page, you can see a screen shot that uses *two* instances of the class tour object.  This screen allows you to move people from one tour booking to another. On the left side is one tour booking object, and on the right side is another booking object.

http://www.attcanada.net/%7ekallal.msn/Rides/Rides.html

The above is just not really workable with standard coding.

So, even while VB is not a OPP environment, I believe that I will have little trouble making the jump to VB. Net (and I am just staring on that path right now).

Albert D. Kallal
Edmonton, Alberta Canada
kallal@msn.com
http://www.attcanada.net/~kallal.msn

Albert D. Kallal
Wednesday, May 07, 2003

Simple advice: Give it time.

Like others here I went from C to C++ and Java, headlong into the world of OO. 

Took me a couple of years to really unlearn all of my procedural habits and get into a real OO mindset, though I was relatively productive with OO projects after a few weeks/months of learning.

While the GoF Design Patterns book is very good, I'm not so sure I agree with the recommendation in this context -- IMO most people won't appreciate it until after they've already embraced at least the basic parts of OO fully.    I'd suggest sticking to less abstract books and learn by doing... THEN revisit the concept of design patterns. 

George McBay
Wednesday, May 07, 2003

The GofF Design Patterns book is helpful because it has a lot of suggestions on why to do things, such as the choice between inheritance and composition. It's not the ultimate OO tutorial, but it's got some useful bits. It's also a fairly low level book - the patterns are useful everywhere, not just in a specific class of applications.

I'll admit I'm still looking for a particularly good book on how to do OOP, even though I'm getting a fairly good grasp. Most just cover the technique for inheritance and such in a particular language, but offer little or no advice on practical reasons to use inheritance. A-dog-is-an-animal may explain what inheritance is, but it's not really a practical example.

Maybe I should learn to write properly so I can make a fortune. Maybe.  :)

andrew m
Wednesday, May 07, 2003

Augusto,

apply the Design Patterns as you find them described in Gamma's & Co book. With time you'll get to feel how these patterns apply and work and how to use them efficiently. That would be a great start.

Cheers and good luck
Dino

Dino
Wednesday, May 07, 2003

Is it hard to make the shift?  I can only speak for myself, and for what I've observed in the handful of good C++ programmer I've ever known (and the dozens of mediocre and bad ones).

It takes years to really - really - "get it".  Several times along the way, you'll think you have it, but you don't have it all, yet.  There are no shortcuts; you just have to read and code a lot.  A whole lot.

What'd I'd love to see is a list of milestones in the process of understanding OO.  Something like, "Coding to the interface is done because...". If you can answer the question, you've reached milestone "n"; if not, you know you have work to do.  Anyone ever seen anything like that?

Spaghetti Rustler
Wednesday, May 07, 2003

As others have mentioned, object orientation imposes structure onto your code. You will still need to code procedurally, just in smaller "chunks".

An object can have properties, methods and events. All of these are just subroutines, some of which return values. An event is basically an interrupt. The code to handle the event (interrupt) is put into a distinct subroutine. The object can raise its own events, which you can trap elsewhere.

I'm not pretending this stuff is simple or that this explanation is complete, merely that the mountain appears higher when your standing at its base. Either start climbing or move further away for a better view.

Something no-one else here has mentioned:
A fundamental of OOP is "encapsulation"; that is hiding information. This applies to objects, as the "how" something has been done cannot be seen from the calling program.

To reuse Philo's car example: How the car door is opened or how the engine is started is unknown; you just call the Start() subroutine.

Start() is a publically available subroutine, the code for which lives in the 'Engine' class.

You (the calling program) don't need to know the steps necessary to make the thing work; you just know that to make it start you call that s/r.

It does require a shift in approach to understand and use these concepts. Start with small, simple examples.

Justin
Wednesday, May 07, 2003

Objects in some languages don't have events.

John Topley
Wednesday, May 07, 2003

Augusto

I've found Matin Fowler's Refactoring http://www.amazon.com/exec/obidos/tg/detail/-/0201485672/qid=1052309955/sr=8-1/ref=sr_8_1/103-0064675-2147840?v=glance&s=books&n=507846 to be very instructive.  It gives step by step instructions on how to take an existing procedural design and refactor it into an OO design.  More subtlely, I think it imparts a sense of OO aesthetics...

It uses Java for examples, but I've used what I learned with C++. 

Steve S.
Wednesday, May 07, 2003

Thinking in Java (Eckles) is frequently recommended.  Author makes it available for legal download.  Try it and see if you like it.

http://www.mindview.net/Books/TIJ/

He also has another similar book for C++.

Ran Whittle
Wednesday, May 07, 2003

Maybe you need to take a course :

I bought 4 or 5 book about ASP.NET programming but I couldn't "get it". I would understand the instruction but not why you would do it that way.
One simple 3 day basic course with instructor and I "got it".

Or maybe the problem is changing from procedural programming to event-based programming.  I started programming during the DOS days. When I made the switch to Windows I had the learn to think in Windows and unlearn the DOS way.

Application Specialist
Wednesday, May 07, 2003

The advice so far is quite good.  However I'd inject a cautionary note as well.  You never say _why_ you're looking to learn about OOP.  If its a character-building exercise, great -- go for it.  Write some small programs and work your way up to big ones.

However it's because your manager's got a bad case of Object Happiness Disease, consider pushing back!  Traditional class-hierarchy OOP was designed for basically two reasons:

1) To cleanly and elegantly express "is a" relationships in code.  A window IS A rectangle.  A button IS A window.  etc.

2) To enable Programming In The Large -- that is, to make it easier for large teams of disparate developers to work on large software, by encouraging information hiding, modularization, explicit interface contracts, encapsulation, abstraction, etc.

There are other reasons of course, but those are the big ones.  If neither of those apply to your project, procedural languages are probably fine, particularly if that is what you are more productive in.

I see symptoms of Object Happiness Disease all the time, particularly in people who are just learning OOP.  One day they're writing great procedures, the next day their 500 line program suddenly has four virtual abstract multiply-inherited base classes with operator overloading.  All those objects seem to make them very happy, but no one else can make heads or tails of it.

Good luck!
Eric

Eric Lippert
Wednesday, May 07, 2003

Things that helped me transition:
UML (Sequence and Class diagrams)
A mentor.
Practice. Practice. Practice.

Try to code something OO then rewrite it as you learn.  This really helped me because I could see my code becoming easier to understand and more efficient.

CharlesC
Wednesday, May 07, 2003

Agree with the above statements that you have to "build one to throw away".

If you're making the shift from procedural to OO, then you will almost certainly have to make a "bad" attempt at it before it makes sense. This isn't a bad thing per se, as long as you learn from your own mistakes - which I find is often the best way of learning.

Unfortunately, this doesn't always cross over well into the commercial market. I remember my first VB project using classes, having spent several years doing purely procedural/functional programming in C beforehand. After I'd finished the project, I'd just about "got" classes, and begged to do it again properly, but there wasn't time. Eventually I ended up rewriting it as it would save time than trying to retrofit new requirements on the original code.

Work out how much margin of error is on your project. If it's mission critical, and you've never touched OO before, I'd avoid using OO on that project like the plague.

Better than being unemployed...
Wednesday, May 07, 2003

Algorithms define how you can link procedures together to perform a useful task. Design Patterns define how you can link objects together to perform a useful task. This way people recommend Design Patterns by the GoF.



On the best things to have when learning a new concept or api is example. Here is an basic implemention of the command pattern in VB.NET. A problem is that you want to undo and redo commands in an application. Conceptually what you want is to be able to keep a list of commands and traverse it up and down executing and unexecuting. The following shows a simple example in VB.NET


Module modMain
    Public MyApp As New MyApplication
    Public Sub Main()
        Dim I As Integer
        Dim Cmd As ICommand
        MyApp.CurrentPath = New Path
        Console.WriteLine(CStr(MyApp.CurrentPath.LocationX) & " - " & CStr(MyApp.CurrentPath.LocationY) & " / " & CStr(MyApp.CurrentPath.Rotation))
        CmdExecute(New PathMoveTo(10, 15))
        CmdExecute(New PathRotateBy(-45))
        CmdExecute(New PathMoveTo(10, -5))
        CmdExecute(New PathMoveTo(0, -5))
        CmdExecute(New PathRotateBy(135))
        Console.WriteLine(CStr(MyApp.CurrentPath.LocationX) & " - " & CStr(MyApp.CurrentPath.LocationY) & " / " & CStr(MyApp.CurrentPath.Rotation))
        For I = MyApp.UndoList.Count To 1 Step -1
            Cmd = MyApp.UndoList(I)
            Cmd.UnExecute()
        Next I
        Console.WriteLine(CStr(MyApp.CurrentPath.LocationX) & " - " & CStr(MyApp.CurrentPath.LocationY) & " / " & CStr(MyApp.CurrentPath.Rotation))
        For I = 1 To MyApp.UndoList.Count
            Cmd = MyApp.UndoList(I)
            Cmd.Execute()
        Next I
        Console.WriteLine(CStr(MyApp.CurrentPath.LocationX) & " - " & CStr(MyApp.CurrentPath.LocationY) & " / " & CStr(MyApp.CurrentPath.Rotation))
        Console.ReadLine()
    End Sub

    Private Sub CmdExecute(ByVal Cmd As ICommand)
        Cmd.Execute()
    End Sub
End Module

Public Class MyApplication
    Public CurrentPath As Path
    Public UndoList As Collection

    Public Sub New()
        UndoList = New Collection
    End Sub

    Public Sub DrawScreen()

    End Sub
End Class

Public Class Path
    Public LocationX As Double
    Public LocationY As Double
    Public Rotation As Double
    Public PathSize As Double
End Class

Public Interface ICommand
    ReadOnly Property Name() As String
    Sub Execute()
    Sub UnExecute()
    Function Clone() As ICommand
End Interface

Public Class PathRotateBy
    Implements ICommand
    Private Rotation As Double
    Private OldRotation As Double
    Private Target As Path
    Private Executed As Double

    Public Sub New(ByVal Rotation As Double)
        Me.Rotation = Rotation
    End Sub

    Public Function Clone() As ICommand Implements ICommand.Clone
        Return New PathRotateBy(Rotation)
    End Function

    Public Sub Execute() Implements ICommand.Execute
        If MyApp.CurrentPath Is Nothing Then Exit Sub
        If Executed Then
            If Target Is Nothing Then Exit Sub
        Else
            Target = MyApp.CurrentPath
            OldRotation = Target.Rotation
            MyApp.UndoList.Add(Me)
            Executed = True
        End If
        Target.Rotation += Rotation
        MyApp.DrawScreen()
    End Sub

    Public ReadOnly Property Name() As String Implements ICommand.Name
        Get
            Return "Path Rotate By"
        End Get
    End Property

    Public Sub UnExecute() Implements ICommand.UnExecute
        If Not Target Is Nothing Then
            Target.Rotation = OldRotation
            MyApp.DrawScreen()
        End If
    End Sub
End Class

Public Class PathMoveTo
    Implements ICommand
    Private X As Double
    Private Y As Double
    Private OldX As Double
    Private OldY As Double
    Private Target As Path
    Private Executed As Double

    Public Sub New(ByVal X As Double, ByVal Y As Double)
        Me.X = X
        Me.Y = Y
    End Sub

    Public Function Clone() As ICommand Implements ICommand.Clone
        Return New PathMoveTo(X, Y)
    End Function

    Public Sub Execute() Implements ICommand.Execute
        If MyApp.CurrentPath Is Nothing Then Exit Sub
        If Executed Then
            If Target Is Nothing Then Exit Sub
        Else
            Target = MyApp.CurrentPath
            OldX = Target.LocationX
            OldY = Target.LocationY
            MyApp.UndoList.Add(Me)
            Executed = True
        End If
        Target.LocationX = X
        Target.LocationY = Y
        MyApp.DrawScreen()
    End Sub

    Public ReadOnly Property Name() As String Implements ICommand.Name
        Get
            Return "Path Move To"
        End Get
    End Property

    Public Sub UnExecute() Implements ICommand.UnExecute
        If Not Target Is Nothing Then
            Target.LocationX = OldX
            Target.LocationY = OldY
            MyApp.DrawScreen()
        End If
    End Sub
End Class

Robert Conley
Wednesday, May 07, 2003

Walk before you run.  You're learning a completely different way of thinking about programming.  The bottom line is that it's going to take you a while before you "get" OOP.  It's not about IQ.

Read good books.  Study the code.  Try to find and work with a mentor.  Take a few courses over the next year.  Be patient, and above all else, write lots of code and learn from your mistakes.

-Thomas

Thomas
Wednesday, May 07, 2003

I second everyone's opinion that it will just take time.  I couldn't make the shift either, but after working with some big java projects, and refactoring some old code, I'd say I have a very solid, practicle grasp of OO concepts.  One thing that helped me, was to go back and look at previously written stuff that I did, and try and think about how I could better design the system to use OO principles.  I think when your first starting, its hard to build something that works the same time your trying to apply new design principles--just too much to think about.  If you try and re-design old code thats allready working, it may give you a new perspective, and you can see how it would be cleaner and more elegant if you used OO concepts.

Vincent Marquez
Wednesday, May 07, 2003

Here are some good OOP links and material: http://www.cetus-links.org/

Ian Stallings
Wednesday, May 07, 2003

Oh also, I learned OOP while transitioning to Java from a ASP/VB background and learned this acronym:

MA's PIE

Messaging
Abstraction
Polymorphism
Inheritance
Encapsulation


Maybe breaking it down into fundamentals like above can help you grasp the concepts one by one. It certainly helped me.

Ian Stallings
Wednesday, May 07, 2003

Thanks! A lot of good advice here. You guys are great !

Today I read the 1st chapter of Fowler's Refactoring book (amazon look inside). It is stuff like that I was looking for. But the remaining chapters are like a cookbook. I need more chapters like the 1st.

But, I will take it easy. I undestant it is a slow process with a lot of practice.

Augusto
Wednesday, May 07, 2003

I would suggest not bothering with the implementation/coding part and focus on the analysis and design. In particular, you might stay away from C# (and Java and C++) initially since the syntax is so much like C it's easy to slip into procedural approaches.

How about learning UML and just doing the design part of the problem (not that I'm saying UML is great, but it will force you to approach OO using new syntax, instead of C-like syntax).

Bill Tomlinson
Wednesday, May 07, 2003

Augusto:

Seeing as how you have an electronics background I would suggest that a good analogue for OO design is digital circuit design. In fact Brad Cox, the author of an OO language called Objective-C, called classes 'Software ICs'. He wrote a book about it in the late 1980's, which I think was called something like 'Object Oriented Programming'.

Think of objects as being like ICs on a circuit board. They each have functions that are activated in response the a message (signal) sent from another component. An OO program is very similar. It consists of a number of objects (ICs) each of which performs a specific function in response to a message sent from another object. The analogy can be taken deeper in that you can consider the documentation of a class to be akin to the manufacturer's data sheet for a particular IC. It tells you what the IC (class) does and how to make it do it.

The only significant difference is that the chip manufacturer makes the components for you, you just take them out of their box and solder them in place. In an OO program, however, you - the programmer - have to 'make' each object  by sending the object's class a message (typically 'new') that tells it to create the new instance. The analogy, I suppose, would be having to call up the IC manufacturer to say 'please make me an XXX' each time yu needed on. To this extent programming is more difficult than circuit design in that you have to write 'startup' code to do all the manufacturing.

Hope this is of help

David Roper
Wednesday, May 07, 2003

Umm this undoing and redoing of commands....

That's a stack isn't it?

Patterns, jeeze, who'd a thunk it.

Patterns aren't OOP,

repeat until clear

Patterns aren't OOP.

Simon Lucy
Wednesday, May 07, 2003

Doing and undoing the command isn't just a stack. How do you represent the commands on the stack to do and undo?

Chris Tavares
Wednesday, May 07, 2003

As another analogy for OOP that made a lot of sense to be as a real-time programmer back in the day:

Device drivers.

An OS defines an interface. As long as the device implements that interface, the OS can talk to it, regardless of what actual hardware is there.

Polymorphism in action.

Chris Tavares
Wednesday, May 07, 2003

its called push and pop

Simon Lucy
Wednesday, May 07, 2003

Starting from C, you have already used objects.  A C "FILE*" is an object.  It has a set of methods: fread, fwrite, fprintf, etc.  It has polymorphism: you could be talking to a file, socket, or pipe, all with the same functions.  It has data hiding: the internals of the structure are hidden from user code.  The only thing it doesn't have is an object oriented programming language.  If you have ever written something similar to a FILE*, then you've also written objects.

On another track, the language that you are using can affect how you learn the concept.  I first saw OOP with Smalltalk, where it seemed rather easy.  Another good choice might be Python, it's very easy to learn and has a very simple form of OO without all the confusig keywords and definitions.  It also allows you to mix OO and plain procedural programming (unlike Java) so you can start slower, just using existing classes, then start writing your own classes.

Tim Evans
Wednesday, May 07, 2003

don't worry about it -- you're hung up on nothing.... oop uses different words for the same thing. you're thinking proceeduraly because you're using words for the only type of programming there is, which you learned was called procedural. classes ARE functions/templates... instances are calls/saved stacks.... in "procedural" langauges, you're usually restricted to function call states/closures being valid only during a function call (vars get pushed on the stack and you use them while in a function); in procedural, you don't usually access the same data (struct, for ex) accross different function calls... in oop, the vars/state get(s) saved on the heap, and you can reference them later... to call a function against an object/state/closure is to resume the function using that context, and the current thread's cpu time.... so, you see, oop is just procedural, with some sugar to make closures easy (in c, we do this all the time with malloc, rather just putting a struct on the stack)...

so: all you need to know to get used to oop is that OOP IS AN ADMISSION THAT PPL LIKE TO REUSE STATES... between function calls...

of course, this, in and of itself, is just a sad attempt to simulate concurrency and distribution, in the physical real-world sense, on a single-threaded, time-shared cpu.

walnut hairpin
Friday, August 27, 2004

*  Recent Topics

*  Fog Creek Home