Slashdot Mirror


Can OO Programming Solve Engineering Problems?

ThChalm asks: "I am the first one to admit that my programming experience is somewhat limited. The majority of it has been obtained writing FORTRAN code to solve problems in mechanical engineering. I have written some smaller (you might say toy) codes using C. I have read a lot of books on C++ (and OOP), but always get frustrated with the following question: Why can't anyone show me an engineering application that is solved with an object oriented program?"

"I appreciate the concepts of OOP and see its applicability in managing records, GUIs, and possibly standard function libraries. I cannot, however, convince myself that there is a clean way to use these concepts to solve the type of procedural problems that I have encountered in the past (finite difference solutions to differential equations, finite-volume computational fluid dynamics, iterative solutions to non-linear equations, Monte-Carlo simulation of radiative heat transfer, etc.)

Am I just being close minded to the ideas of OOP or do my problems just require 'procedural' solutions, which are better solved using procedural techniques? I'll even be happy with the answer 'Your problems are two small and specialized to realize any significant advantages of OOP.'

I'd be interested in hearing comments from anyone else who has this problem, anyone who has worked through it, or anyone who can send me an example of an engineering application of C++ and OOP."

43 of 621 comments (clear)

  1. Don't confuse OO techniques and languages by twoflower · · Score: 3, Insightful

    OO design has nothing to do with C++ versus C. You can do OO design with any language you like; much of the Linux kernel has elements of OO design, but is implemented in C.

    Language is an implementation detail. It does not dictate design.

    Twoflower

    --


    --
    Twoflower
    1. Re:Don't confuse OO techniques and languages by Anonymous Coward · · Score: 2, Insightful

      > Now templates are a whole different ball of wax. C has no paradigm for expressing generic programming.

      You are right, there is no nice way to specify generic (i.e. template) functions in C, but as with everything else in programming, there are ways. I can do generic functions in C, no problems at all, its just rather darn ugly.

      As you, and many people have correctly pointed out, the language is irrelevant. You can do pretty much anything in any language apart from where the language stops you expressing certain things. After all, C/C++/python/haskell all end up being run on finite state machines (CPUs) which do nothing more than maths and storage. A language can stop you in areas (like make file access impossible because there is just no way to do it) but apart from that you can do it all (might not be in a reasonable time frame, but so what)

      A language is just a way for a programmer to express what they want to be done. Some languages lend themselves to certain methods better than others. A perfect language would lend itself to any conceivable method, with a good clean, yet powerful syntax. Unfortunately elegance and control do not go hand in hand, which is why there are still many different languages.

  2. Round peg, Square Hole... by einer · · Score: 3, Insightful

    I'm not terribly familier with the problems you have presented (I.E. I know what a monte carlo alogorithm is, but not the radiative heat transfer part...), but it sounds to me like you're trying to fit the problem to the solution and not the other way around. OOP can be useful if you're trying to model something, or replicate the behavior behavior and characteristics of a real world problem, but it's not that great for say, solving a system of equations... I guess you can use whatever language or system you would like, but not many need C++ and the STL to evaluate expressions.

    1. Re:Round peg, Square Hole... by madmaxx · · Score: 3, Insightful

      I disagree. C++ is intended to solve systems in the language of the domain - which is one of the central purposes of the language (see Design and Evolution of C++ by Stroustrup). Some of the strongest uses of C++ I've seen today are well abstracted matrix libraries for advanced signal processing (Blitz++) ... not too far from what the question is asking about.

      --
      mx
  3. Engineering Processes are Procedural by mheine · · Score: 4, Insightful

    All of the techniques you listed and most other engineering problems are expressed in a procedural format. In order to use OO you would have to transform the problem into an object problem. The things that OO does really well at are things where we already think in object terms. Like GUI widgets. Most engineering problems simply aren't expressed that way. Although most problems could be rephrased that way the algorithms would necessarily not be equivalent (better or worse would require experimentation)

  4. I think it's a problem of scale and understanding. by PHAEDRU5 · · Score: 4, Insightful

    If you're dealing with a problem that can be reduced to a mathematical formula or the like, you're probably better off looking in Numerical Recipes or the NAG libraries, or what have you.

    In this case, you're dealing with a well-defined, well-understood problem. You could implement a solution using OO principals, but why bother. I mean, you're not going to be changing it or adapting it all that much.

    The power of OO happens at a higher level, and with less-well understoof problems. In this case, you're modeling higher-level entities, with less well-understood properties that are much more liable to change. In this case, the ideas of modularity, pluggable behavious, cohesiveness, etc., become much more important.

    I hope that didn't sound too much like a hand-waving explanation.

    --
    668: Neighbour of the Beast
  5. any componentized program by mugnyte · · Score: 2, Insightful

    Code Reuse and extensibility is (IMHO) the largest advantage of OO. By (trying) to demark a dotted line around the box of code you want to (re)use and separating out your new code, you realize gains in writing and testing. Communicating what code actually does is also much cleaner in a componentized view.

    So take a look at many programs writting in Windows these days. Anything written that uses COM. Almost all *ix shell scripting. While they all follow different aspects of "object" reuse, you are benefitting from using a block of solid code without having to retest it. I'm abstracting the definition many people have of "object" as such, but in the end all the goals are similar: Get it done better, faster.

    mug

  6. Is it neccessary to be an end all be all? by syrupMatt · · Score: 2, Insightful

    I would tend to agree that OOP might be the wrong solution. It seems to me that OOP is designed to generalize code to solve broad problems. Engineering, and other applications which require minute changes depending on multiple factors might be better served by procedural code designed to specifically handle those problems.

    An interesting point that is raised is the fact that OOP, while an enormously helpful tool to many programmers and despite its advantages in many other theaters of software design, does not have to be an end all be all for programming as a whole. The tool that works should be the tool that is used.

    --
    "Moving through the masses like a fish through water." syrup
  7. How can we answer that... by Katravax · · Score: 2, Insightful

    ...when the jury is still out on whether OOP can even solve computer science problems?

    Other than a small handful of examples, I haven't seen where OO helps any way other than the creation of arbitrary data types and convenient grouping of data and functionality which can be done, although less cleanly, in a procedural language as well. The complexities of inheritance and God forbid, polymorphism, usually lead to more problems than they solve, in my opinion.

    I agree that OO programming can be more programmer-friendly in some cases, but in general find it more trouble than it's worth. Sometimes it looks to me like most of the things that can be re-used have already been turned into libraries, and the rest is all custom programming.

    I confess to learning programming using procedural techniques and using them for a dozen years before picking up OOP, and still finding those techniques easier to apply. But I'm not the only one that questions whether OO is a big red herring to productivity.

  8. OOP solves Software Engineering problems by soboroff · · Score: 5, Insightful

    OOP doesn't solve engineering problems of the kind you describe. The programs solve the problems.

    OOP is a way to think about structuring the program, how you organize data and operations on the data, how you build reusable components which you can apply in some future problem you need to write a program to solve. In other words, OO helps solve software engineering problems. You'll still need to write the program which solves your particular problem.

    And before the flames commence, yes, OO isn't the only solution to this class of problems. It's just one.

  9. OOPs (I did it again) by CaptainAlbert · · Score: 5, Insightful

    Take a look at BLITZ++, then tell me OOP is not useful for scientists and engineers. :-)

    I think the safest thing to say is that whatever your programming needs, whether you're doing pure matrix/BLAS number crunching or writing complex simulations/models, you should think twice before using FORTRAN. Well-written code in, say, C++ will be more maintainable and accessible to other people you work with (and who have to touch your code in future).

    The only thing which keeps people using FORTAN that I've seen is that the optimising compiler support is fantastic compared with the equivalent offerings in C/C++ compilers. But that's not much of an excuse for general day to day problem-solving.

    Just my 2p.

    --
    These sigs are more interesting tha
  10. Re:OOP by kevin42 · · Score: 3, Insightful

    That has been true in the past, but with modern compilers (like gcc) you will get very similar code and only a slight increase in overhead (vtables) with C++ over C. Lots of people are using C++ in small embedded systems now.

    Real bloat comes from libraries like STL...

  11. One example by bapya · · Score: 2, Insightful

    One example that comes to my mind immeiately is MMTK ( link) (Molecular modeling tool kit) developed in python by Konrad Hinsen.

  12. Re:Look at the audience.... by Bat_Masterson · · Score: 3, Insightful

    You're confusing programming language with design concepts. The question is not "is Fortran better for engineering problems than C++?" but rather "can OO design and development be applied well to engineering problems?"

  13. You don't understand what OO is by Papa+Legba · · Score: 3, Insightful

    You seem to think that OO is some end all be all of the programing language. It is more on how you structure the code. You can do a hello world program using OO is you wanted. Instead of acting on the logic of the problem you design from the idea that the data is what must be manipulated and therefore is an object to be handeled. All the problems you are listed are easily solved by defining the class that is associated with the data inputs and then perform actions on those objects. It is quite a bit different in thinking over how fortran is programmed.Having programmed in both OO is a much more powerful solution.

    Here is an excerpt from www.whatis.com that may explain this better than I can.

    " The first step in OOP is to identify all the objects you want to manipulate and how they relate to each other, an exercise often known as data modeling. Once you've identified an object, you generalize it as a class of objects (think of Plato's concept of the "ideal" chair that stands for all chairs) and define the kind of data it contains and any logic sequences that can manipulate it. Each distinct logic sequence is known as a method. A real instance of a class is called (no surprise here) an "object" or, in some environments, an "instance of a class." The object or class instance is what you run in the computer. Its methods provide computer instructions and the class object characteristics provide relevant data. You communicate with objects - and they communicate with each other - with well-defined interfaces called messages.

    The concepts and rules used in object-oriented programming provide these important benefits:

    The concept of a data class makes it possible to define subclasses of data objects that share some or all of the main class characteristics. Called inheritance, this property of OOP forces a more thorough data analysis, reduces development time, and ensures more accurate coding.
    Since a class defines only the data it needs to be concerned with, when an instance of that class (an object) is run, the code will not be able to accidentally access other program data. This characteristic of data hiding provides greater system security and avoids unintended data corruption.
    The definition of a class is reuseable not only by the program for which it is initially created but also by other object-oriented programs (and, for this reason, can be more easily distributed for use in networks).
    The concept of data classes allows a programmer to create any new data type that is not already defined in the language itself.

    One of the first object-oriented computer languages was called Smalltalk. C++ and Java are the most popular object-oriented languages today. The Java programming language is designed especially for use in distributed applications on corporate networks and the Internet."

    --
    Papa Legba come and open the gate
  14. The act of learning by pdqlamb · · Score: 5, Insightful

    I've seen some truly awful procedural code (lots of it was Fortran, BTW). I've seen some truly gorgeous procedural code (lots of it was Fortran, BTW). I've seen some some wonderful, and even more pretty awful, OO code (mostly C++, but with some Java).

    Go ahead and study object oriented programming. You'll learn some new ways to do things. But I think it's the act of studying, and the act of learning, that will be the most valuable thing you get out of the process. Too many people never study how to program, how to document, how to design code. They learn one or more languages. Their code shows it.

    A few people have a natural tendency to write elegant code. A few more, but still not very many, study and try to learn how to write elegant code.

    But don't expect the object-orientedness to make much difference. A dozen or more years ago, a young whippersnapper got hooked on objected-oriented design. He derided all the existing Fortran we had as spaghetti code. To some of us, though, his "object-oriented" code was lasagna code. No overriding structure, code spread out all over the place, a single function scattered over three files. And this was still Fortran; I've seen C++ coders who took six files for a similar, simple function.

    I've also surprised myself! when some of my OO C++ code needed four lines to add new functionality. But it was carefully designed, after years of programmer improvement and study.

    Go ahead and try it; it can only help.

  15. Pragmatics... by Yoda2 · · Score: 2, Insightful

    If your primary job is engineering and not programming, and you're getting the job done in FORTRAN, then by all means stick with FORTRAN. If on the other hand, you are building software systems from scratch that will need to be maintained over time and have components that might need to be reused then maybe OO is the way to go. In any event, it is good that you are exploring OO because even if you don't use all the techniques explicitly, you are probably picking up some good design ideas through osmosis.

  16. Re:Complex Question... by taliver · · Score: 2, Insightful

    However, you still end up writting 100 different functions in either case, and calling

    squarepipe.calculateFlowrate

    seems no easier to remember than

    squarePipe_CalculateFlowRate()

    or

    CalculateFlowrate(SQUAREPIPE,...)

    Also, if you have generic functions across all classes, you are left with a bizarre model of pipes, bowls, steam generators, and anything else having to be under some umbrella so you can attach a "SurfaceArea" or "Volume" calculator or some other generic routine.

    I've also never been a big believer of the whole "code-reuse" argument. The biggest code-reuse in practce is all done in C, and very non-OO -- libc.

    Unless you already have a big simulator witten in OO style, and you need a simulator, I'm not sure of the use of OOP. If you are trying to do a large calculation, then the time you spend in trying to stick to the OOP mindset doesn't seem like it will ever pay off.

    --

    I demand a million helicopters and a DOLLAR!

  17. Particle Simulations by McBeth · · Score: 2, Insightful

    As part of a project I was on, we needed to do a bunch of simulations of particles moving subject to physics. Unlike what you usually see in games, these needed to be real simulations (reproducable in the lab).

    We ended up doing a bunch of OOP so that we could handle many different kinds of particles, and many different PDE solvers, each selected for the particular task. Because of polymorphism, we were able to write the engine once, and plug in what we needed fairly easily. In the end the code ended up being much cleaner, readable, and faster than the Fortran we started with. We have gone on and are using it for a completely different kind of simulation now with minor changes.

    This was all in the Chemistry Department, but I certainly think it applies.

    I would guess that most engineers use Fortran in part because of the book "Numerical Recipes in Fortran". Although there exist C and C++ versions of the book, they certainly don't take advantage of the languages, and for the most part are direct ports of the fortran. They are very disparaging of the languages in those books, and even spread FUD about C, C++ and the numerical stability of the compilers.

  18. OO by ShrimpX · · Score: 1, Insightful

    Object Oriented problem solving is not a "rival" to procedural problem solving; it encompasses it. The OO core notion doesn't "solve" problems, it organizes them into more intuitive and maintainable forms, so that they are easier to solve. It is best suited for larger scale applications, where it makes most sense to have your problem broken down into tiny self-contained units that are flexible and easy to manipulate.

  19. The advantage of OO... by wowbagger · · Score: 5, Insightful

    Preface: I've been an embedded systems software engineer since 1987. I've been programming in C for almost all of that time, and C++ since '91. I've designed systems with over 250kloc, hard realtime.

    The biggest single advantage of OOD is that you can say "This sort of thing will have a function that does something like this, but I won't make the final decision on exactly HOW to implement that function until late, when I have more information on what needs to happen."

    Let me give you a concrete example. I had to design the code to reprogram the flash in one of our devices. I faced the following problems:
    1) the way the data got to us could either be Xmodem or Ymodem.
    2) The file format could be either OMF or raw binary.
    3) The types of memory devices could change - they could be Intel type 1 flash, AMD type 1 flash, or Intel type 2 flash (or RAM), all of which have different programming requirements.
    3a) In addition, the types of flash could be changed by the production line (based on what was available - most of those parts were "on allocation", meaning "you take the quantities we give you and you like it - you ain't IBM so you don't matter".
    3b) The types of flash on a given unit could be mixed - you had to probe at runtime to figure out what you had.

    So, here's how I decomposed it:
    1) I had two file type objects: OMF and Binary. They each HAD-A Input object, which provided data , and HAD-A Memory object, which would program memory. The OMF object read OMF records from the Input object, parsed the OMF records, extracted the data, and commanded the Memory object to program regions of memory.
    2) I had an Xmodem object, which WAS-A Input object. It read data from the serial port, handled the checksum or CRC verification, block counting, and made the data available to the user (the file object).
    3) The Memory object HAD-A pointer to a Memory_driver object. When the Memory object was commanded to write to a block of memory, it verified that the write was in the current block, and if so passed the request to the Memory_driver object. If not, the Memory object HAD-A list of Memory_driver_list objects, which each HAD-A pointer to a function that would probe a given memory address and return either NULL or a pointer to a newly created Memory_driver object. The Memory object would iterate through the list, asking each Memory_driver_list object "Can you program this?". When one of them returned a non-null value, the Memory object would delete the old Memory_driver, and use the new Memory_driver.
    4) I had Intel_series1, Intel_series2, AMD_series1 and RAM objects, all of which WERE-A Memory_driver. Each class HAD-A static instance of a Memory_driver_list object, which automatically linked itself to the driver list. Each driver HAD-A static member function to probe memory and return a pointer to a newly created driver if needed.

    First, this let each routine be focused on what it needed to do - the Xmodem routines didn't worry about OMF format, the OMF didn't do Xmodem handshakeing, the Memory routine didn't care about the specifics of programming memory. I could test each object out in isolation, get it working, and move on. Now, you can do this with proceedural programming techniques too.

    Second, when a new type of memory was added, I was able to just write the driver for it, and not touch the OMF object, the Memory object or the file transfer objects. They automatically picked up the new driver. Now, you can do this in a proceedural language like C, but how do you do so? You make each driver have a table of function pointers, and you have the upper level code keep track of a void * that contains your driver information. Guess what - that's OOP! The function table is the same as a C++ vtable, the void * is your this pointer. Except that in C, you have to track all that stuff yourself, in C++ you can let the compiler worry about the BS and you focus on the code design.

    In short, OOD helps, but you still have to use it correctly.

  20. OO is Hard by karb · · Score: 3, Insightful
    I'm a software engineer. However, I lost you at the "I'm having trouble doing ...". I'm assuming this means you are some sort of real engineer :) :) OO is great. It does what it promises. It makes everything a whole lot easier to manage, makes your code more reusable, blah blah blah.

    However, I have lots of bad experience trying to get engineers to write good OO code. Nothing against y'all, but, conversely if you forced most software engineers (aside from a few savant freaks that I'm sure will chide me) to deal with the engineering problems you mentioned (that I have never heard of or forgot) we would probably die.

    What I'm getting at, I guess, is that OO rules. However, it's like linux, or repairing cars, or (ad infinitum). Being an expert rules, but it's not always worth the time to become an expert. You can't just jump in. Reading a few books helps, but I've read a few books, been doing this full-time for two or three years, had a very OO college experience, and most of the stuff I design and code is still crap.

    In addition, the code you are writing seems really unlikely to change. Write it procedurally, and write it well, and your grandkids will still be using that code because it would be too much of a pain to rewrite it to OO.

    I think you might be looking for an exemption. Here it is : use procedural programming for things that are tough for you to imagine in OO terms. Don't feel guilty. You will still never have as much crap code lying (laying?) around with your name on it as I do, and I do this for a living ;)

    --

    Jack Valenti and the MPAA are to technology as the Boston strangler is to the woman home alone

    1. Re:OO is Hard by LoveMe2Times · · Score: 2, Insightful

      Wow, I see one actually sane comment in this whole thread, and it's not even modded up. First off, let me state that the people that post on /. aren't necessarily the technological savants that you might presume them to be. You've asked a loaded question on a forum where you're guarunteed to have a poor signal to noise ratio: a lot of people have something to say, but the moderators can't tell who knows their arse from a hole in the ground. It might be fun for everybody to come out and rant or give you advice, because, hey, everybody likes to rant or think they know better than you. Ok, not everybody, but enough people to keep /. lively.
      Anyway, point is, as per usual, most of the posts here are arguments that probably aren't real helpful for you. I'm going to read between the lines hear and guess that you're real question is, "Should I bite the bullet and learn OO?" Now, you kind of have to make a choice (unless you're one of the lucky few that can have it all): do you want to be an engineer that programs, or a programmer that knows engineering? Let me put it to you this way: most professional programmers are average. Early proponents of OOP mistakenly believed that OOP would make programmers better, and this thought still lingers in many places. OO, like any problem solving paradigm, will help those who use it well and hinder those who wield it poorly.
      I'd like to try and clarify one other thing, too. A problem solving methodology like OO is just that. A problem solving methodology. And like any problem solving scheme, it has a lot more to do with how the problem solver thinks, and not so much the problem being solved. So, if you like OO, go for it. If not, don't. Either way, unless you really care a lot (or again, if you're one of those lucky ones), you won't be good at it. It won't help you get work done easier and there's a good chance that it will make your work more difficult.
      Besides that, all I can do is describe how *I* would solve your problems, which doesn't help you much. It would take you a long time to gain the expertise to understand my solution, much less how I got there, much less being able to get there yourself. There is no One True Way. Good luck!

  21. Re:Complex Question... by piggy · · Score: 4, Insightful
    However, you still end up writting 100 different functions in either case, and calling

    squarepipe.calculateFlowrate

    seems no easier to remember than

    squarePipe_CalculateFlowRate()

    or

    CalculateFlowrate(SQUAREPIPE,...)
    But this is easier if you don't know the pipe type before runtime, or the type could change:

    PipeType * theTypeOfPipeAsParameter;
    FlowRateParams * flowrateparams;
    Pipe * thePipe;
    [[thePipe alloc] initPipeWithType:theTypeOfPipeAsParameter];
    flowrate = [thePipe calculateFlowrate:flowrateparams];

    That is, you are correct unless you dynamically create pipes of different kinds at runtime, perhaps using an abstract factory (for example, an interactive simulation which allows the engineer to manipulate the objects) or, at a more basic level, have need to send the same message to a collection of disparate pipes (for example, compare the simplicity of the design and code to send the same "calculateFlowrate" message to each object in an array in a polymorphic OO language versus a procedural language).

    My point is that, perhaps the implementation of the calculation cannot easily be made OO, but access to that calculation can often benefit from an OO wrapper.

    Just off the top of my head. At work, we are attempting to apply OO to requirements analysis, while still persisting in the "object-based" world of Ada development. (This means that I don't have any real world, OO engineering implementation examples).

    Russell Ahrens

  22. Re:Math objects are objects, too by Twylite · · Score: 3, Insightful

    I'm sorry, but this is a classic example of bad OO, except in specific circumstances. A simple calculation is expanded into 6 method calls (3 x setCoefficient, 1 x calculate, 2 x getRoot), and even if compound methods are provided the side effects grossly impede calculation performance.

    An object can represent anything that has a state which changes over time, in response to input or other events in the software. If what you are modelling does not hold with the above definition, it shouldn't be an object.

    Discrete calculations are especially suited to NOT being objects. They have no requirement for persistent information outside the function, and thus no need to be in an object. The primary reason for putting them in an object is grouping, which is a Really Bad Idea for common library routines because you can't export C++ objects from libraries (unless you assume that the library user has the same compiler and linker as you do...).

    Fortunately C++ (unlike some other OO languages) has a solution to this problem: namespaces. Any function which is self-contained (has no need for non-local data) can be placed in a namespace, logically grouped with similar functions, and if the header is carefully constructed can still be used in libraries using C name "mangling".

    The only situation in which I can imagine the object you propose being useful is as a data object behind a GUI which allows you to enter quadratics and fills in the other fields. And even in this case I contend that the correct model would be a QuadraticModel object (like the one you describe) which calls calculateQuadraticRoots() in a namespace or other library.

    --
    i-name =twylite [http://public.xdi.org/=twylite], see idcommons.net
  23. Re:OOP by Kamel+Jockey · · Score: 2, Insightful

    "very bloated" is really incorrect nowadays for modern compilers for OO languages such as C++. This is a common misconception that old timer real-time and embedded programmers like to cling to whenever anybody mentions OO.

    Not quite. The reason my statement about compiled code being very bloated, especially on embedded systems, is because there are numerous embedded CPUs for which you can develop software, and good-quality compilers for each of these chips (yes, you need a compiler for each individual chip!) are only now beginning to enter the fray.

    Many of these compilers do not take advantage of many of the obscure but highly efficient CPU instructions which can truly optimize the machine code. Additionally, speed is not necessarily the only objective for which a coder would wish to optimize. In the embedded world, other factors such as minimal code size, power consumption and memory consumption, among other things, often take precedence over speed.

    So hence, many programmers still prefer to use hand-coded assembly for these types of systems.

    --
    In case of fire, do not use elevator. Use water!
  24. Re:Complex Question... by STSeer · · Score: 2, Insightful

    "It is better to have 100 functions operate on one data structure than 10 functions on 10 data structures. "

    Alan J. Perlis

    http://www.cs.yale.edu/homes/perlis-alan/quotes. ht ml

  25. Re:OOP won't help, sorry... by imp · · Score: 5, Insightful
    The great thing about Object Oriented code is that it can make small, simple problems look like large, complex ones.
    Well, the great thing about C is that you can write great FORTRAN programs in it :-)

    You can abuse any tool. OO code also lets you make complex problems look like a managable set of simple ones.

  26. Re:OOP == encapsulation ... by Twylite · · Score: 3, Insightful

    One day, grasshopper, you too shall understand.

    You seem to have grasped one of the central concepts of OO, and a fraction of its usefulness. You have yet to come to terms with its real worth, or the Greater Picture.

    To a limited extent OO is the "reverse" of passing around a data structure. It is convenient, and to most people more logical. But most importantly it offers something that non-OO languages cannot provide: compile time type safety and encapsulation.

    The and is really important, because a non-OO language can offer either, but not both. This means than a function can never be entirely sure that its data is in a consistent or expected state, which an object can.

    Aside: to provide compile-time safety to must declare the entire data structure, and not do any type-casting. But to provide for encapsulation you must hide the data structure, so that a developer cannot at compile time reference any member of the structure by name (i.e. can't screw with the data without making assumptions about offsets that equate to hacking, and will not remain true if the data structure changes). Doing both is not possible without additional code in the function to calculate and check some sort of checksum of the data structure; and that does not provide for compile-time error checking.

    This may not seem important, but it greatly reduces bugs. You can code and debug a library of objects, happy in the knowledge that no other part of the program can screw with the objects' minds. Never underestimate the value of compile-time error checking; a well-designed program may most of its bugs in this fashion!

    And now we move on to more interesting stuff, like inheritence and polymorphism. (And no, "templates" (parametised classes, for the better educated) are not OO).

    OO is not about "making programming easier". It is about creating a more logical structure to allow the application of engineering principles to software design and implementation. This means improving robustness and maintainability.

    OO achieves this by reusing code in a more effecient fashion than procedural languages; as a direct consequence of inheritence.

    In any situation being modelled by software there tend to be a number of data-bearing entities (physical objects, processes, representations) with similar properties and having similar functions. OO allows the similar properties and functions to be matched, factered out and reused across all the entities.

    Non-OO languages can approximate some of this functionality by using embedded or chained data structures, but they lack a significant capability: to automatically adjust the function according to the entity.

    This difference is best illustrated by considering an office with a manager, secretary, clerk and some production workers. The manager walks into the office and says "all of you, do your job!". Simple, and OO.

    In the non-OO case the manager walks into the office and says "all of you, if you are a secretary answer the phone and do the filing, if you are a clerk total the books, if you are a production worker on the Toy line then build toys, and if you are a production worker on the Pen line then make pens."

    OO simplifies the procedural logic which controls a situation, because each object knows how to behave in an appropriate way in reaction to a more generic instruction.

    If you find no benefit in OO other than "it makes coding easier" then you are missing the point, and I would suggest getting a good book on the topic and reading it thoroughly.

    --
    i-name =twylite [http://public.xdi.org/=twylite], see idcommons.net
  27. Re:OOP won't help, sorry... by Arandir · · Score: 3, Insightful

    The comment got modded up to funny, but it's dead on the mark. OO Programming is about O (Objects). When designing a program, first determine the objects in your domain. The stuff you specifically mentioned are not objects. If you can't find any objects in your domain, then don't go the OO route.

    Here's an example: Airfoil design. The object in the domain is the airfoil (and probably composed of other objects like surfaces, sections, etc). The actual equations used are not the object, they are what you do with the object. So when you talk about finite difference solutions, fluid dynamics, and iterative solutions, you aren't talking about objects, but what you can do WITH objects.

    Even if OO doesn't fit your domain, take a look at the STL and Generic Programming in general. There's some useful stuff in there for your needs.

    --
    A Government Is a Body of People, Usually Notably Ungoverned
  28. The Answer Is YES, OOP is Appropriate by waltal · · Score: 2, Insightful

    OK folks, how about object-oriented NASTRAN? Anybody out there agreeing yet? This is hardcore structural analysis, and a major pain for years because of its initial programming architecture.

    Lockheed-Martin is using a generalized data handling/simulation library called GEMD. It's object-oriented data complemented by an object-oriented, high performance C library. It's powerful enough for F-16 or F-22 simulation, and conveniant for simple one-hour problems. It is a standard for much of the engineering staff.

    Are spreadsheets great engineering tools or what? I've done propeller design with a spreadsheet. At the interface, there are lots of objects. I'm sure spreadsheets are best programmed with object principles in mind.

    Engineering is a very real-world endeveor. You can argue that engineers use mathematical abstractions in their work, and I would argue that even mathematical abstractions can be regarded as objects in a programming implementation. And I would also argue that most engineers are held to much higher standards of accountability if their software fails. And that goes for accident and incident analysis, too.

    Anything that improves production, use, testability, maintenance of software in engineering is well worth learning and using well.

  29. There is something wrong with OOP by Anonymous Coward · · Score: 1, Insightful

    I've been OOPing for several years in various languages and I've found that while OOP helps in writing larger programs, it is not the panacea that many think it is. Many of the ideas are very compelling, like inheritance, but hard to take advantage of in practice.

    I think OOP has some good ideas, but will turn out to be an evolutionary step on the way to a much better way of programming that has not been conceived yet.

    An interesting interview with a thoughtful anti-oop perspective:
    http://www.stlport.org/resources/StepanovUSA.htm l

  30. Re:Complex Question... by michael_cain · · Score: 4, Insightful
    Dang -- never have moderator points when I want them...

    I particularly like this as an example of the expressive power that an OO language can provide. A straightforward "equivalent" in C (not necessarily a good equivalent) might look like

    #define PIPE struct Pipe
    #define ROUND 1
    #define RECTANGULAR 2

    PIPE {
    int type;
    float diameter;
    float width;
    float height;
    }
    .
    .

    float
    flow_rate(pipe, x, y)
    PIPE *pipe;
    float x, y;
    {
    float result;
    switch (pipe->type) {
    case ROUND:
    result = stuff;
    break;

    case RECTANGULAR:
    result = stuff;
    break;

    default:
    result = -1; // Assume real flows are positive
    break;
    }
    return result;
    }
    .
    .

    PIPE *round, *rect;
    .
    .

    round = (PIPE *)malloc(sizeof(PIPE));
    round->type = ROUND;
    round->diameter = 30.0;
    result = flow_rate(round, 12.0, 9.0);
    rect = (PIPE *)malloc(sizeof(PIPE));
    rect->type = RECTANGULAR;
    rect->height = 4.0;
    rect->width = 40.0;
    result = flow_rate(rect, 12.0, 9.0);

    And there are lots of problems with trying to maintain or extend this code. For one thing, the code that deals with ROUND pipes is scattered all over the place in each of the functions that applies to the generic pipe concept. If different pipe types require different numbers of parameters for flow_rate, you have to get into varargs stuff and lose a lot of type-checking that the compiler might do for you.

  31. Business strength (tighter binding to domain) by ratajik · · Score: 2, Insightful

    One strength I've seen with OO isn't in the pure programming realm, but more in the business realm. You build objects based on the domain you are working in, whether that's banking, accounting, games, whatever. The terms you use, and how the high level objects fit together and interact can be more closely aligned to the domain you are working with, compared to procedural languages. This allows a developer to more easily verify that what they are developing is actually what is needed (easier to check against the domain), and also allows non-techies to look at the object model and be able to understand what's going on (again, because it's modeled directly to the domain, in the terminology of that domain).

    There's lots of other good things about OO (which others have already pointed out), but this one strength is something I've seen work on several projects. Many of these other strengths are in more of the pure technical realm, but the business-oriented strength is one that can be overlooked, but is still important

  32. Polymorphism matters by SimonK · · Score: 3, Insightful

    Encapsulation is only half the story. To get any benefit from OO, polymorphism is essential. Encapsulation does indeed get you nice organisation by itself, but you don't get any improvement of flexibility. With polymorphism added, you gain the vital ability to operate on objects without having to discover their runtime type. This lets you write, for instance, a catalogue system that can operate on video tapes or books, without having to have any knowledge of what exactly its working on.

  33. Resue and extend... by Razzy · · Score: 2, Insightful

    I doubt OO will help with computational efficiency in the problems you mentioned. Where it could help is in the man-hours department. Creating reusable and extensible OO objects can reduce your coding time on any particular problem a great deal.

    For example, I am a contributor to the Scythe Statistical Library which is essentially a big matrix object which supports many common operations. Scythe was initially designed by two professors who do a lot of monte carlo simulation. They still write programs that are essentially procedural to do each simulation, but the library greatly reduces the overall coding effort on each project. Other portions of the library (random number generators, numerical optimizers, etc) are as procedural and stand-alone as a standard c library. But matrices are so important that it makes sense to create an object for them. If needed we could create extending objects like triangular matrices, etc with little effort.

    In essence, if you can think of some portion of your coding effort that is object-like (a matrix, a polygon, an engine part) and important enough to many different projects, creating an object for it makes sense. This is especially true if you can think of sub-objects which you might use in the future.

  34. I think you asked the wrong question. by Anonymous Coward · · Score: 1, Insightful

    There is probably no problem that can be solved by OOP and not procedural programming.

    But then there is probably no problem that can be solved by procedural that can't be solved by machine code.

    The question should be when is it more appropriate to use OOP instead of Procedureal programming?

    For small simple programs procedural is often enough, but the bigger the problem the more chaotic procedural can become.

    OO can be safer as everything is kept in it's own little container. For example you have a simple snake game with a single snake. You have a snake object that looks after the snakes direction and has an array that looks after the location of it's body on the map. If you have a single snake it is easy to write it procedurally because all you need is to have a single array that looks after it's body. But what if you want to add a second snake? with OO all you need to do is create a new snake object. With procedural you would have to extend your snake array so that it can look after the second snake as well. Then you want to add a third snake, or X number of snakes.

    Again it is all possible with procedural, but what is simpler to do?

  35. OOP - It's about Structure (I'd say) by Pinky · · Score: 2, Insightful

    I've always viewed Objects and object oriented desgint to be usefull for structuring programs - that is making moduals simple to glue together.. getting rid of "glue bugs" (problems that occure when intergrating moduals). I don't think that Objects help make a program fast or efficient.. if anything they seem to work against it, making data structures fatter and blocking possible optimisations that could come from tigher integration. This is fine with me, however, since most of my problems come from people not understanding how each others moduals work or making errors that come from simply being un-experienced with someone else's code.

    I think you're looking at a tool that can be used to help structure, isolate and make code self sufficient to help with calculations and modeling.

  36. I work on the same thing you do by glyph42 · · Score: 2, Insightful

    I have implemented Monte Carlo radiation transport algorithms (read Global Illumination Renderers) and it would have taken me three times longer to do it without C++.

    What people forget is that every little structure, every little piece of data can be considered an object. You have samples for your Monte Carlo system? Make a class. You have some kind of representation of the environment? Make classes. You have radiation sources? Make classes. You have several sampling techniques that can be chosen at runtime? Make classes.

    Why? Haha. Because you get type-safeness, you get reusable code, you get increased readability, you get increased writability (no thinking "what was this int for now?) but *especially* the type-safeness, and it provides a nice framework for you to organize your code into (objects). Did I mention the type-safeness? How it saves yor brane from having to remember your structures?

    Is this more code? Sometimes. More lines, yes, but usually much more readable (shorter lines). Is it slower to do it this way? Well, I didn't win the APICS programming competition by not using C++ :)

    I use classes for just about everything! People forget that if you program this stuff *well* in C++, it gets compiled away! It's not a "solution to an engineering problem", it's a tool! It gets the compiler to do a lot of things for you that you used to have to keep track of in your head. You can even do OOP in C, for instance, by pretending to do your own namespaces (adding prefixes to all your structs and functions) but why not let the compiler do it for you?

    BTW, I strongly believe in the OO/procedural hybrid that is present in languages like C++. Data and functions are organized into objects, but the functions themselves are still procedural on the inside. So OOP is a tool for organizing your code!

    That's so important I want us all to say it together: OOP is a tool for organizing your code.

    This concludes today's lecture :)

    --
    Music speeds up when you yawn, but does not change pitch.
  37. Re:OOP Myths by Anonymous+Brave+Guy · · Score: 3, Insightful
    There is an interesting (and rather negative) review about OOP here (OOP Criticism).

    This is an oft-cited anti-OO article. However, it's clearly written by a very biased author, is hardly objective (no pun intended) and is littered with obvious misunderstandings about OO.

    Rather than spend hours dismantling his major arguments and point out all the flaws, I'll just post his "challenge" to the OO community to prove the superiority of OO:

    I have been asking for 3 examples of typical "small or medium custom business applications" or portions that demonstrate OO's superiority for this niche.

    I will even supply the procedural/relational version which to compare it to if you do not wish to.

    It can either be real code or pseudo-code. The example provider is responsible to answer any questions about the example. The example should be well-documented, and any oddities of the particular language used should be clarified.

    Now tell me, how many people are going to expend the dozens of hours probably required to fulfil this challenge, and then field an arbitrary number of arbitrary questions from the author as a result? Is this a reasonable challenge? Does he seriously expect anyone to take it up in earnest?

    Note also the rather gratuitous disclaimer, waaaay down (probably off most people's screens) on the front page of a whole anti-OO site:

    I have been programming small and medium custom business applications for most of my career. Most of my complaints against OO are related to this rather large niche. Perhaps OO is good for other niches; however, I cannot really answer for other niches.

    'Nuff said, I think.

    --
    If you disagree, post your argument. (-1, Overrated) isn't your personal censorship tool for views you don't like.
  38. Think macro not micro to get benefit from OO by anorlunda · · Score: 2, Insightful

    I'm an old FORTRAN guy who swtiched to objects, so I can relate as to the initial conceptual difficulty of choosing which objects and why. My best advice is to leave your engineering problem X code intact and think about how to encapsulate it to do more than you imagined in the past.

    I worked with power grid problems (load flow). Think of it as glorified E=I*R. In the beginning, we could accomplish 0.04 cases per hour. Today's computers run more like 4,000,000 comparable cases per hour. That's more than ample reason to think differently about how to handle a case.

    One way to take advantage of the extra computing power is to embed the engineering solver prodedures in optimizing programs. A linear programming engine object can be linked to my load flow encapsulated object. Together they might solve a million what-if cases to produce one optimum result.

    A 2nd example. The solver can be encapsulated in objects that make stochastic pertubations of key parameters. Thus your deterministic engineering problem solver could become part of a higher-level solver that gives probability distributions as results.

    A 3rd example: Modern load flow solvers are encapsulated in objects so that they can be called by higher level programs. GIS users can sketch out a new housing development and the housing object can create and place the needed poles, tunnels and wires and then turn to the 1960s-vintage procedure to calculate voltages and short-circuit currents then check the anwers against the building code objects. That could not have been achieved wihtout object encapsulation of the solvers.

    A lot of the other replies to your post focused on the use of objects at the micro level, linked-lists, wires, resistors, etc as the objects. My advice is to look in the other direction, macro rather than micro. Use them to stretch your thinking about what's possible to do with your engineering algorithms.

    Even brand new programs sometimes benefit from cutting off the OO at the lowest levels. Ask yourself why C++ keeps ints, chars and so on as non-object atoms while Smalltalk lets you make objects of everyting down to ints and chars and even bits if I remember correctly. It's lots of fun to play with but the overhead of too many micro level objects is great. All in all, I've gained much more benefit from objects that focus on the macro management of algorithmic solvers rather than the micro details. That's one of the problems I have with MathCAD use; as soon as the CAD programs solve the problem, they become a hindrance to encapsulating the result as an object to be used by higher level programs.

  39. In defence of C++ by Anonymous+Brave+Guy · · Score: 3, Insightful
    You obviously never read the slashdot article about how C++ at runtime must instantiate all the objects and do some other funkiness that makes startup time slower than C.

    I read it, and gave up partway through the discussion, because most of the comments made were so much ill-informed FUD that it actually made me angry. It's true that C++'s biggest problem is the ignorance of the programming community, but I had hoped for better from the /. community until I read that discussion.

    The extra overhead involved in initialising objects in C++ is similar in both purpose and time consumption to the overhead when you first load a C program. It may take marginally longer, but it's measured in milliseconds, and a one-off when you first start up. It's one of the few places where C++ can genuinely be slower than C, and it's still hardly worth mentioning.

    Oh and here is an article you may want to read -> http://www.gamedev.net/reference/design/features/w hatlang/page3.asp It talks about some of the tradeoffs of using C++ vs C.

    I really hope your perspective isn't based on articles like that. It's well-meant, I'm sure, but there was never any debate about whether C++ was slower than C in informed circles, because the answer is obvious: no. Whether you look at the theory of the languages (try reading The Design and Evolution of C++, by Bjarne Stroustrup for some insights) or simply code generated from C++ and the equivalent functionality in C, you find the two comparable on all counts. There is far more variability in quality between compilers of either language than there is between the two languages. In fact, some language features allow C++ to make optimisations C couldn't even dream of, bettering it several fold in performance.

    Also there are other reasons why C++ is not that good a programming language and here is a guy who was talking about creating D programming language -> http://www.digitalmars.com/d/ and some of his reasons for this.

    ROFLMAO. I'm sorry, but this is just not carrying any weight with me. Let's look at a few quotes from the first couple of pages, and see how the author demonstrates a lack of consideration on his part, not that of the group behind C++.

    Yes, C++ does provide the meta programming ability to implement resizable arrays and strings like the vector type in the STL. Such fundamental features, however, ought to be part of the language.

    No, that is exactly the wrong decision. These are not fundamental features in a language with low level support. Much better to provide a simple language with solid foundations, and build a powerful library on top, than to clutter a language with "powerful" features, but then find the next time you need a new powerful feature, you have to change everything around, or can't add it at all. These features are still available in C++; what difference does it make to the developer whether they are built in or part of a standard library?

    Features To Drop: Multiple inheritance. It's a complex feature of debatable value. It's very difficult to implement in an efficient manner, and compilers are prone to many bugs in implementing it.

    And yet, many languages (not just C++) implement MI quite happily, in various ways, with good efficiency and few bugs. Speaking as someone who uses this feature on a regular basis in large application frameworks, I can say with some authority that it's rarely appropriate, but when it is, it's horrible to be without it. Supporting interface inheritance alone is not an adequate solution to replace many useful MI idioms, however much those without MI like to claim otherwise.

    Features To Drop: Operator Overloading

    And how exactly were you planning to write useful generic algorithms without this? Many critics slam op overloading, and many of the same advocate the introduction of generics into their language of choice. Few have thought it through enough to see the connection. Again, C++ got this one right.

    Features To Drop: Creating object instances on the stack. In D, all class objects are by reference. This eliminates the need for copy constructors, assignment operators, complex destructor semantics, and interactions with exception handling stack unwinding. Memory resources get freed by the garbage collector, other resources are freed by try-finally blocks.

    Riiiight. So we're going to improve on C++ by removing the ability to write classes with value semantics, or indeed programmer-definable semantics at all. Further, we're going to be replacing the powerful RAII idiom with the rather underpowered and error-prone try-finally construct. And this is progress?

    Features To Drop: Non-virtual member functions.

    Unless you're going to provide a smart alternative, you just hit your performance big-time. In doing things like this, you cripple your language for developing truly high performance apps.

    Features To Drop: Support for 16 bit computers.

    OK, let's rule out writing for embedded systems completely as well.

    I could go on, and dismantle many of the other myths, personal views that are far from universal and downright misleading claims on the site, but I don't see much point. There are certainly flaws in C++ -- some of which will be addressed in the next revision -- but things like having MI and op overloading are not among them. Putting C++ down on that basis, in the face of informed opposition, just makes you look like you haven't done your homework.

    You know, the best bit of that page is the "Who D Is For" bit. I guess I qualify, as do many I have worked with, on about 75% of those counts. Yet the arguments given in the previous "Features To Drop" section would immediately convince me that D wasn't a serious tool.

    --
    If you disagree, post your argument. (-1, Overrated) isn't your personal censorship tool for views you don't like.
  40. Re:what should i use? by Anonymous Coward · · Score: 2, Insightful

    Glad to see so many mentions of Python, and i agree. Its a great language, with clear syntax, powerful built in types and many many useful libraries (web server library as standard... what are thinking?)

    Python makes excellent glue for bringing in a lot of different parts to make one program. The thing is that for a lot of the time glue is all you need.

    When you need more than glue, I recommend some other languages, and some super-glue. If Python can't do something fast enough, Ada can ( I was shocked to see a teeny ada program outperform a teeny C program by a factor of 5, and all it was doing was a simple calculation several million times. The Ada compiler must have done a truly great job .)

    If you think you can express certain parts of the system better in a functional language, such as haskell, then use haskell for those certain parts.

    And as for the super-glue? CORBA is an amazing system for getting languages to talk to each other, even with parts being run on other machines ( if you need high MFLOPS in one function, make sure it runs on a mchine with high MFLOPS, makes sense to me ;)

    So yes, I would recommend you start by learning Python. If that is ever not enough for a part of a system, use something else that is. I like haskell and Ada, as I think they represent the best there is for their target audiences. I can say the same for CORBA, I think its the best super-glue on the market, and enables many languages to integrate seemlessly.