If this is your first visit, be sure to
check out the FAQ by clicking the
link above. You may have to register
before you can post: click the register link above to proceed. To start viewing messages,
select the forum that you want to visit from the selection below.

Enjoy an ad free experience by logging in. Not a member yet? Register.

Writing APIs, libraries or code that is large enough to require management, when you want to create distinct separate modules or packages that are largely independent of eachother. Object based function driven coding is often a far better choice in JavaScript - it's smaller and more efficient, but the code stays clearly ordered and code snippets are still largely independent of eachother.

Or when you write code for others to use, so that there is no need for them to actually get a knowledge of the code. (Functional style can do this as well)

Also remember that for JavaScript, the deep hierarchical inheritance trees you see in C++ or Java are far less useful than a flatter, more shallow structure. JavaScript has rather strong object orientation, but for the uses JavaScript is being put to object orientation is often not the best way to go.

Garadon: But for those purposes object orientation is overkill. There's no need at all for inheritance, and I'd say an object based system is much better suited. Have a look at my cookies library for instance: <http://liorean.web-graphics.com/scripts/cookie.zip>

That code would only have been longer and harder to read had I made it object oriented instead of plainly object based, and I still use only one global variable for it.

I also have to say using OO techniques is *always* a good thing to do. My explaination won't make much sense unless you've "been there, done that" but when i was learning JavaScript OO stuff I kept going on faith that there would be a payoff; and there was.

Object Think
Generally i think about my problem solutions in terms of objects, and the code naturally comes out that way. It is a bit different way to approach a problem; having been brought up in the traditional procedural coding style I can tell the difference.

OO code tends to be more complete. When I design my objects I tend to come up with utility functions. For example I write a toString() function to output my object's property values. Really good for troubleshooting and it's there for the next guy if he needs it.

OO code tends to be more organized. Instead of a mass of variables I group them where it makes sense and make objects and even sub-objects. This organization tends to pay off later when I'm referenceing things all over the place. Data is easily passed "in chunks" because it's all one object.

When I am thinking about this object and what IT should do I tend to write more rigorous validation code; due to OO principles such as "always keep an object in a valid state."

OO think makes you a better programmer
A lot of what goes into good object code writing is just good coding practices period. I think "my object must do A, B, and C so I write methods that do A (and nothing else), B (and nothing else), and C (and nothing else). There you just applied the principle of "maximize cohesion and minimize coupling". Miraculously this makes code easier to read, easier to modify, easier to test.

OK, you do write more code
I find this to be true. This is a natural consequence of writing better, more robust code, but it goes against the grain of web programmers. I think we get brainwashed into thinking we must write the absolute minimum code in order to "save bandwidth." Talk about your urban myths! I write so much client-side JS that fellow programmers give me "that look" (really, they do!). But no one has yet proven the down side. In the mean time I've got solid code! Can't argue w/ success.

OO code is often easier to write
When your data is organized into objects, and the functions that go with it are each "singular in purpose" (remember "maximize cohesion" above?); I've often found that the methods I write are pretty small. Oh I might have a lot of methods, but they tend to be smaller and/or less complex.

Again we get into the "less code is better" bass-ackwards way of thinking issue. "I'll save some keystrokes by putting 3 things into one function - that's good". NOT!! Writing smaller, more focused - singular in purpose - makes each function much less complex, thus easier to write, debug, read, etc.

OO code is a little more reusable
Variables and methods are encapsulated w/in the object so if you include the code in an HTML page, you don't get variable name conflicts.

A well written object stands alone. It has all the methods it needs to do what it does. These methods do what they say they do and nothing more. A well written object tends to not need more code written for it for the next time it's used.

OO code is easier to use
After we invoke the buzzwords encapsulation and abstraction we admit to ourselves that at some point we do have to write down-and-dirty detail code OF the object. BUT once that's done the magic happens. You will pleasantly discover that writing the code using the object looks and feels "higher level" than you'd expect.

Because you wrote and debugged the core object code first you find yourself focusing on the highlevel control code rather than getting distracted by trying to write and debug high level and detail code all at the same time.

After some practice with this stuff you begin to notice some things:
* your code is more modular because you wrote it "from the ground up".
* You loose the "I'm trying to write all the code all at once" feeling.
* You surprise yourself one day realizing you wrote perhaps your most complex code yet, but it works!
* Testing is easier
* You can tell you're putting out consistantly better quality code.

Garadon: Yes, the comments, spaces and indentations are removed, and I also don't close inherently closed statements by a semicolon. However, if you put those back in place you will find the code much more easy to read than it's object oriented equivalent is.

As for inheritance have a look at the JavaScript ref sticky, the object orientation section.

RadarBob: A typical procedural/imperative view, I'd say. Let me compare to the object based and functional ways of doing things:

First on all, the difference between object based and object oriented coding: One uses objects, the other uses objects with inheritance. Inheritance requires objects and instances and setting prototypes, while object based programming just requires the use of objects for storage, which object oriented programming requires as well.

Second, the functional versus imperative views: The functional view see everything as programs calling other programs, which in the end complete a task. The imperative see everything as a sequence of commands that in the end complete a task. The functional way is task oriented, the imperative way is processing oriented. Functional programming typically use scoping, closures and what is in imperative thinking called callback functions, while imperative uses statements and structures.

Object think
In object based programming, you use object for storage and performing actions. You use properties and methods in the same way as with object oriented code, but you don't utilise inheritance where it is not needed. Functions may either be part of an object as methods, which means the object is performing things. Or they may be functions taking an object for argument, and handling that object.

Function, scope, think
In functional programming functions handle data, and are in turn data themselves. Scoping provides encapsulation and closures provides privacy - so called black boxes are provided by closures, the same way object do in imperative languages. Object privacy is provided by closures, too.

Task orientation makes you a better programmer
Or, for every task the tools best equiped for the purpose. Use object orientation only if inheritance is a feature you need. Use object based programming if you only need objects as containers and abstractions related to the task. And use methods or functions depending on whether it it the object that should be doing things or things should be done with the object. Separate tasks into functions or methods of their own for easier testing, extending and modification, as well as making the code easier to read.

For each langauge a suitable abstraction
Don't think the best tools for the task are the same across langauges. JavaScript has modular, dynamic objects that are best suited for shallow inheritance trees, while for example Java has fixed, static objects that are best suited for deep inheritance trees.

Readability
Object oriented code is larger than procedureal or flat imperative code, true. It is also better structured and task separated. Functional programming is also task separated, to an even higher degree than imperative object oriented code, and object based code provides the same structural advantages as object oriented code. Which in the end means that functional and object based code is more readable and better task separated than regular object oriented code.

Reusability
Is one of the the key concepts of functional programming. The scoping and closures creation together with task orientation makes the code widely reusable because of the task separation. Scoping provides the solution to the namespace problem.

Ease of use
Task orientation makes functional code easy to use on the same way object orientation does - by task separation. The difference lies in that while object oriented code is object centered, the functional code is task centered. This makes functional code better for the purposes of achieveing a single, simple goal, or a complex task consisting of several such single, simple goals. Object orientation is better for heavy structures and data storage, but not for performing tasks.

Things you notice if you use functional, object based programming
- Your code is readable.
- Your code is modular.
- Your code is task instead of structure separated.
- Black boxes.
- Testing is easy and can be done on single instances.

EDIT: Post crossed, this one was written before the last replay of liorean.

Wow RadarBob, what an essay. I remember dimly that we engaged in OOP discussions some months ago. Nice to see that you reap now the benefits of venturing into OOPtupia.

Let me state that I fully agree to what you wrote, I've had a similar experience. The points about cohesion and coupling - very good you mentioned them. A week ago I had to customize a very complex interactive calendar script - and I was very successful because the whole script was object-oriented. I even reused some components in another script, to the calendar unrelated, running on the same page.

Code Wizard, don't get intimidated if people tell you that OOP takes longer to write and is less efficient. The efficiency issue pops *always* up in the discussion whether or not to use OOP, and has been debated to death. Usually it is countered by telling that you should optimize later after you've done some benchmarking and identified the parts of code that have to run more efficiently.

OOP doesn't take longer to write. It takes longer to define the interfaces of your objects, and the relation between them. Which objects sends which message to whom and questions like that. But once you've done this, you have very good idea of the problem space. That's the main difference between OOP and procedural programming: In the latter, you have to use the computer's way to think and model your problem in it. In OOP, you define the problem in your own vocabulary. *That* improves readability, and makes your app better to understand by others.

liorean, I don't know why you brought up inheritance. You don't need to use inheritance if you have better, more fitting alternatives, and yet your app may qualify as a true OOP app nevertheless. Often, inheritance is overused and better refactored as composition/aggregation. Remember that inheritance breaks encapsulation.
Also, I have to agree with garadon that your cookie library is not a very good example for improved readability through an object-based approach. It's nice, condensed, and probably a bandwidth save, but another developer could have written a CookieJar library in which each cookie is modeled as a separate object, and it would be still efficient to use. Some people favor sometimes features over slight margins in performance.

Originally posted by Garadon read liorean code, and if you call that easy to read ur mad in IMHO , I strongly assume that script is optimised with minimising white spaces and new lines after u coded it .

Oh and inheritance I didn't know u could that how u do that in Javascripts?

"Make things as simple as possible, but no simpler"Albert Einstein

I don't grock the syntax/style used by liorean either. But basic OO scripting w/ JS is not that esoteric. Nonetheless this supports my points. This detail code may look daunting, but USING it is quite another matter.

As for inheritance, that's a bit funky in JS. JS is NOT an Object Oriented language, it's "object based." The distinction is that features that make a language OO are not there or are weakly supported in JavaScript. Inheritance and polymorphism are the two classic features of OO, but are not "fully there" in JS, IMHO.

In fact I've been writing JS for over a year w/out using inheritance - because I didn't know how to do it. You simply won't find it discussed in virtually any published material. At times I wish I had it, but I managed. Just recently I've "seen the light". Search this forum for a recent thread; look for "closure" or "closures". That'll make your head swim...

Getting back to fundamentals... The basics of 'object based' scripting w/ JS gives you the basic encapsulation and nicely organized data / code. That's one giant leap. Get that down pat first.

Forcing(?) rigorous OO capabilities in JS is yet another giant leap. But as I understand it the basics of inheritance means utiizing the "prototype" property that every object (built-in and "home grown") has. You know that if you define a new method, for example "Array.prototype.MyFancyArrayFunction" that the "MyFancyArrayFunction" is "inherited" - is automatically available for use by every Array object. Follow the links from that thread I mentioned above, you find at least some of what you're looking for.

IMHO if we *really* need to have serious OO capabilities in web-slinging, we need to drop the "script" in "javascript", if you know what I mean.

As for inheritance, that's a bit funky in JS. JS is NOT an Object Oriented language, it's "object based." The distinction is that features that make a language OO are not there or are weakly supported in JavaScript. Inheritance and polymorphism are the two classic features of OO, but are not "fully there" in JS, IMHO.

I beg to differ on that point. JavaScript is a full fledge object oriented language that supports polymorphism. It's a prototype based inheritance, true, but it is an object oriented one. Object orientation is achieved by making the constructor functions (that are also objects) act as initiators for object instances created by using the new keyword. The prototype acts as the template for the object instances in the same way classes do in the classical inheritance model. Destructors are unnecessary as the garbage collection mechanism does that. Object instances and prototypes are not fixed, which means that in many cases adding a property or method is more effective than creating a subclass, thus the flatter object inheritance trees. Polymorphism is achieved by dynamic prototype or method overriding in instances and by scoping, but makes less of a difference since JavaScript is a dynamically typed language and you use run time object type detection coupled with forking instead of overloading functions and methods.

In fact I've been writing JS for over a year w/out using inheritance - because I didn't know how to do it. You simply won't find it discussed in virtually any published material. At times I wish I had it, but I managed. Just recently I've "seen the light". Search this forum for a recent thread; look for "closure" or "closures". That'll make your head swim...

Getting back to fundamentals... The basics of 'object based' scripting w/ JS gives you the basic encapsulation and nicely organized data / code. That's one giant leap. Get that down pat first.

Forcing(?) rigorous OO capabilities in JS is yet another giant leap. But as I understand it the basics of inheritance means utiizing the "prototype" property that every object (built-in and "home grown") has. You know that if you define a new method, for example "Array.prototype.MyFancyArrayFunction" that the "MyFancyArrayFunction" is "inherited" - is automatically available for use by every Array object. Follow the links from that thread I mentioned above, you find at least some of what you're looking for.

IMHO if we *really* need to have serious OO capabilities in web-slinging, we need to drop the "script" in "javascript", if you know what I mean. [/B]

They are both object oriented. Java has a more complete system bewcause it has parameters that allow super/sub refrencing, but that is something that could be added to JavaScript easily, had ECMA chosen to go that way. (They didn't. They change to Class based inheritance in the fourth revision, currently being written.) The prototype object allows single object inheritance, and together with JavaScript's dynamic typing and inheritance, it allows a more modular inheritance model than that Java has.

Back to the original question, here's a good example of why OOP is a good thing to do. Suppose you've coded a widget for a web page using normal coding methods. Later on you decide you need two widgets on the page so now you have to create a second copy of your code using unique variable and function names. Then it becomes obvious that four widgets would be even better, guess what your going to have to do now .

However, if you coded the first widget using OOP methods then all subsequent uses would require nothing more than an additional invocation of the created object.

Check out the Forum Search. It's the short path to getting great results from this forum.

Originally posted by Roy Sinclair Back to the original question, here's a good example of why OOP is a good thing to do. Suppose you've coded a widget for a web page using normal coding methods. Later on you decide you need two widgets on the page so now you have to create a second copy of your code using unique variable and function names. Then it becomes obvious that four widgets would be even better, guess what your going to have to do now .

However, if you coded the first widget using OOP methods then all subsequent uses would require nothing more than an additional invocation of the created object.