Sample introductory Object Oriented Programming code in
php, java, and C++ showing the similarities and differences.
With the possible exception of large, long-term projects, OOP, despite all the hype, is a lot more expensive to write and to maintain than clean structured code. The reality of it does not live up to the theory, and the hype is often “smoke and mirrors” unfortunately.
This simplest of introductions to it, like the one here, is enough to convince a logical, rational, person that “There is something wrong here.” It is too complicated, convoluted, to be a realistic alternative.
PHP
1st class definition and obj: Example
class Example { // Private class-wide variables (the default here in php): var $var1; var $var2; //function to assign-set two numbers function set_numbers($number1, $number2) { $this->var1 = $number1; # assignment of 1st class-wide variable $this->var2 = $number2; # note: class variables are accessed differently } //function to add numbers together - get the total function add_numbers() { return ($this->var1 + $this->var2); } } // end of class "Example" /* * $var1 and $var2 are [private] available only within the class. * You must access them inside a function within the class by using * the syntax $this->variablename * notice the "$" on "this" not on the variablename * ************************************************** * To use this class, create an instance of the Example class (object) */ // create an object variable for the instance // of the Example class - using the "new" function $exampleobject = new Example; // With an instance of the Example class, you can use the // functions (or "methods") inside of it: $exampleobject->set_numbers(1,3); # calling function set_numbers() echo "the total is ".$exampleobject->add_numbers() ; // the output will be: the total is 4 $cpy = $exampleobject; $cpy->set_numbers(2,4); echo "the total is ".$exampleobject->add_numbers() ; // we will get "6" in php5 and C++, java, etc. // a php "extra": clone($exampleobject); $cpy2 = clone($exampleobject); echo "the total is ".$exampleobject->add_numbers() ; // we will get "the total is 4" ... clonning the obj. instead of the class
/* * * end of PHP class definition: Example * * */
JAVA Java HelloWorld class definition class HelloWorld { public static void main(String[] args) { String text = new String("I'm a simple Program "); System.out.println(text); String text2 = text.concat( "that uses classes and objects"); System.out.println(text2); } } /* ************ end of Java HelloWorld class definition ************ */ /* ************** dog class definition and obj in Java *************** */ class dog { // "public" is the default Private int size; String name; // the compiler initializes all "instance"(object) variables for you // int=0; floats=0.0; string=null; boolean=false; references=null; public // this makes explicit the default: the (3) methods are public int getSize() { return size; } void setSize(int siz) { size = siz; } void bark() { // you must initialize local (method) variables, the compiler doesn't // (however, there are none in this 'dog' class) if (60 <= size) { System.out.println("Wooof! Wooof!"); } else if (20 <= size) { System.out.println("Ruff! Ruff!"); } else { System.out.println("Yap! Yap!"); } // != (not=); || (or); && (and) } } // * * * * note: make variables private and methods public * * * * /* * * * * code to call/use the class which is, itself, a class * * * * */ class dogtest { public static void main (String[] args) { dog mydog = new Dog(); mydog.setSize = 70 ; System.out.println("Dog mydog Bethoven: " + mydog.getSize() + " lbs." ); mydog.bark(); } }
/* ************ end of Java dog class definition and obj ************* */
/* ************* C++ ************** */ /* ************ bird class definition and obj in C++ ************* */ #include #include using namespace std; class bird_class { private: int number_seen; // not accessable outside the class, the default public: string name; // "private" is the default void increment_count() { number_seen++; // set the count } int get_count() { return number_seen; // get the count } // public explicit declaration of constructor class: bird_class(string text); // here, the class is constructed to be a string obj. }; // initialize variables in the explicit constructor: bird_class::bird_class(string text) { name = text; // text is an incoming string and assigned to 'name' number_seen = 0; // value initialized } /* ********* "entry point" with code to call/use the class ********* */ int main() { bird_class orioles("oriole"); // create instance & set name (& #seen=0) orioles.increment_count(); cout << "number of " << orioles.name << "s seen: " << orioles.number_seen << end1; return 0; } // in this C++ example, it is good to "build in" the // initialization of the number_seen variable. C/C++ programmers // maintain the habit of always initializing variables; // C# programmers don't: In .NET, the Common Language Runtime (CLR) // [processor?] expressly initializes all variables as soon as they // are created. Value types are initialized to 0 and reference // types are initialized to null. Programmers only initialize values other // than 0 and null. // C vs. C++: main() does not need a 'return' value in C // but, in C++ main() becomes int main() because a 'return' value is // required and return 0; tells the operating system that the program // ended normally.
/* ************ end of C++ bird class definition & obj *************** */
/* ************* Theory ************** */
"Creating and using a set of functions, versus creating and using (OOP) methods (functions) grouped into classes isn't very different in some ways. There are benefits and advantages as well as costs and disadvantages to using classes (of functions) instead of simply using a list of functions."
/* ************* & experience ************** */
The greatest, overall, disadvantage to OOP is the 2 (to 4?) times increased day-to-day cost of having to become aquainted with all the custom functions which are written to replace the known, standard, functions, built into every programming language and learn whole, independant, sets of them created in every oop application, meaning, learn another whole, independant, set with each and every oop application - so, you cannot gain from experience. Every application is written independantly.
Savings "down the road" claimed for OOP is more myth than reality. Even when you have learned the new set of functions-methods etc., there is always more overhead in constructing classes, methods and "objects" as opposed to simple functions or procedures. OOP is often "Penny wise and pound foolish". Application programming gets more and more complex year after year. "Keep it simple stupid" becomes more imperative, not less. A company must remain competitive or loose market share ... or go out of business. If its IT dept. becomes cost-prohibitive, it could scrap the dept. and "out-source" in order to survive.
Back when operaing systems had 100,000 lines of code to several 100,000 lines of code, the infamous "goto" of "spagetti" code was the bane of programming, the "crutch" that could double the cost of a software enhancement - modification project. Where these new oop languages have forced programmers to create functions-methods and, in so doing, break free from the old habits, languages and "spagetti" code and start from scratch, they have done a service. To the extent that C/C++ has not changed, it is still an issue to watch out for.
...
for an example of a very simple concept taken to an OOP extreme, consider the "MVC", Model-View-Controller, concept implemented with oop: "Building a simple MVC system with PHP5" at http://www.phpit.net/article/simple-mvc-php5/ Dennis Pallett is the author who provides a very clear, concise, tutorial on doing it with oop.
Despite all his success at making it as simple and clear as possible, it makes it very clear just how complicated and convoluted, oop can make things. Consider that most blogs and most e-commerce packages have been doing it since before oop and any time you create a page that pulls in different data depending on a parameter (?) passed in to it, you have accompolished it.
"Personally I've found design patterns the best way to learn the real value of OOP."
- an oop convert
DESIGN PATTERNS
The Observer pattern - "trigger" -- (observe and react - behavioural)
The Observer pattern is defined by the Gang of Four in Design Patterns as behavioural pattern - that is one we can use to modify the behaviour of our applications. It's regarded as being so useful, that Sun implemented it in the Java API
The basic principle behind the observer pattern is if you have some object, such as a Post object for a forum system, you can have other objects, such as a Mailer object, act as an observer and respond to any changes in the Post object, such as emailing relevant forums users that a new post has been added to the thread they were subscribed to.
Conceptually, the Observer pattern is something like a trigger in a database, which runs a stored procedure when a table row is modified.
// Base Observerable class php class Observable { var $observers; // an array of Observer objects to notify var $state; // state of this observable object //! A constructor // Constructs the Observerable object ... & initializes var's function Observable() { $this->observers=array(); } //! An accessor // Calls the update() function using the reference to each // registered observer - used by children of Observable // @return void function notifyObservers() { $observers=count($this->observers); for ($i=0;$iobservers[$i]->update(); } } //! An accessor // Register the reference to an object object // @return void function addObserver(& $observer) { $this->observers[]=& $observer; } //! An accessor // Returns the current value of the state property // @return mixed function getState() { return $this->state; } //! An accessor // Assigns a value to state property // @param $state mixed variable to store // @return void function setState($state) { $this->state=$state; } } // Base Observer class class Observer { // Private // $subject a child of class Observable that we're observing ? var $subject; //! A constructor // Constructs the Observer // @param $subject the object to observe function Observer(& $subject) { $this->subject=& $subject ; # "& $subject" is a pointer // Register this object so subject can notify it $subject->addObserver($this); } //! An accessor // Abstract function implemented by children to repond to // to changes in Observable subject // @return void function update() { trigger_error ('Update not implemented'); } } ? >