Object Oriented

Status
Not open for further replies.

bjrady

Seniorius Lurkius
31
In college I was heavily into Object Oriented programming and design. When I got out of school I got a job as a OO desginer/coder working in Java (Which is an OO language...if you use it correctly, that is). As such, it's hard for me to see things from the other side of the fence (Procedural style), but there's still a lot of people out there who are convinced that OO is more trouble than it's worth.

If you're one of those people, what are your reasons? Stuck in legacy code? Never learned any Object Oriented techniques?
 

Pont

Ars Legatus Legionis
26,160
Subscriptor
You know java, so you know how to do Hello World in Java. I don't feel like writing it now.

Here's Hello World in perl
code:<HR>
Code:
#!/usr/bin/perl -w
print "Hello World!\n";

Compare that to Hello World in Java. In java you have to implement a class just to print Hello World.

OO programming has significant overhead in performance and initial development effort. For large, complex projects that must be extensively designed with a Model/View/Controller paradigm or some such, the initial overhead of an OO design may be worth it. Many problems, however, are simply stated and do not need to be modelled.

Furthermore, for apps that need to eek out every ounce of performance possible, you need a procedural language. You might use a loose object-oriented framework to set things up, but you need to know exactly what is happening during the main game-loop. OO is designed to ease software design, not to increase performance. AFAIK, most games are written in C or C++. The ones that are written in C++ probably use some OO principles to set up a scene or the menus or something, but the input/render/network loop is probably written procedurally (i.e. it's really C).

Some rules of thumb:

For applications that are interactive and persistant (no definitive program end), especially if they model a real-world system, OO is probably the way to go.

For meat-grinder applications, where data comes in, gets processed, and gets spit out (like converting an AVI to an MPEG), procedural is the way to go.

"System" => Object Oriented
"Task" => Procedural

[This message was edited by Pont on November 26, 2001 at 17:47.]
 

kenada

Ars Legatus Legionis
17,589
Subscriptor
Java is a procedural language that facilitates object oriented design. OCaml is a functional language that facilitiates object oriented design. Some languages have a higher barrier than others (e.g., C v Java).

IMO 'OOP' isn't a paradigm unto itself but one that compliments existing ones (e.g., like DbC compliments OO design and procedural programming in Eiffel).

Edit: BRAIN: Parse error. Mismatched parenthesis in second paragraph.
 

bjrady

Seniorius Lurkius
31
Originally posted by Pont:

"System" => Object Oriented
"Task" => Procedural

For the most part, I'd agree with you. Code that is written once and never changed could be written in polish by a circus monkey and as long as it works, who cares how it's designed. However:

A) You don't always know when you're going to need to change something

B) A good OO design can speed up a system much more than hand-tuned procedural code. Remember, the fastest code is the code that's never executed. Also, OO design is all about how objects interact...what goes on inside them is almost irrelevant. I've seen OO models where the guts of the classes have inline assembler in them.

C) You might not ever need to change the program itself, but it might be nice to reuse the code in it for something else.

It's all a matter of overhead. It makes no sense to spend a week on a OO model for a program that takes you a day to code, but at the same time, spending an extra 20 minutes to do it the OO way...just in case...is almost always worth it. Also, once you start thinking in the OO frame of mind, it's easy to go back and hack out a piece of code. If you've been hacking code for 20 years, it's going to be a lot harder to learn how to do it the 'right' way.
 
D

Deleted member 5324

Guest
Originally posted by bjrady:
B) A good OO design can speed up a system much more than hand-tuned procedural code. Remember, the fastest code is the code that's never executed. Also, OO design is all about how objects interact...what goes on inside them is almost irrelevant. I've seen OO models where the guts of the classes have inline assembler in them.

Find me one example of a good OO design speeding up hand-tuned procedural
code.

Jeremy
 

John

Ars Praefectus
3,789
Subscriptor++
Find me one example of a good OO design speeding up hand-tuned procedural code.

First, speed is rarely the number one priority (otherwise we'd all still be writing everything in assembly). Second, "OO" does not necessarily mean "written in C++, Java, etc." You can write "OO" code in C, or even in assembly. In fact, I content that any sufficiently complex program that is well designed and maintainable will make extensive use of OO design techniques (encapsulation, method/data inheritance, etc.) no matter what language it's written in. I've certainly seen a lot of "hand-rolled OO" in C. And while certain languages encourage (or require) OO design, very few languages forbid OO design techniques.
 

MooseAreFun

Ars Legatus Legionis
10,827
Subscriptor
You know java, so you know how to do Hello World in Java. I don't feel like writing it now.

Why do people make such a fuss of text out in Java?

File HelloWorld.java
code:<HR>
Code:
public class HelloWorld {
     public static void main(String[] args) {
          System.out.println("Hello World");
     }
}

File HelloWorld.C (IIRC)
code:<HR>
Code:
#include <stdio.h><P>void main(char[]* argv, int argc){
     printf("Hello World");
}

File HelloWorld.CPP
code:<HR>
Code:
#include <iostream><P>void main(){
     cout << "Hello World" << endl;
}

What's that, 5 Java lines to 4 C lines to 4 C++ lines? Why is that considered easy in C and complicated in Java?
 

MrMills

Ars Praefectus
3,727
Moderator
Not that it's related to the task at hand in any way, but here's Hello, World! in INTERCAL:

Code:
DO ,1 <- #13
PLEASE DO ,1SUB#1 <- #234
DO ,1SUB#2 <- #112
DO ,1SUB#3 <- #112
DO ,1SUB#4 <- #0
DO ,1SUB#5 <- #64
DO ,1SUB#6 <- #194
DO ,1SUB#7 <- #48
PLEASE DO ,1SUB#8 <- #22
DO ,1SUB#9 <- #248
DO ,1SUB#10 <- #168
DO ,1SUB#11 <- #24
DO ,1SUB#12 <- #16
DO ,1SUB#13 <- #214
PLEASE READ OUT ,1
PLEASE GIVE UP
 

TheBorg

Ars Tribunus Angusticlavius
8,555
John:
First, speed is rarely the number one priority (otherwise we'd all still be writing everything in assembly).

If you're speaking within the world of academia, that may be true. My professors aren't interested in how fast as much as how elegant my code is. But, if you're out in the salary-paying world speed is often the ONLY priority. I can't imagine my customers waiting twenty times as long as they need to for a million row rip through a database and not wanting to tear my head off instead. The reason why we don't all write everything in assembly is because there is a tradeoff between performance and codability - at the one end we have assemblers (and microcode and angels dancing on the heads of pins) which are very fast and very hard to understand, at the other end we have OO languages which are typically bloated and slow but very easy to understand, and in the middle are the languages that balance the two.

Second, "OO" does not necessarily mean "written in C++, Java, etc." You can write "OO" code in C, or even in assembly. In fact, I content that any sufficiently complex program that is well designed and maintainable will make extensive use of OO design techniques (encapsulation, method/data inheritance, etc.) no matter what language it's written in. I've certainly seen a lot of "hand-rolled OO" in C. And while certain languages encourage (or require) OO design, very few languages forbid OO design techniques.

Wellll - no. There's a difference between object-like and pure object-oriented languages. C++, for example, is generally agreed to NOT be an object-oriented environment for at minimum two straightforward reasons: 1) it allows you to write code in a non-object oriented fashion, and 2) it allows you (through dynamic memory structures) to get behind the objects in memory and expose their structures and data, which is a no-no. Java IS an object-oriented environment - even simple or bad programs must follow the paradigm. You can have languages that allow certain OO attributes, but it's difficult to find an imperative, logical or functional language that incorporates encapsulation, inheritance and polymorphism.

Having said all that, I agree that you can practice object-like techniques in everyday, procedural programming - you model things in a real-world fashion and try to build your data structures so they only expose the parts that need to be seen. I always design databases that way - mapping out the model in this way gets you farther along in normalization.

*deeeeeeep breath*

theBorg
 

TheBorg

Ars Tribunus Angusticlavius
8,555
Try Java versus C or heck, try Java versus VB6 for that matter. Java is typically at least a full order of magnitude slower than compiled languages (or quasi-compiled ones like VB). It's one of Java's biggest weaknesses, but it's a tradeoff to it's strength of being very cross-platform (although it's more like "write once, debug everywhere" ;)) and OO.

I did some simple testing (W2K) and rewrote a honking database traversal (HP-UX) to test it, and it was slower in both cases. While you're at it, check out the resource usage - Java takes quite a bit of memory overhead to do its thing.

theBorg

P.S. I did this testing last year, although I still believe it's friggin' slow. If anyone has any more recent information on Java performance I'll listen attentively.
 

TheBorg

Ars Tribunus Angusticlavius
8,555
"peed is often the ONLY priority"? Is "ONLY" an acronym in that sentence or something? I stand by what I wrote: speed is rarely the number one priority.


Okay, I got tired of doing italics :D Sheesh, I go through that dissertation and that's the only thing you can point out? So what you're saying is that while everyone else is inside sitting down, you're "outstanding"? ;)

Seriously, I appreciate your conviction in your viewpoint, especially when you realize that making a statement like "speed is rarely the number one priority" without backing it up invites just a single counterexample to burst it into flames. For example: If I'm doing transaction processing on a large scale (ie, dozens or hundreds of transactions per second), which would be (and I'll resist caps this time) the number one priority:

1) the elegance of the language
2) the niftiness of the user interface
3) The reusability of the code in later projects
4) raw, unabashed processing power

If you selected 4), you're right! And if you're right, you're therefore wrong! Sometimes performance is the most important thing. Sometimes it's a combination of things (like a tradeoff between speed and quality of error-checking). And yes, I'll admit that sometimes issues like supportability or richness of structure is more important than speed, but it's not enough to put performance at the bottom of the list.

Anyway, I have to get back to this pesky language theory term paper I have yet to start. Thanks for the chat.

theBorg
 
As one who has been applying oo techniques for 20 years no matter what language he is forced to code in, I can tell you that there is a HUGE difference between "applying OO techniques to solving a problem" and "using all the features of an OO language". I learned the application of OO using simula and have applied it in every language I have used since. The fact that I have full access to the structured without using the defined interfaces when writing in assembly does not make my implementation non-oo (at least not by any definition I have seen but I suppose there could be some that define it that way). It merely puts the burden of using the defined interfaces on me the programmer, not on the compiler.

Put another way, a craftsperson will not allow themselves to be limited by primitive tools but bigger faster and more powerful tools will not help the less skilled do the job any better. Give a master woodsmith a tree branch and a sharp knife and (s)he can make you a table leg. Give a weekend warrior the same tree branch and a power saw and (s)he will cut their OWN leg off.

I have seen clearly designed object heirarchies, properly encapsulated with well defined inheritance implemented in assembly language and I have seen sloppy code destroyed with operator overloaded multiple inheritance written in java because the programmer failed to stop and think out the solution before coding.

p.s. my answer to your quiz is

5) the accuracy of the results :)
 

Agathos

Ars Praefectus
3,558
Subscriptor
Java is typically at least a full order of magnitude slower than compiled languages (or quasi-compiled ones like VB).
Sounds to me like you have less a problem with OO than you do with interpreted languages. Heck, if I wrote a program in OO C++ and then wrote the same thing in a procedural, interpreted language, I think I'd find the OO program running several times faster.
I also think you're a bit too dismissive of the sometimes pressing need for rapid development. If a nifty and elegant language can help me write in a week what would take a month in C, even a 20x speed difference may be a fair price.
And now for some nitpicking: it takes more than a single counterexample to refute a statement if that statement is modified by the word "rarely" instead of "never." "Rarely" allows for counterexamples, as long as they're uncommon. But then, proving they're common or uncommon gets into statistics, which makes me sleepy.
 
ah, I was under impression that Java doesn't allow multiple inheritance.

As for OO vs procedural, its been my experience that well designed code is the most often the fastest. OO techniques often provide me the right tools for the job. Remember, 90% of your execution time will be in 10% of your code. So, I don't think its fair to say that OO code will be slower than procedural. Since, the vast majority of your code will not be speed critical, providing more abstractions that hopefully provide better maintainability and readability are worth it 100% of the time. When speed is paramount, alway look for a better algorithm first. Show me a hand coded bubble sort in assembly, and I'll show you a quicksort written in any compiled language that will be faster. Now, that's a bit of a contrived example, but I think it demonstrates my point. Speed of execution is more dependent on the algorithm than on the language and/or design techniques used to implement it.
 

Anton

Seniorius Lurkius
36
I think one of the reasons people perceive Java to be slower than C++ and the like is because Java hides most of the complexity from the programmer. Without knowing how classes work internally how can you guarantee that you are utilising the class in the most efficient manner? Take the String class in Java as an example.

code:<HR>
Code:
String output = new String();
for(int i = 0; i < source.length; i++)
{
  output += source<I>;
}

The above piece of code adds all the Strings held in the source array and compiles them into one long String called output. But what you can't tell from looking at that is that Java creates a whole new String every time it goes through the loop. It finds out how many chars source is and creates a new String that is long enough to accomodate that as well as the existing output. It then copies the existing output and source into the new String. Can you imagine how long that would take if we are dealing with thousands of characters when you take into account all that redundant copying for each loop iteration!! :eek:

Although there are no strings in C++ (so it's hard to draw a straight comparison here) the general idea would be to create a character array that is big enough to hold all the characters at the begining and then copy everything into that. Already you can see how this is much more efficient than the Java version because there is no redundant copying.

But there is a way to do this more efficiently in Java. But why would you bother looking for it if you didn't realise how inefficient Java was being? You would just make the assumption that Java is slow and dismiss it as a viable language for what you are doing. It's only when you peel back the layers that you discover that Java, in it's efforts to shroud the programmer from complexities, is actually doing things in a very inefficient way. But once you understand how it does things you can manipulate it so that it does things more efficiently...
code:<HR>
Code:
StringBuffer buffer = new StringBuffer();
for(int i = 0; i < source.length; i++)
{
  buffer.append(source[i]);
}<P>String output = buffer.toString();

Run that compared to the first example and you will probably find it runs several times faster over a long job. In fact the longer this code runs, the more it will pull away from the first example in speed. The StringBuffer class is designed to be used when you want to add together a large volume of Strings. It grabs a big 'ol slice of memory which is plenty big enough which means it doesn't have to keep recreating itself to be just as big as it needs. So you've done away with all that unnecessary copying.

Admittedly this approach is never going to be as fast as the C++ method, but I think you'll agree that it's gonna be a heck of a lot faster than what you would have hacked out without knowledge of how Java works under the hood. There are also other aspects of how Java works with Strings that could put you in a scenario where a String with only character could actually take up 2MB of memory (or more)!! And the shocker would be that you wouldn't even realise unless you knew what it was doing behind the shroud :eek:

But anyways, I shall step off my soap box now :D I just wanted to deomstrate that Java isn't really that slow. Admittedly it is slower, but when you learn how it does things you will be amazed how much faster you can make your code.

Anton
 

John

Ars Praefectus
3,789
Subscriptor++
Seriously, I appreciate your conviction in your viewpoint, especially when you realize that making a statement like "speed is rarely the number one priority" without backing it up invites just a single counterexample to burst it into flames.

I said "rarely", not "never." And My point about you typing "ONLY" was not that it was in all-caps, but that you couldn't possible mean "exclusively" or "solely." Think about it for a second. If speed was the "only" priority, a program that crashed 2 seconds after launch (but ran very fast right up until then) would be preferred over a program that ran slightly slower but ran for 5 seconds before crashing. Because "speed is the ONLY priority," right? And how about "correctness"? How about a spreadsheet that gets incorrect results, but does so very quickly? Great! Because "speed is the only priority!" ;)
 

bjrady

Seniorius Lurkius
31
Originally posted by jemfinch:
Find me _one_ example of a good OO design speeding up hand-tuned procedural
code.

Jeremy

Well without violating my Non-Disclosure Agreement, I can tell you this:

You can optimize the inner loop of a rendering routine all you want, write it in assembler, spends hours with a profiler to eek every last bit of performance out of it...

BUT

If you have a good OO design that allows the system to dynamically respond to events that would cause the rendering not to be necessary (when another window is covering part of the rendering surface, for example), then your highly tuned inner loop is still 100% slower than not executing the code at all, which is what you can do by investing in a good design.

Now yes, you could also try to do this in procedural design, but the overhead is going to be much, much higher because you have to try to account for it in the design phase of the project. And trying to figure out perfomance optimizations in the design phase is VERY difficult. If, however, you just make a good, modular, OO design, you can wait until the testing and optimization phase and then incorperate those things, which is MUCH easier and will save you lots of time and headaches.
 
re: speed

Typically your bottlenecks are in small, localized parts of your code. So if you focus on writing clear, maintainable code, you can then profile the code and optimize the troublespots for speed.

The trouble with optimizing for speed is that it can othen result in less readable code. So you don't want to optimize the whole application for speed -- then it would be illegible.

Furthermore, you often don't know what the real bottle necks are until you run the code. If your entire codebase is optimized for speed in the all the wrong areas, it will be near impossible to make that profiling adjustment.

Example:

Database access is often very slow. It is very easy to write bloated queries. So you try and optimize your queries, optimize your database calling routines, and optimize every bit of code you can. Still, your code spends most of its time waiting on the database

Then you realize that you could cache the results from the first lookup, and never hit the database again. Except that now your db access code is needlessly complex because you were "optimizing", and you can't make the real optimization, the one born from profiling.
 

Anton

Seniorius Lurkius
36
quote:
--------------------------------------------------------------------------------
Although there are no strings in C++
--------------------------------------------------------------------------------

yes their are, std::string or std::basic_string<whatever>.

the MFC CString has the same problem as the java string(temporary objects) however std::string does not

Sorry. Forgive my arrogance. I was just demonstrating that using the C stylie char* is gonna be quicker than Java's implementation. I forgot that String support is supplied by additional libraries :rolleyes:
 

yugami

Ars Tribunus Militum
2,547
I forgot that String support is supplied by additional libraries

well, if you count libraries that are required by the standard as additional i guess then yes using additional libraries you get string

however all of c's string(strlen, strtok, ...) functions are also in "an additional library" so i'm not sure where you going with this.
 

TheBorg

Ars Tribunus Angusticlavius
8,555
Whoah, did this generate some interesting conversation! I can't stay long, but:

TheBorg:
don't talk about the salary paying world while you are in grad school :)

Lol, patsPLAT - I think I gave you the wrong impression. I actually work for a living in IT (analyst and infrastructure design going on fifteen years now), and I'm just getting around to my undergraduate degree in Comp.Sci. And you're right - maintainability is important, and so are a lot of the other things that some of the others mentioned. I didn't mean to turn this into a speed-freak issue. My point about speed was that sometimes, sometimes speed is the main priority, and choice of platform becomes pivotal. That was my whole point about Java and it's lack of speed - and I can't believe anyone would dispute that issue that Java is bloated and slow, I thought everyone knew that.

Just for grins, I wrote a small, identical 'for' loop in both VB6 and Java 1.3.1 from 1 to one billion that did nothing more than increment another variable (type long). I timed the results - VB6 ran in around 14 seconds and Java ran in around 43 seconds. This is not typical - it actually gets worse the more complex the program, and quite frankly VB is a poor performer anyway. I won't rehash my previous rant, but I'll publish the C results when I get back to work. I would encourage others to try it and see what they find.

Anyway, some of the projects I'm involved with (distributed computing on W2K engineering workstations, for example) require that we do things fast - the department I work for needs to crank out results against hundreds and/or thousands of Unigraphics part data files every night. Yes, it's important that the code be maintainable, but good analysis and design help achieve that. Performance counts in this case as much as anything else - if the bulk of the work isn't done by the next morning, a whole bunch of designers are going to be ticked with the programmers because their workstations will be bogging huge ;). It then comes down to a choice of platform to achieve faster results. Compiled C executes many times faster than Java (about an order of magnitude), therefore a lot of the task chunks are written in C (or more appropriately, they're not written in Java). I really don't like C myself - it was a language written to develop an operating system intended to maintain phone switches - and I don't code much in it myself, but I digress again ;). C is fast, the compilers are very well optimized. Java is not a language I would use for performance.

Anyway, I'm drawing it out again.

Later,

theBorg

P.S. I sorta got slagged by folks who have maybe one or two languages under their belt, telling me tongue-in-cheeck that it might be my lack of OO expertise that's making the code slow. Heh. My Java runs just fine, thanks for the help though ;)
 
Status
Not open for further replies.