SitePoint Sponsor

User Tag List

Results 1 to 11 of 11
  1. #1
    SitePoint Evangelist tetsuo shima's Avatar
    Join Date
    Oct 2005
    Location
    Switzerland
    Posts
    597
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Come back to procedural code at times?

    Hi,

    Been deep into OOP for a while now.

    I found myself in an interesting situation lately that I would like to discuss here. I was away from my library, couldn't use any framework and had to build a small application real quickly.

    For some reason, I went the procedural way. And I found this experience very refreshing and useful. So I was wondering, should we sometimes come back to procedural code? Can that be of some use to us or should it be definitely left behind? One of PHP idiosynchrasis is the procedural approach, so is there something to learn from it, that we could then bring back into our OO practice?

    During the last months, I've been trying to use as few design patterns as possible, going the composition and aggregation ways as much as I could instead. Theoretically, can I relate this procedural experience to this new approach, like an unconscious act, or is it just about circumstances?

    As you can see, I am wondering if I should make the effort to go back to a procedural approach in order to try to discover some secrets, hidden in it, that could change and improve my OO approach.

    The SEO Faq thread
    Dependency injection made easy: Phemto

  2. #2
    SitePoint Evangelist hexburner's Avatar
    Join Date
    Jan 2007
    Location
    Belgium
    Posts
    591
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    The procedural way, I would call it structured programming, is used to break a problem into routines. It emphasises functionality but does not stress data.It is particularly appropriate for applications that have a lot of independent functions that don't interact much. It is more appropriate for problems where functionality is more likely to change than data.

    In contrast to that, object-oriented designs work well at a higher level of abstraction. They facilitate the designing of modules, decomposing a problem from the top level down. They are especially appropriate for problems where the data is more likely to change than the functionality.

    At the point at which you have identified the object interfaces (based on the data structures), and you start designing the code to support them within the modules, it is usual to switch to a structured design.

    Object-oriented techniques seem to be a better solution for the coherent design of large projects. However, structured techniques are still useful on any but the largest projects.
    FOR SALE: 1 set of morals, never used, will sell cheap

  3. #3
    SitePoint Guru
    Join Date
    Nov 2002
    Posts
    841
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    The term structured programming has a specific meaning, which has more to do with structuring conditionals and avoiding goto statements. (my thoughts on goto). I learned to program in the 80s where there was much exhortation to switch to the structured style. The structured camp came along with a set of techniques, such as flowcharting.

    Mostly, structured programming has won. Many modern and popular languages don't even allow multiple points of entry into a segment of code. Strict structured programming would also dictate a single exit point. However years of collective experience has shown this to be far less confusing. I don't think anyone strives for this goal anymore. Other things, like flowcharting have entirely disappeared.

    I think there are parallels to the adoption of structured programming in the adoption of object oriented programming. I think some of the charts and processes for OO programming that were developed in the 90s will eventually fall by the wayside. For example, most programmers can read a flowchart, but few would consider it a good idea to produce one, except in very specific circumstances or for educational purposes. I think things like UML diagrams will end up the same way.

    So which aspects of OO are important?

    The abstraction axis of generalization and specialization gets alot of attention. This plays a role, but I think as people become more comfortable with objects, they use inheritance less and delegation more.

    I think a better indicator of the difference between OO and procedural is the factoring of conditionals via polymorphism. Good OO code has fewer conditional statements, especially switch statements.

  4. #4
    SitePoint Enthusiast
    Join Date
    Jan 2006
    Posts
    51
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I find that for the larger projects, especially those with more complex data, I go object oriented. For smaller projects, as long as the data is relatively simple (e.g. not hierarchical), I often use procedural programming because it's faster and often less complex.

    Just like you want to pick the right programming language for each job, pick the right paradigm.

  5. #5
    SitePoint Evangelist
    Join Date
    Aug 2004
    Posts
    428
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    uml will never disappear.

    I think things like UML diagrams will end up the same way.
    will never happen; it standardizes how problems [usecases] or solutions are described [sequence, state, object diagram ...]
    http://en.wikipedia.org/wiki/Unified_Modeling_Language

    documenting your work with uml and using appropriate design patterns allows a new employee get to speed on things much quicker. If anything uml savy individuals are in demand.

    true for web, desktop, and even for embedded systems:
    http://people.tamu.edu/~leblanc/seni...oller%20v2.png

  6. #6
    simple tester McGruff's Avatar
    Join Date
    Sep 2003
    Location
    Glasgow
    Posts
    1,690
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I can't think of a reason why I'd personally use procedural code except in the simplest of command line scripts. I never think of OOP as making things more complicated: it's a way to manage the complexity which already exists but which might not have been understood. An object wraps up behaviour and data but procedural leaves different threads of logic tangled up together.

    Each object is a discrete (testable) component in a larger machine with a defined responsibility. This creates different levels of detail. "Throw the ball" is much easier than saying "release 2mg of adrenalin to boost heartbeat, contract right deltoid 35% balancing with 5% tension in the infraspinatus and etc etc " (OK I made that up and probably just killed the patient but you get the picture). I can open up a component to look at the detail if necessary or I can just pull levers and push buttons and not have to bother how it does its job. A different type of mind might have the ability to be conscious of a thousand things at once but us humans are more limited. The information processing device we're really writing code for is not the beige box which plugs into the mains. A computer will happily gobble up any old crap so long as it's parsable but trying to understand and maintain it is another matter.

    If the app is designed in the right way different behaviours can easily be created simply by aggregating different objects. You can almost guarantee that the first write will have to be changed. Your ideas will be refined as you learn about the domain or new requirements will be requested. The arm can be replaced with CricketBallThrower or BaseballPitcher - or SuperBionicArm if you really want to win. I'm not sure if you can adequately define the concept of "ball throwing appendage" procedurally. OK code can be organised into functions but they quickly look like classes struggling to be born. Classes are more powerful tools and it's all down to their plasticity. You're free to invent whatever concepts you need to express the problem in the simplest, clearest way you can think of.

  7. #7
    SitePoint Addict Jasper Bekkers's Avatar
    Join Date
    May 2007
    Location
    The Netherlands
    Posts
    282
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by tetsuo shima View Post
    Hi,
    As you can see, I am wondering if I should make the effort to go back to a procedural approach in order to try to discover some secrets, hidden in it, that could change and improve my OO approach.
    One of the things you will, hopefully, discover is that they're both te same thing. Good procedural applications are written in an object-oriented way. Take a small look to see what I'm sayin'.

    PHP Code:
    <?php
    function Employer_pay($this = array(), $employee = array())
    {
        
    Employee_receiveSalary($employee$this['pays_employee']);
    }

    function 
    Employee_receiveSalary($this = array(), $amount)
    {
        if(
    $amount $this['minimum_salary'])
            
    Employee_resign($this"You didn't pay me enough");
    }

    function 
    Employee_resign($this = array(), $reason)
    {
        echo 
    $reason;
    }

    $employer = array('pays_employee' => 50);
    $employee = array('minimum_salary' => 60);

    Employer_pay($employer$employee);
    Versus
    PHP Code:
    <?php
    class Employer
    {
        var 
    $pays_employee;
        
        function 
    __construct($amount)
        {
            
    $this->pays_employee $amount;
        }
        
        function 
    pay($employer)
        {
            
    $employer->receiveSalary($this->pays_employee);
        }
    }

    class 
    Employee
    {
        var 
    $minimum_salary;
        
        function 
    __construct($amount)
        {
            
    $this->minimum_salary $amount;
        }
        
        function 
    receiveSalary($amount)
        {
            if(
    $amount $this->minimum_salary)
                
    $this->resign("You didn't pay me enough");
        }
        
        function 
    resign($reason)
        {
            echo 
    $reason;
        }
    }

    $employer = new Employer(50);
    $employee = new Employee(60)

    $employer->pay($employee);
    Design patterns: trying to do Smalltalk in Java.
    I blog too, you know.

  8. #8
    SitePoint Enthusiast Chousho's Avatar
    Join Date
    Jun 2006
    Posts
    97
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    This is an interesting thread for me. I'm coming from procedural and reading up a lot on OOP. So far I'm getting the ideas, but I can't see any reason to build a class for a function that I'll use on one page, perhaps only one time.


    --edit--
    Just noticed your name (talking to Tetsuo), hehe. Nice
    Last edited by Chousho; Jun 2, 2007 at 14:15.

  9. #9
    SitePoint Guru
    Join Date
    Nov 2002
    Posts
    841
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by Jasper Bekkers View Post
    One of the things you will, hopefully, discover is that they're both te same thing.
    I've been preaching this for a long time. General principles of writing good code are the same for both procedural and object oriented code: loose coupling, strong cohesion, encapsulation, information hiding, interfaces, duplicate code elimination.

    I see objects as merely a higher order way of grouping code. Objects are a grouping of functions (among other things). Because of this they are both more complicated, but also more powerful.

    I think the things that are unique to objects both fall under the category of eliminating duplicate code. These are inheritance and polymorphism. What I see is that more experienced OO developers use inheritance less than the novices and polymorphism more. Hmmm.

    Looking at things in terms of duplicate code elimination helps introduce a sense of scale to the procedural vs. OO decision. If you don't have much duplication because your app is small or you are only doing something once, then the complexity and power of objects don't provide a good return on investment. As you gain in size and duplication, then the ROI of the more advanced duplication elimination techniques improve.

    There are situations where the extra complexity is balanced by a clarifying factor. For example, you might want to encapsulate some code in a function, even if that function is only called once, because doing so allows you to give it a name and thus ends up creating self documenting code. Doing this is probably better than adding a comment to your code.

    Regarding UML, I find it to have an extremely low ROI. It has its uses, in special situations, but is not a good general tool. Wait a decade. You'll see.

  10. #10
    SitePoint Addict Jasper Bekkers's Avatar
    Join Date
    May 2007
    Location
    The Netherlands
    Posts
    282
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by Selkirk View Post
    I think the things that are unique to objects both fall under the category of eliminating duplicate code. These are inheritance and polymorphism.
    Although you introduce al little overhead, you can implement inheritance and polymorphism in procedural languages by just manually implementing and maintaining a vtable, if you're willing to spend some time on it you might even implement data encapsulation and multiple inheritance (no one will know why ).

    A trivial example of that in PHP:
    PHP Code:
    function call($object$function$arguments null)
    {
        if(
    $arguments == null$arguments = array();
        
        if(isset(
    $object['___vtable'][$function])) // virtual call
            
    return call_user_func_array($object['___vtable'][$function] . '_' $function, array($object) + $arguments);
        else
            
    trigger_error('Undefined method ' $object['___vtable'][$function] . '_' $function);
    }

    function 
    create($class$parent null$virtuals null)
    {
        
    // build virtual table and inherit
        
    $object = array('___class' => $class);
        
    $vtable = array();
        foreach(
    $virtuals as $name)
        {
            if(
    function_exists($class '_' $name))
                
    $vtable[$name] = $class;
            else if(
    $parent != null)
                 if(
    function_exists($parent '_' $name))
                    
    $vtable[$name] = $parent;
        }
        
    $object['___vtable'] = $vtable;
        
        
    // call constructor
        
    if(function_exists($class '_initialize'))
            ${
    $class '_initialize'}($object);
            
        return 
    $object;
    }

    function 
    House_openDoors($this)
    {
        echo 
    "Opening house doors";
    }

    function 
    Villa_openDoors($this)
    {
        echo 
    "Opening villa doors";
    }

    function 
    Vill_poolLights($this$state)
    {
        echo 
    "Pool lights are ", ($state 'on' 'off');
    }

    $house create('House''', array('openDoors'));
    $villa create('Villa''House', array('openDoors'));

    // use dynamic dispatch
    call($house'openDoors');
    call($villa'openDoors');

    Villa_poolLights($villatrue); 
    Take a look at it and compare it to:
    Code C++:
    class House
    {
    public:
        virtual void openDoors()
        {
            std::cout << "Opening house doors";
        }
    };
     
    class Villa : public House
    {
    public:
        virtual void openDoors()
        {
            std::cout << "Opening villa doors";
        }
     
        void poolLights(bool a_State)
        {
            std::cout << "Pool lights are " << (a_State ? "on" : "off");
        }
    };
     
    House *l_House = new House();
    Villa *l_Vill = new Villa();
     
    l_House->openDoors();
    l_Villa->openDoors();
     
    l_Villa->poolLights(true);

    Do you spot a difference?
    Design patterns: trying to do Smalltalk in Java.
    I blog too, you know.

  11. #11
    SitePoint Evangelist
    Join Date
    Aug 2004
    Posts
    428
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    wow

    so thats how its done in the background eh

    i think maintaining the vtable idea begins to break down the more complex your app becomes.

    delicate function names.

    Example you misspelled villa. Vill_poolLights .. so you end up with runtime errors instead of compile time errors. The most i use are function pointers and my beautiful structs... but in c you also don't have hash arrays..[1]

    so this idea eventually becomes useless.

    i would probably use something like this in c... if i really needed it.
    typedef struct
    {
    void (*opendoor) ();
    void (*poolLights)(int);
    }House;


    House house[2];

    house[0].opendoor = House_openDoors;
    house[1].opendoor = Villa_openDoors;
    house[1].poolLights = poolLights;

    void execute(House *h)
    {
    if(h->poolLights == '\0')
    {
    //type house
    }else
    {
    //type villa
    }
    }


    other than that both outputs look the same.


    Regarding UML, I find it to have an extremely low ROI. It has its uses, in special situations, but is not a good general tool. Wait a decade. You'll see.
    its already past a decade. and every once in a while i still have to draw a flow chart. eliminates hand waving during presentations. If your selling the idea to your peers, to a client who is not tech savy (use cases, flow charts, quad chart) ... it has a very high ROI. Not to mention that ms visio brings it to the masses.



    [1] http://www.thescripts.com/forum/thread215981.html
    Last edited by leblanc; Jun 3, 2007 at 11:34.


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •