Can OO Programming Solve Engineering Problems?
"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."
Your problems are too small and specialized to realize any significant advantages of OOP.
It's not that you can solve problems in OOP that you can't solve in Procedural (Fortran/C like), it's just that for many problems, OOP is much faster, allowing you to re-use much code to deal with things in a similar way when they can be and use the specifics only when needed.
Functional programming is better suited to solving engineering problems. You don't need the overhead of OO design for your engineering programs. I would stick to C unless you are trying to do some kind of fancy GUI.
Today's Sesame Street was brought to you by the number e.
Most engineers have been taught that FORTRAN is the way to solve problems in engineering. If everyone starts out with that prejudice and is stuck there.
Where I work, there is a project to write an engineering application in VB, and it has seemed to be one problem after another after another. (I know i know, VB is crap). The core library functions are in C, in a DLL, so I guess thats a bit of a start.
FORTRAN has been ingrained into the current working generations of engineers, so they're going to use what they know.
Heck, I've even seen SQLPlus code (from Aspen) written very very very FORTRAN like. Instead of using min(), max(), there was a bunch of select looping and checking variables..... Oy.
In my opinion, OOP is only good in large scale yet generic problems. I've seen many people do C/C++ combonations where they filled in C++ gaps with their own C code.
Maybe another way to look at it is to use what you know. It seems like a good amount of engineering students use fortran or pascel to do their engineering work in. As a computer science guy I hardly ever see fortran or pascel when doing my work (school or job), but it boils down to the fact that it works and thats whats important.
So what would be a good language to learn for a beginning mechanical engineering student?
The masses are the crack whores of religion.
This is a really difficult question to answer. I guess my reply would be that no, pure "OO" programming wouldn't hold any advantage to simple procedural programming in this case. However, you can easily add procedures to objects, so OO language is really just a superset of procedural.
Personally, I like the organizational potential of OO. You can have a Pipe object, and call function like Pipe.calculateFlowrate(12,43,23), then you could have a subclass SquarePipe, and call the function SquarePipe.calculateFlowrate(12,12,43,23).
Essentially, you could have 10 objects each with 10 functions to do 100 different tasks, rather than 100 different functions to do 100 different tasks.
Moderation: Put your hand inside the puppet head!
There are a number of ways to approach this, but I've found the following useful:
It's more a matter of thinking in terms of telling your processes to do stuff than creating a road for them to walk down. If you know what I mean
All your Qaeda are belong to US
I am not experienced in OOP programming anymore, especially how good the compiler are now, but maybe OOP is mostly used for its inheritance in data structure , and reusability of the code (enhance UI, management problem etc...). On the other hand, physic and mathematic problem require usage of pure processing power on calcul. Maybe OOP would help add an UI layer, but using data structure with OOP in raw calcul might add an innacceptable "slow down".
C. Sagan : A demon haunted world:
http://www.amazon.com/gp/product/0345409469/
visit randi.org
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
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.
if you are plugging numbers in and expecting numbers out then procedural would be just as good as anything.
but there might be other applications where oop will really pay off for you. one thing i can think of is possibly simulations.
i think oop was first used in northern europe (yeah before PARC) to simulate manufacturing systems.
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)
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
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
Some of the replies here are a little confused. To paraphrase The Princess Bride, the word does not mean what you think it does.
Functional programs evaluate expressions rather than execute commands to "get stuff done". Scheme (which is derived from Lisp) is one of the more well known functional programming languages.
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
If a program's sole purpose it to generate numbers based on other numbers, I don't see any reason to force OO methods onto the system. But if it's part of a larger system, then you may want a class that behaives like an object to the world, but acts like a function set internally.
So there's no easy answer. Unfortunatly, the real answer is to spend a year or two coding in C++ or Java and becoming familier with OOP concepts. Then you'll be able to answer your own question.
Maybe its just us new eggs, but I've only been taught using OOP, through MATLAB code, which is almost the same as C/C++.
S
------
The City of Palo Alto, in its official description of parking lot standards,
specifies the grade of wheelchair access ramps in terms of centimeters of rise per foot of run. A compromise, I imagine...
The reasonable man adapts himself to the world; the unreasonable one persists in trying to adapt the world to
...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.
Despite what the 13 yr old computer science experts on Slashdot might tell you, Fortran (esp. Fortran 77) rocks. Stick with it. Remember the KISS principle.
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.
How do you write a million lines of maintainable code in six months with 5 programmers in Silicon Valley and 50 in Turkey? Hint: You don't do it in C.
OO programming is not just about modeling the problem well, which in and of itself is enough to recommend the approach to an engineer. It also addresses the very difficult task of generating and maintaining a large software project in a form that a human can understand. For many small tasks, the extra overhead involved might not be worth the extra effort required if you are not already comfortable with the OO metaphor.
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
Read the following book:
Object-Oriented Implementation of Numerical Methods: An Introduction with Java & Smalltalk
by Didier H. Besset
One of the items I've run into is that FORTRAN natively supports complex numbers. C doesn't support them, and I need to use the Standard template library in C++ to get the support.
After I've used the STL, I then don't have the huge library of old code that I can draw from in FORTRAN.
I much prefer writing in C / C++ to writing in FORTRAN, but there's lots of legacy FORTRAN code out there that'll get reused.
When you get down to it, every application, at some level, is a database of some kind. ie. it will end up storing many records of the same or similar type, usually in memory, and then go and do actions on those records. Weather each 'record' is a data packet, plugins for your application, records from some kind of file, whatever. In the end, it all acts a little like an in-memory database.
....) you would just do mystruct.do_something(...). Which when you think about it, is a more logical solution. Almost every function you write, except for the straight out code-flow, and accessor functions, is some kind of operation on a data record in your 'in-memory database' (however it is represented). OOP's main purpose is to more link the functions doing stuff to the data, and the data itself. Nothing more, nothing less.
.c file, and you know they're all related to that structure because they're in that particular .c file, you instead put all the functions in a class, and you know the funcitons work on that data, because the data, and function, are all part of the same logical unit.
... its just a cleaner way to group together data and functions that work on that data in a more 'binding' fashion, something that had to be done by the coder's memory and by hoping the previous coder's comments were good enough to make it clear what goes with what.
The traditional way to handle this kind of thing is with a linked-list or array of structures. The main thing OOP gives you is not any 'special' solution to old procedural programs -- infact, a good blend of procedural and OOP is always the best solution, because every program is a combination of both. However, what OOP does give you is a nice way to encapsulate all data that is relevent, instead of into a structure, into a complete package.
Instead of calling functions, and passing that object around, and then worrying about lost pointers, NULL's, etc. You take the more logical course of action, and perform the action directly ON the object. ie. instead of doing: do_something(mystruct,
Things like inheritance, templates, polymorphism, etc, are all just fluff to make coding easier, that has been added on top of the OO ideal. Granted, they make life ALOT easier (dont get me wrong, I use all of them all the time, and I'm an OO junkie), but the main purpose of OO is simply to create logical units, including code, and data in one block. So instead of having a bunch of structures, and then all functions to act on that structure in one
So I think you've mistaken the benefit of OO. As I said before, OO is not some kind of magical wand that will solve even the most complex of computing programming problems easily
One example that comes to my mind immeiately is MMTK ( link) (Molecular modeling tool kit) developed in python by Konrad Hinsen.
OOP isn't going to help you solve your math problems, for the most part. If you're dealing with a lot of objects, it could clarify things. For example, if you had physical objects with a list of properties like dimensions, temperatures, etc... you have a few options.
You could have parallel arrays, like
double nObjectX[100] (array to be clear)
double nObjectSpecificHeat[100]
...
This would certainly work, and you could write functions to work with data as it is here.
But if you thought of all of these as properties of one object, (ie Object.X, Object.SpecificHeat), you could:
- pass them to your functions more easily
- make your code more clear
- impress your programming friends
It could be that none of the above will help you at all. There is, by definition of how computers work, nothing that you can do with OOP that you can't do without it. And lots of time it's more effort for the same product.
.
Let's not stir that bag of worms...
Prakman, nice sig, I wake up listening that song everyday!
Broken Hearts are for Assholes. - Frank Zappa
There are some areas where OOP is considered undesirable. The avionics industry, for example, makes very limited use of OOP because certain aspects (garbage collection, dynamic allocation of resources, & others) raise safety-of-flight issues. Certification authorities prefer things more controlled, as plane crashes are generally considered a bummer.
This is also why the aviation industry doesn't adopt new technologies quickly. It prefers to wait until they have a proven service history. The 486 is stilled widely used in the industry, for example.
gm
Ad luna, Alicia! Ad luna!
This is "just" numerical code, but maybe will give you some ideas:
http://www.oonumerics.org/blitz/ (Blitz++)
Not really, but there is an element of truth to that mantra: most engineers traditionally learned to program in Fortran, and there were some damn good Fortran compilers/libraries to handle the types of matrix manipulations commonly encountered.
You don't need the overhead of OO design for your engineering programs. I would stick to C unless you are trying to do some kind of fancy GUI.
While abstract classes will incur the hit of an extra level of indirection in a function call, and exception handling in C++ can be expensive (as can multiple inheritance), these features only cost you if you use them.
Now, to answer the question at hand, I have helped to design and develop commercial speech recognition products using C++. Of course, there was plenty of C and hand-tuned assembler there as well.
A more concrete example would be the VFS in Linux, as well as the classes of network, block, and character device drivers -- while generally coded in C, they represent the notion of abstract base classes unifying a common interface to many different implementations -- there's no reason C++ could not have been used there.
You could've hired me.
...............or Forth maybe?
First off you're examples Monte Carlo simulations and differential equations aren't "engineering problems". They are math problems that are a component of an engineering problem. Engineers does things. It builds a bridge, drives a car, prints a document. The examples you give are parts of that solution. Every GUI needs to do things like interpolate colors and position, which are the same class of problems -- if orders of magnitude simpler -- as differential equations and Monte Carlo simulations. So it seems to me that you need to figure out what your real problem is and figure out what programming paradigms might help you out with that.
As others have pointed out OOP doesn't let you solve things that are otherwise unsolvable. It is a way of solving problems that may be better in some situations and worse in others. The examples you give of solving equations are all better suited to a functional language than a procedural one like Fortran, so rather than asking "why use OOP" you might want to first ask yourself "why am I using Fortran?" Obviously there are a number of factors that go into how we pick our solutions. Maybe OOP per se isn't a good fit for your problem but you need it to be multiplatform and have a huge amount of available code and standard libraries so you end up going with Java. Or whatever.
The kinds of problems you're talking about don't have a great mapping onto the traditional ways of describing OOP. However, OOP is really just a somewhat formalized kind of way of dealing with abstraction and data encapsulation. You can make a difference equation a class. Maybe it'll only have one method that immediately finds all the finite solutions. But once it is a particular datatype you can also do things like compare whether two user-entered difference equations are identical and just returned the cached solution. You can curry them. You can return partial solutions and then come back later and ask the object for more solutions.
Don't you already have discrete data types for these things? And don't you already have functions that operate on those discrete datatypes? Then you're already doing OOP. Sure you're not using inheritance and multimethods and things like that. But not every OO program does.
Fortran already has most of the really basic objects used to solve engineering/numerical analysis problems: Integers, reals, arrays, matrices, subroutines, functions, etc.
Object-oriented languages are so popular at the moment because it's a way of adapting a language to a new problem domain (keep in mind that C was written to write an OS kernel, and it's only through bad luck that folks are using an extended version to do everything under the sun today).
But just as C++ and Java are (slowly) displacing COBOL for business applications, I think we'll see object-oriented code displace Fortran and C for number-crunching. (Remember, COBOL was written specifically for Business applications!)
I honestly don't know of a good book on numeric computation that is truly object-oriented. The current edition of Numerical Recipes in C++ doesn't really take advantage of everything you can get from an OO approach. Maybe the new edition of Numerical Recipes in C++ will do a good job at this. Still, the current version shouldn't be ignored, there are some good ideas about how objects can really help in large computational challenges.
To the question "Can OO programming solve engineering problems", I would answer an emphatic yes. However, the engineering that I do at my place of work has to do with coordinating RADAR tracks in an air traffic control system, among other things. OO principles are applied to this domain with excellent, elegent results. The problems you are talking about (though I don't pretend to understand them) sound like very specific mathematical ones which are probably best solved in a procedural fashion, perhaps packaged up neatly into a class. However, just because it's the only engineering problem you are faced with, don't make the mistake that OO design principles cannot be applied to any engineering problem domain.
--
CPAN rules. - Guido van Rossum
OO languages exist at the "high" end of the language-level spectrum. They're geared toward managing code complexity in the face of a problem domain which is conceptually complicated, primarily by encapsulating bits of the problem domain into digestible and self-contained sub-problems. The overhead of all of the OO constructs is worth it if the reduction of your problem domain into smaller chunks is neccessary to solve the problem (or advantageous in terms of directing the efforts of multiple team members in areas where some decoupling is possible).
However, if you problem is "low-level" or conceptually simple (though not neccessarily computationally simple) -- a recipe like "apply transformation x to dataset y, then transform again w/ algorithm z", the OO features simply serve as a distraction from thinking about your actual problem domain and it's solution.
So yes, IMHO, there are problems for which OO techniques are not ideally suited, and most importantly, if the techniques get in *your* way they are not the right tool for *you*. Rememer, languages and tools don't solve problems. People do. If a tool makes you task easier, use it. Otherwise, save yourself the time.
When I worked at AEDC I spent some time involved in NASA Lewis (now Glenn)'s numerical propulsion system simulation project. The idea of this project was to apply OO principles to turbine engine modeling.
Each component of a modern engine was viewed as an object (compressor, turbine, burner, etc). The solver could use helper aplications of any complexity to model components, then tie them together (very useful for integrating proprietary codes with a common architecture).
I could talk a lot more about it but it has been years and it would be better for you just to follow the link...
neh
... and there is no doubt, that one day he will be
where the eye of his telescope has already been
It could be that the OO methodology simply isn't applicable to the problem area you're interested in. OO is fine for describing/developing some parts of a system, but not for others parts. Just as functional or logic based formalisms are good at some parts and bad at others ...
Each of the examples you give is essentially a function (ok I'm not 100% familiar with everything you mention, but from what I know...). In OO design, each of these would be a discrete "building block", think of each as a specialized calculator. Now if you're just trying to solve a single equation, (in my opinion) yes it is too small for full blown OO.
However, if you have a function that say, needs to do many integration, derivation, or whatever steps, you can write an object instead of just doing a function. The advantage of writing a integration object instead of just a function is that you are forced to pass in all of your data, and thus the object is reusable (it in effect becomes a library). You could include in the same object many different types of integration, single, double, Legrande, although I would separate out derivatives.
I guess another (abstract) way to relate it is to buying a new computer. You can either go to Dell (or whomwever) and buy a new package every time and pay a premium, or you can just upgrade one module at a time - your hard drive isn't big enough, get a better one, not enough RAM, get some more, etc.
And if anyone wants to flame me about how this will lead to a legacy system let me point out that: a) Linux runs on a 486; b) it's just an abstraction!
Kurdt
I'm not anti-social. Just pro-technology.
For simplicity's sake, let's think about quadratic equations for a second. You can solve them easily, but if you want to use them in a larger program, you could create a QuadEq object in OOP with the following properties:
An OO programmer would then add methods to set, retrieve, and calculate those properties based on what's been entered. And the QuadEq object would be entirely portable and easily amplified for future equations.
I don't think choosing OOP is a matter of being the only tool to solve certain problems. However, it is often the most efficient way to solve large, rapidly-changing problems. But like you said, other problems (like many of the ones I encounter in web development) will be small and uncomplicated enough that the overhead of OOP isn't worth the trouble.
look here:
http://www.oonumerics.org
(not just blitz there)
Working for necessity's mother.
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
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.
I think the "answer" to your question is that, yes, your examples are too simple. When you're doing some simulation where the "finite difference solutions to non-linear equations" all interact with each other, and with computed fluid dynamics and heat transfer, etc, you'll immediately see the benefit of separating all these concerns into encapsulating object types.
[
The kinds of problems you're trying to solve aren't problems object oriented designs are good at. While OO is a natural way of dealing with some concepts (for example, GUI concepts), its real power doesn't come from this kind of thing. It tends to be best for designing very large systems that are complex and may change significantly over their life-time. The kinds of problems you mention (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.) aren't really the kind of software engineering projects that require carefull design. They may be hard problems, but they're also understood and well studied problems.
Take a step away from the scientific problems and consider something like an inventory management system for a pharmacy chain that needs to be solid and accurate, while at the same time collecting data and producing pretty reports for whatever statistic the company directors think is important on that particular day of the week. A slightly different kettle of fish, no?
Another often stated advantage of object oriented programming is component reuse. It seems that most developers don't really try, but for a little bit more effort and thought, object oriented techniques make writing highly reusable software components easy.
For my own personal projects, I have a set of classes that do all sorts of things for me, from a log file manager to a small LALR(1) parser which I have a generic config file parser built using (all in C++, no need for external programs). It's a pain in the ass to write the code originally, but it was all well worth the effort. :)
Using polymorphism if you have different types of data to solve certain problems you can use your objects to create multiple inputs with the same name, just different data type inputs.
An excellent example of complex mathematical algorithms implemented with an object model is the quantlib project. Financial modelling is a kind of engineering, although usually more rewarding monetarily than electrical engineering.
From their front page:
The QuantLib project is aimed at providing a comprehensive software framework for quantitative finance. QuantLib is a free/open source library for modeling, trading, and risk management in real-life.
QuantLib is written in C++ with a clean object model, and is then exported to different languages such as Python and Ruby. Bindings to other languages (including Java), and porting to Excel/Gnumeric, Matlab/Octave, S-PLUS/R, COM/CORBA/SOAP architectures, FpML, are planned for the near future.
Ethics II Axiom 2. "Man thinks." B. Spinoza
In a finite element program you would probably have an object "Mesh" that holds all your elements. Now as you probably know you can have all sorts of different element types with different solution methods. These can all be implemented as subclasses of an abstract "Element" class. A method element->solve() (or solutionIteration() or similar) would then take care of hiding the different solution methods from the higher layers of the program.
If you want you can extend this method even further, implementing a Node object that can be shared by multiple elements. By subclassing the nodes you can implement things like boundary conditions.
You see, the problem now becomes a connected forest of objects that are rather uniform, but can have their own specific rules of behaviour when needed.
I'm not saying this is not possible with regular procedural code, people have been writing procedural finite element simulations for years. What i'm saying is that if you want to bring some architectural sanity into the world of computational science (and god knows it needs it...) OO might help.
Note that if for whatever reason you cannot/do not want to use an OO language, you can still think OO. You can then implement the thing using a regular procedural language that has some way of keeping data together in a logical way. Structs in C are perfectly suited for this task. This way you might miss some of the neat OO features, but the resulting code will at least have the advantage of keeping data and related code together.
Pathman, Free (as in GPL) 3D Pac Man
From the 1920's through the 1960's it was quite common to solve engineering problems with analog computers. Some analog computers were mechanical and others were electronic. These machines were inherently object-oriented. One built the program by connecting together components (objects) into a model of the system of interest, and then observed the results. If O-O software hasn't reached this level of capability yet, maybe there's a problem with the way we do O-O.
It's not necessarily a matter of mapping a specific engineering problem to an OOP model that will yield benefits. I see OOP as valuable for any large software project even if the problem itself is not particularly object based. User interface code maps better to OO designs and collaboration in a developement team tends to work more smoothly with an OO framework. I think it is in the general construction of an application that OOP will give benefits (if used properly) rather than in the specific solution to a specific problem. In that sense, any engineering application could benefit. For small problems (and small applications) I generally use an imperative language like C or Perl, but for larger projects I favor a OOP approach.
- Russ
A lot of engineers have trouble with the problem "Staying employed during a recession." OOP is the cure - every bit of code you create is now unmanagable to your cow workers. As such, you can't be fired.
Moneyed corporations, non-working 'poor' and criminal prisoners are turning productive citizens into tax-slaves.
My personal experience has been that OO is a big win when a problem is subject to factoring. By factoring, I mean that when you take each element involved in the problem, you can find common factors between them. In that case, you get a natural class hierarchy by moving the common elements into parent classes with each individual element being a subclass. The reduction in code size decreases the number of bugs substantially.
One way you can detect this is if you are doing a lot of cutting, pasting and modifying during development. Often this is an indication that a better design would be to have one copy of the base code. All the other elements that had copies would now essentially inherit the base code and then override the parts that need to be changed for that particular element.
If your project is not going to involve a lot of inheritance, then OO is really only useful if you are in a large project, in which case it acts as a useful way of delineating responsabilities. (i.e. all I have to do is implement and test these interfaces and I don't have to worry about stepping on other people's toes.)
This is all a great simplification, but it covers my experience in a nutshell.
I'm an electronic engineer and a little while back I was playing around with an algorithm for designing impedance matching networks (circuits that make one impedance look like another one). The network can consist of series inductors, parallel inductors, series capacitors and parallel capacitors. I implemented each of these components with an object. So OOP can be used for some engineering programs!
On the other hand, heavy duty computations are probably not well suited to OOP because there is a very slight overhead involved with using objects. This small overhead can be multiplied a HUGE number of times for very large problem and can increase the computation time and memory requirements. That's one of the reasons FORTRAN is still so popular for heavy duty calculations: it's very simple and has no unnecessary overhead to speak of. Add to that the fact that it was designed for heavy duty mathematical work in the first place and you have a winner.
Just my opinion mind you!
. . .take a look at some issues of Computing in Science & Engineering; they have a website, although much of the actual content isn't free. You'll find some successful OO applications there.
I decided that behaving ethically was the most nihilistic thing I could do. - Paul Pavel
For my Master's Thesis (in ME) I created a FEM applet written in Java. OOP works well for this application since elements can be treated as objects. In theory, you can add new element types to your code by creating a new object with an appropriate interface.
l ac ementMatrix);
OOP also helps with mathematical entities. Java lacked a suitable Matrix class for Force and Stiffness matrices. Luckily, OOP made it practically trivial to create new classes to not only hold the numbers, but to also encapsulate matrix algebra. Want to multiply a matrix by another? You can easily do something like this:
myForceMatrix=myStiffnessMatrix.multiply(myDisp
In short, I found OOP concepts very helpful for my Java finite element applet.
- Perldivr
There are quite a few finite element programs in OO. Some CFD code too.
I use various methods of solving partial differential equations in large scale applications like segmentation of medical images. As I am sure will be expanded upon by others, OOP methods do not help to solve the problem per se, but they can make coding and debugging much easier. With complex algorithms that can be the difference between a single researcher applying the algorithm in a month versus 6 months and having to get 2 or 3 others to help code.
An example:
I have a Data class that can store itself (serialize) in a standard scientific data format, like HDF and can perform other various tasks (get, set, null all values, add, subtract, etc). Now I might have subclasses that specialize to vectors, 2D arrays, N-dimensional arrays, etc. The basic functionalities are inherited and once tested will be less likely to cause problems in other classes. Lets further say that these classes are parameterized, i.e. templates. Now the basic functionality works for floats, doubles, unsigned char's etc. I could of course get this same functionality with normal procedural programming, but in the end my colleagues and I will be more productive.
OOP is a tool, just like an oscilliscope or a strain guage. Not using it when appropriate is not good engineering practice.
I've done programmnig for truck engineering support.
Objects are things like engines, axles, gears.
"finite difference solutions to differential equations, finite-volume computational fluid dynamics, iterative solutions to non-linear equations, Monte-Carlo simulation of radiative heat transfer" are process to be run on objects. They may be objects also, but OO is best at helping you organize you data.
My experience with IT supporting engineers is that engineers first think of the process, then the data (data may be denormalized data sitting in some table somewhere, but here is the math that we want to perform on every row) and IT concentrates on organizing the data (here is an efficient datamodel for that data that you want to perform some operation on). See how OO would better fit the needs of the IT staff?
The trick is understanding what engineering wants to do with data, so your object models facilitate their computations, not get in the way.
The work I did was to model the truck, then using math supplied by engineering, we performed simulations with our models. The advantage was that engineering couldn't do the simulations alone because they couldn't get their minds around the vast amount of data and we couldn't do the simulations, because we didn't know the behaviors of the materials.
We acutally had objects like a transfercase that had a bracket location, gearRatios, input location, output location, currentGear, inputRPM, outputRPM, etc. Some of these values were calculated and some we given depending on the type of simulation. The trick was deciding when to calculate values and when to use cached values. (we used a dependence graph that was implicitly constructed) Are simulation would include activities like running the engine through the RPM range and each gear of the transmission, and articulate the rear axle through its positions to find binding in the drivetrain. Using these simulations we were able to select some parts (is this axle better than the previous?)
Joe
Joe Batt Solid Design
OOP is good for big programs with complex workflows. When you have 50-1000 developers working on a single product you need to devide their job. For these projects OOP is a must. Even if you work on a project alone you will be more organazed by using OOP. OOP can also be used to improve reuse of the code, but I rarly see a library that is designed well enough to use it. Well designed libraries usualy designed in such way that mistakes are not easily made. If you not sure why OOP might make you program better, you probably will be better off not using it. This exspesialy true if you procedural way of programming gets job done..
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.
Although Industrial Engineering (IE) reflects different problems than your more mechanical examples, IE is definitely engineering and its problems can be solved (conceptually) better with OOP. Why? Because IE deals with large-scale simulations involving multiple discrete parts. The systems cannot (typically) be represented by a system of differential systems, and instead must be modelled as independent parts communicating with each other. In other words, these are complex systems.
For example, I'm a research assistant in a project studying realtime promising. (Essentially, this project is looking at ways to determine the due date of an order quickly and accurately. This way we can avoid saying 6-8 weeks to deliver...) Although the different algorithms and heuristics could be included in a procedural or functional paradigm, the overall size of the system (>10,000 lines) along with the complex data types (some with more than 20 attributes) lends itself best to OOP. Earlier versions of the code were written in a more procedural fashion, but by moving toward a more OOP framework the code has become simpler and easier to manage.
Additionally, since this is research software, ease of making changes is a high priority. It is easier to be able to make changes to key systems without disturbing other code within an OOP system than with procedural or functional code. If the system was already well-understood, then a straight-forward procedural solution might be preferable.
I would like to add that my statements about functional programming do not include functional programming with objects (ala CLOS).
Imagine for a minute that you don't know what problem you want to solve yet. You know that that you want to apply a Galerkin Finite Element Method (for instance, though this particular method isn't required) to a whole class of problems on unstructured grids on a whole class of distributed and shared memory parallel computers. Imagine that you want your user base to be able to specify their equations like they would in LaTeX or some other markup language. Now try imagining that you have only FORTRAN77. Not a pretty picture. We're in the process of completing a rewrite of major sections of our parallel code to do exactly this. Our code started out (7 years ago) as an extremely efficient parallel (3D) C/F77 code for Navier-Stokes + Heat Transfer and is quickly growing into a multi-purpose, multi-physics code written largely in C++.* We extract considerable advantage form C++'s ability to hide implemenations so that as long as interfaces don't change the guts can. We also make good use of the ability to run code before main() in order to register the exisitence of routines (hash tables are your friend). If the routine isn't there you can't call it, but the code still compiles and runs otherwise. We also make use of base class/derived class relationships and polymorphism to allow, for instance, one base mesh class for the rest of the code to interact with, but with two separate derived classes: one to generate meshes internally, and one to read meshes from other programs. Etc., etc. I'm not sure our website can take the /.'ing, but you can look here for some hints.
* I say largely b/c there's a few struct's still left over from the code's C days, but all the F77 is gone. There are still calls to assembly coded (vendor supplied) BLAS routines, though.
Yes...I am a rocket scientist.
Remember that OO code tends to compile into slower and larger executables than structured code. This is not always the case, and optimizing compiliers can do a great deal to mitigate this, but the fact of the matter is that OO code was developed to give coders more power and shorter development times.
Most of the engineering problems that I've ever seen solved in code are math intensive. One such problem was calculating the drag on a certain aircraft wing. If I remember correctly, the coder who was showing me her code indicated that the math involved broke down into a repetitious series of a few hundred cross-section integrations. These equations had to be solved for several hundred thousand cross sections to get a final result and a chart. At the time ('91) there was no 3d model, and the calculations were being conducted on a desktop computer. As you can imagine, it took a very.. very long time. One of the people I was with asked her what she was doing her math in.
C. C++ had too much overhead, she complained, and the C compiler she was using was slightly faster than Pascal or Fortran. She was very seriously considering trying to translate her equations to register-based assembler code to speed up the process.
If you have an engineering problem, and you're happy with the results you get from a funcational language, it's probably not worth your time you'll lose from switching to an OO language.
If you
The next Slashdot story will be ready soon, but subscribers can beat the rush and slashdot the links early!
From your post is sounds like you're solving single solution problems where you write a 'disposable' procedure (probably reusing some code) for each problem. OOP isn't designed for that.
OOP really starts to shine when you actually have objects to work with. If all you're doing is trying to solve a single solution problem a simple 'disposable' procedure is the best route. For larger, evolving, iterative projects OOP is a godsend. In my case, I'm designing a MAV (Micro Air Vehicle).
I'm using Python instead of C++ but the OOP example still holds. Aircraft design is a highly non-linear process, and for myself at least, counter-intuitive. I could write a single procedure to run the analysis but that's not nearly a flexible as an OOP solution.
Basically, I'm using off-the-self components (i.e. motor, batteries, propeller) as a starting point for my design. Each of these components is considered an object. These components are combined in such a way as to make another object: the entire MAV. By using OOP it's rather easy to try different component configurations and design conditions (flight altitude, cruise, loiter, velocity, etc).
If I was really cool (I'm not) I could add in some simulation stuff (Larger aerospace corporations do a lot of this, as it's cheaper and quicker than an experimental approach).
One thing that this sort of OOP approach lends itself towards (especially in my case, is genetic algorithms). Since aircraft deisgn is so non-linear, and counter-intuitive the best solution is not easy to find. So many different designs need to be analysed. OOP and genetic algorithms were born for just this sort of thing.
If you have a single problem that needs to be solved once for one set of conditions, then use a procedure. If you have a larger project that requires the solution of many smaller problems for various conditions (instances to use the OOP term) then OOP is an easier route. Anything in between is a judgment call and really depends a lot on your specific case.
For most physics/engineering problems, though, you only have a single type of object. For example, in a FEM heat transfer problem you would have
- A vector that relates actual position (x,y,z) to node index
- The thermal conductivity at each node (a REAL)
- The current temperature at each node (a REAL)
There is no hierarchy of data here to exploit, so proceduraly progamming will be the easiest to work with (especially if that means using a language you're already familiar with).Let the data determine the language you use, not the other way around.
-JS
Vanity of vanities, all is vanity...
Many people confuse OOP with C++. The two are not the same. C++ contains enhancements that are _supposed_ to help OOP, but often don't.
I've been programming for more than 24 years and have dealt with languages from assembly to FORTRAN. I learned to program in assembly before PC's were even invented. I have always written code as modular and reusable and in a sense in an OO style. I've solved many problems, some large, some small, using OO programming without using C++. In fact, I try to avoid OO C++ for many reasons, though I prefer to use a C++ compiler and a smattering of C++ functions/keywords and style.
I think you will find that many problems have been solved using OOP, but that the definition and composition of OOP is often misunderstood. For a good example of an application that is written using OO techniques, but does NOT use OO C++, see the Quake II source code.
The reasons I avoid using OO C++ is due to inefficient compilers, the tendency to generate hard to find/fix bugs, excessive overhead, and the tendency for other programmers (if I'm working in a team) to overuse/misuse OO C++ features (e.g. - operator overloading). To date I have been able to accomplish the same tasks, with the same OO designs, using straight C, with less hassle and greater efficiency.
- Rohan
OOP will help you manage your code, not your engineering.
I'd recommend that you check out the Ptolemy project (http://ptolemy.eecs.berkeley.edu/). It brings the most powerful features of OO design (encapsulation, polymorphism) into an engineering modeling environment. Applications? Signal processing, simulation of hybrid electronic and mechanical systems, embedded control, etc. Also the basis for many electronic CAD tools.
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.
What about games? Without object-oriented programming, IMHO FPS game programming would never have come to being. What did OOP do for you, you ask? It made such wonders as Doom, Quake and Unreal Tournament. I'll give a few examples, but since I'm only an aspiring amateur game programmer, no flames for my ignorance plz.
The concept of OOP objects comes to life in highly visual games:
You have monsters that maintain certain attributes: when you shoot different monsters in certain ways with certain guns they fall down or gib in varying ways according to the monster's size and whether its guts are green on red. Each of these monsters is an object.
Each weapon has its own attributes to keep track of: ammo, range, accuracy, etc. Each of these weapons is an object.
A grenade flies through the air a certain way only if gravity is such a level and it bounces 5 times. That grenade is an object.
And so on.
When a team is writing a game, or any program for that matter, communication becomes very complex. If a scripting language is used, it's much more difficult to keep track of variables and subroutines than with OOP because with OOP you can say, "Ok, all you need to know is that if you create a new object of my class, this is what goes in and this is what comes out." This "solid state" style has greatly streamlined software development and has allowed developers to more easily reach goals and set assignments for themselves.
There's an intriguing book called bject-Oriented Implementation of Numerical Methods: An Introduction with Java & Smalltalk which might give some pointers. I haven't read it (just browsed it in a bookstore), so I can't give a personal recommendation one way or the other. It does seem rather intended to address just your question, though.
Don't listen to the guys saying engineering problems are best solved with procedural programming. That's a ludicrous generality.
Both methods (and basically all programming paradigms) can be used to solve your problem. Which you choose depends on factors other than just "which will work". Readability, reuse, maintainability, performance, and ease of design are some of the issues you'll have to weigh do decide whether to use OO or procedural. In my opinion, OO programming beats procedural in all these matters except performance (but C++ ain't too bad, right?).
My company does a great deal of mission-critical engineering software development (satellite command and control, for example), and we approach every large project with OO design and implementation. We find it insturmental in managing complex systems.
If you ever have to show your code to someone else, they'll thank you for having partitioned your project into smaller entities each with their own responsibilites and personalities. This modeling concept is much easier to follow than procedural's interweaving threads of execution.
To illustrate clear lack of understanding for both engineering and OOP in the title commands my certain respect. That is the stupidest slashdot posting I have ever seen. For fuck's sake, any language can do anything but some do it with less pain.
Plenty of people use OOP every day to solve all different kinds of problems, end of story. This same discussion happens at least once a month on Slashdot.
Please stop posting these kinds of questions, because it just baits everyone into another useless OOP war.
class MySystem : public AbstractSystem { ...
}
MySystem MEKReactor;
MEKReactor.Init(...);
PDESolver MySolution(MEKReactor);
MySolution.InitBoundaryCond(...);
MySolution.Solve();
MEKReactor.Dump();
It was a student project, and all OOP crept in was just to add a little fun to a utterly boring reactor design (not to mention impressing friends) and it was very limited. I doubt anything like it might be used for a real application, since you will have a performance hit. But some coder (which I am not) under directions of a real programmer (which I am not either) and an engineer can build something like it both flexible and high performance. The problem is, as long as most engineers know and use fortran exclusively, such a thing would be of little use.
A CFD Framework in C++
A Multiphysics Simulation Framework in C++
and many more. I have more to say but I must leave for work to get back to hacking my own OOP engineering code.
Flat5
(sorry if this sounds like I'm talking down to you -- I don't mean to, I'm just giving the same shpiel I give to my students when they want to know generally about what OO is about)
Object Orientation is really great when you want a complex system of different components working together, and you need to design the entire thing from scratch. Also, knowing OO is great when you have to repair or upgrade a system that's already OO.
At the risk of sounding arrogant, from a systems design point of view, there's little these days that's as complicated as your high-end software application, which is the purview of OO. Some systems try to do this without OO (or quasi-OO, like Gnome with C), and it often ends up looking muddled.
But just because your proposed system has a lot of components doesn't mean it's a good candidate for OO. What you need to do is start thinking in terms of the complexity of the individual components themselves. Do each of these components keep track of lots of state variables? Do the components have lots of different ways of accessing them? Do some of the components share a common design parentage? Do you want to keep some component information hidden? Do they need to communicate with each other using a unique protocol? Do you think you might want to reuse these components in other applications? If you can see that this might be the case, you might have a candidate for OO.
There's also something that a prof told me once -- that 97% of all C++ programs aren't OO. I don't know how valid the stat is, but it highlights the problem that an OO language doesn't necessarily translate to an OO setup, so seeking out an OO system to look at isn't necessarily as simple as finding some C++ source code.
For the problems that you've outlined, you're talking about pretty simple math, and by "simple" I mean, can probably be solved using a few lines of code, a few recursive functions, a couple of complex data structures, etc. This stuff can be solved in any number of high-end languages -- at worst, you might want to learn C. If, on the other hand, you want to develop a software application around these calculations, to streamline the input and output of data, you might potentially have something that can take advantage of what OO is all about. For instance you might have objects that have private attributes for the different operators and public methods for doing the calculations or redirecting the results to a database or graphing suite, etc. You might also have an abstract base class so that all the objects have the same feel to them, even though they do different calculations...
-------------------------------------------------
charlton heston is more of a man than yo
My old CS instructor said that OO would help make design and implementation easier and cheaper, when it was appropriate. And for a large part, that possibility exists.
However, as MS repeatedly proves, OO is useless when it comes to actually doing this... GIGO code is now simply encapsulated and inherited.
help me i've cloned myself and can't remember which one I am
Not only OO, but also managed code will solve issues in software engineering.
----- Whats wrong with this picture? http://www.revoh.org:1234/whatswrong
Here at the CPSE at Imperial College, London, I use a set of C++ class libraries called ooMILP (Tsiakis/Pantelides). They basically provide an OO wrapper between the integer/linear program solver (eg CPLEX) and your code. I find them really useful for my PhD work in process scheduling.
OO is a way of organizing code.
There are 3 basic axioms with any programming: i) coupling - clearly defined and small interfaces, ii) cohesion - related things (code/data) stay together and iii) localization - changes to the program should not propagate out of control.
These principles/axioms are true for any programming OO or otherwise
OO is a good way to achieve these goals.
It is difficult to build a system with low coupling, high cohesion and perfect localization of changes since it not only requires an understanding of the problem but also of the tools used to solve the problem.
Again, OO is a great tool to achieve these goals, if you know how.
Pushbutton switches can be on or off, lights likewise (same class, sanity checks to ensure you don't read a light or turn on a pushbutton).
Remember, you are dealing with real world objects which have attributes. Look at them from that perspective, and see how you can model them in software.
Best Slashdot Co
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.
There are many instances where C++ can actually produce faster code.
For a simple example, compare the C qsort with a C++ template Quicksort function. In the C++ version, the comparison operator would likely be compiled inline to the function, meaning that you don't get the overhead of a function call for every comparison. In C the only way you could do this would to be to write quicksort yourself for every data type that needs it. C++ templates allow a lot of work to be done at compile time, rather than at runtime.
Check out http://www.oonumerics.org/blitz/ for fast C++ scientific applications.
cheers,
Tim
As well as inter-process communication.
If you want to take advantage of SMP, etc., OOP to me seems like a natural fit.
Let me also underscore the point that it manages your code better.
To, me the question would be, "Why should I use FORTRAN that my old professor so dearly loves."
You must put alot of initial design in a OOP to make it re-usable. Start with making functions more universal. Where there's a will there's a way. It's just going to take more time initially to code a reusable program than one just designed to solve one particular task.
"Times may change, but standards must remain the same." - George Carlin.
In my final year of Comp. Eng., I hooked up with some Comp. Sci buds of mine in a senior thesis course. Ultimately I didn't take the course, but I still had a hand in the project, and laid the ground work for it (I had some summer jobs working with PLCs - programmable logic controllers).
[long background, but there is a point to this:]Anyways.... In traditional software development, the general process is design, code, then test, test and more test. In automation, the rule seemed to be (at least it was where I worked) spec --> code ladder logic --> install. Test? Not really.... testing [on the plant floor!] was limited to turn it on and cross your fingers. If it doesn't work, run around the floor resetting drives and e-stop buttons, hack the PLC code to cover unforseen scenarios that the original logic writer didn't think of (who would have thought that the guys on the line would have tried to do...?). Ugh. Wrong on so many levels. Expensive, time consuming.
But what if you could simulate the plant floor off-site? Test your ladder logic before hooking up the PLCs to the equipment? True, PLC ladder logic simulators exist, but these really only verify that your code is syntactically correct.. not that it does what the spec says it should. They just run the ladder logic you wrote outside of an actual PLC. But what happens when an e-stop is pressed, and THEN a drive faults? etc. Does your ladder logic consider this?
So what we did is propose that you could model things you'd find on a plant floor with C++ objects. For our demonstration, we modelled a really basic and trivial setup. We had a few lights, a few emergency stop and start push buttons and a cheap simulation of an AC drive. Each object lived in its little process... it wasn't truly *realtime* per se, but it was close enough for demonstration purposes. The point of the exercise was that we were able to send the simulator dozens of scripted test scenarios like:
[time] [object] [action]
00:10 start_pb PUSH ON
00:30 ac_drive SIMULATE CURRENT FAULT
00:45 ac_drive VERIFY SHUTDOWN
for example... check that your PLC logic to see that it monitors correctly for a fault... the last line would check the drive object to see that it got a shutdown signal (from the PLC)
The second part of the project (which we didn't get to) was to actually build an interface through a multi-channel I/O board so the simulated objects could talk directly to the I/O on a real PLC using +/-12V, 24V analog and 5V TTL digital signals.
But the idea was that equipment manufacturers could write simulation objects for their real devices. Installing a new AB drive on the line? Test out your PLC5 code before hand... go download the sim object from allenbradley.com, and throw your test plan into the simulator. Could find out that the new drive uses a different range for output speed, and you have to rework some conversion in your ladder logic. A new sensor has faster response time so you have to adjust a PID loop. Or whatever. All this before wasting time and money on the plant floor.
So.. ok, we never get very far with it (although my buds did get a good mark for the course) but the idea of having these objects was good. You could do something similar with procedural code of course, but you'd have to rewrite the code for every setup you wanted to test.
By nature, engineers are lazy. I say this in the context of one that is not demeaning but rather in the sense that engineers will try to solve a problem in the easiest and most economical way possible. I say so because i'm also a mechanical engineer like the poster.
solving a problem using OOP will require more initial effort than using a traditional language like FORTRAN so you see why OOP is seldom used.
Also, engineering software is not as mainstream as say a spreadsheet so that it has a very limited market thus is not very appealing to the software makers and tend to be niche markets.
Return the bells of Balangiga.
The reason for using OO was code maintainability and compartmentalization. It is generally easier to divide work up once you're able to break your application down to classes.
OO also means extendibility. With the right class hierarchy it was easy for us to add a new node to our scengraph to support a new type of data. For example, initially the app supported horizon data only, later on we added support for faults just by extending one of the base classes. OO will help you write any application if your class structure is sane.
Your pizza just the way you ought to have it.
OOP is suitable for large software packages that evolve over time. Such as a Word Processor, Inventory System, etc.
If you are writing a program to calculate the trajectory of a rocket or something, where the code probably won't change over time, then a quick procedural program is probably the best. For engineers, something like mathcad was probably designed using OOP, because it is a software package that is changed often between versions.
I want my rights back. I was actually using them when our government stole them after 9/11.
I know that NASA has used java for control of the Mars Rover and with some sensor applications. That by default is OO. I think that there are quite a few other companies taking advantage of java for engineering applications (especially in the wireless arena). For M.E. I think that simulations applications could (and likely do) take advantage of OOP.
If you following the links to CS 615 from my home page then you'll find some functional/object-oriented code to solve finite elements with various iterative solvers (conjugate cradient, multigrid, etc.) for various problem domains (symmetric elliptic problems, transport-dominated diffusion problems, parabolic problems, nonlinear elliptic obstacle problems, etc.)
The applicatations that you listed primarily deal with physical systems, so they are very well suited to OO, where an object can be used to represent some real-world thing. Molecules, machine parts, elastic elements, or magnetic domains are all things that have behavior, state and identity, so they are perfect cantidates for objects.
But, the physical simulations are also iterative, so the code will have a loop, and loops feel like procedural code. That is not a conflict -- you are allowed loops in OO code! Your simulations would likely have a loop that iterated over time, space, temperature, or energy, and for each iteration, you would examine the state of each object in the system and call some methods on them to simulate their behavior.
For instance, if you were building a solar system simulator, each planet would be an object, with properties for position in space and mass. Your loop would iterate over time and over each planet. For each planet in a time step, calculate the force on the planet due to other planets, and move the planet in response to the forces. ( More likely you would use an adaptive iterator and use another loop to do several iteration steps per planet per timestep. ) The benefit of OO here is that it makes it easy to organize your code and move simple things like F=Ma, 3d vector manipulations and your Runge-Kutta integrator out of the main algorithm. Plus, your code is easier to read, since you don't nned a lof of comments for things like planet.mass() or planet.move(vector)
OO makes physical simulations much easier because it allows you to organize the program according to the physical structure of the system, and those object remove a lot of basic code from the algorithm, so the algorithm becomes simpler and easier to work with.
I have built simulations for packet networks, simulated anealing, Ising glasses, Newtonian mechanics and finite element analysis in both OO and procedural style, and OO worked so well that I would never consider writing any of them in procedural style again.
It sounds like (to me at least) that you are asking how can I use OOD/OOP to solve a single small piece of code that's only going to be used once.
:-)
You can use OOD/OOP but frankly, you won't find any benefit. OOD/OOP is not for throw away code. Use perl and be happy.
Now, if you want to take a set of common engineering problem, and write a generic solution for them, then OOD/OOP are MUCH more useful. Especially if you have coders in different areas working on different sections of the code. (OOD/OOP seems to really favor breaking up large development project into smaller managable chucks.)
John J. Barton and Lee R. Nackman, "Scientific and Engineering C++", Addison Wesley Longman, Inc., 1994. (ISBN: 0-201-53393-6)
i believe the poster is trying to think 'out of the box'. while i hate that term, it does have some uses. in engineering we are taught methods to approach problems. these are very procedural and also very useful. the problem with this is that we tend to get stuck in a rut and are unable to see other perspectives.
i think the person who submitted the article wants some insight on how to look at engineering problems differently. by looking at problems in a different light (eg. variable transformation) you can make an untractable problem solveable, or you can simplify something that was very complex.
it could be that oop will not help this person. alot of the tools we are taught as engineers have no immediate benefit, but rather their applicability becomes obvious in the future. if you are never exposed to these tools then you might not be able to solve the problems when they present themselves.
-- john
No matter how many OO books or code you read, adapting those to your specific need is never straightforward (I guess that's what engineering is all about) don't mention if the kind of problems you are trying to solve are rather procedural as opposed to the more classic OO examples, usually based on modeling interactions between objects in the real world.
You have to come up with your own ways to apply OO to hide complexity and increase reusability, in fact some of those solutions are so devishly clever the got a name of their own: design patterns. Some research into patterns is likely to give you ideas on how to scratch your own itch.
Carlos J. Hernandez
If you following the links to CS 615 from my home page then you'll find some functional/object-oriented code to solve finite elements with various iterative solvers (conjugate cradient, multigrid, etc.) for various problem domains (symmetric elliptic problems, transport-dominated diffusion problems, parabolic problems, nonlinear elliptic obstacle problems, etc.) .
You wouldn't find this type of code in books you will have to read the source.
"This is a test of cross-platform 'curly quotes.' Can you Unix users out there see curly quotes?"
If you are just trying to solve an equation or have a program do one thing it is necessary to use OOP to get this done. Although OOP is more of a concept then anything. It's a way to look at the world. Dividing everything into the smallest possible bit it can and then stacking all your objects together to create a specilized thing.....like nature does with us.
OOP is intended for larger applications and not necessarilly just for programs that only require a function or so.
But, let's say you are an architect and are designing buildings. It would be nice to have a heiarchy of objects similar to the tools used to build a house and then be able to use you electronic tools to simulate real tools. This way you have a collection of tools that you can "pick up" and use at will without worrying why they work.
Also, since when is C++ OO? At least a good OOP language. Sure, I guess I was fooled into thinking it was in my programming courses but if you want a *real* OO language that works how OOP should try Small Talk, and if you want to stay in the C world try Objective C, the best OO C. Just because you have to subclass like mad doesn't make it OO. =)
"Allez Cusine!"
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.
www.eFax.com are spammers
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
Many engineering programs use a combination of languages. For example, C++ is used for the high level programming and FORTRAN for low level the numeric kernels. Of course, you can write low level numeric kernels in C++ because it supports both OO and procedural programming. Often FORTRAN is used because
My present employer, the Center for Applied Scientific Computing, has Overture and SAMRAI written in C++.
Just look at the speech synthesis project at sun.
You can make your design to have plugable algorithms with OO design by applying the Strategy design pattern.
This line:
"If you are just trying to solve an equation or have a program do one thing it is necessary to use OOP to get this done."
should read like this:
"If you are just trying to solve an equation or have a program do one thing it is NOT necessary to use OOP to get this done."
Thanx.
"Allez Cusine!"
Diffpack from Numerical objects: http://www.nobjects.com/
I'm sure that OOP is useful in modelling, but more detail would be nice. Most people don't realise that the engineering problems solved on supercomputers are usually approximations, and increasing efficiency or available resources can improve those approximations. Even a mundane problem like the temperature distribution of someone jogging in wet trousers on a humid sunny day would need serious computing power, and there are a lot of problems more complex than that which can give useful results.
OOP is mainly useful for the design of large systems. Unless your language is being overly intrusive, there won't be anything OO inside the solution of an engineering problem like the ones you describe.
The way OOP would apply to your problems would be when you're looking at the problem from more of a distance. You might have a situation in which some code wants the solution to a problem; the problem is specified by some other code, and it is solved by some other code, but there is a chunk in between that is doing something with the two parts (e.g., graphing them or something). You could make a "problem" interface, with a "solve" method, and various methods for getting information about the data. Then the intermediate code doesn't need to know what procedure to call to get the solution, because the problem object knows that.
As for things like "solve a differential equation" or "solve a set of linear equations", OOP means that you're writing a big method instead of a big procedure. It's not a big deal. The real jump is switching to a functional language, where you write your code without side effects, and the compiler can do optimizations which change when code gets run and do not run the same code with the same data more than once.
I am using OO for an engineering problem (delphi). The core is just a bunch of functions. But the material-models are seperate objects and interchangeable.
I'm sure plenty of people use C++ to kick butt, but I personally never appreciated OOP until I used it in more high level languages.
For something that's much more OOey, and easy to learn, try Python. I don't see any reason for new applications to be written solely in C++ nowadays. And the speed issue is irrelevant since you can rewrite portions of code in C (and quite easily, I was pleased to find).
Actually I work for a company that has a mix of PL/1, FORTRAN, VB, C, C++ and probably a few other things that are used to solve engineering problems.
I have been working on the same project for eight years now and it was written in C++ from day one.
The original engineering routines where written in PL/1 sometime in the 1980's. They involve an iterative solution for minimizing the end-user's cost and while maintaining at least minumum profit level to our business. The computations are very complex based upon what can be sourced by each of our manufacturing plants, optimizing material usage, minimizing freight costs and many other things. All of this is while meeting the design characteristics specified by the user and staying within all of the pertinent regulations.
Initially the PL/1 was ported to C and involved a lot of straight table lookups. C++ was primarily used to encode the business rules and UI. There is a very complex set of rules as to what can be used in various situations and the user has great flexability in what they can request. As an example we may have three different products that can fill the same role for a particular component of a project, but due to certian engineering constraints only one may be available in that situation. If the user really wants to use one of the unavailable products then the software must direct them to how to make it available. This would not always be clear or obvious to the user. Each part of the product line has their own rules, requirements and costs. All of this is handled very nicely through class hierarchies and the polymorphism of C++. A well designed C++ architecture allows us to query our model for why a product is unavailable. Imagine clicking on a disabled control or menu in a MS Windows application and being told why it is unavailable and what your options are to make it available. That is just a part of what our software does.
Now you are probably saying, but your engineering is still done in the ported functional PL/1 code. This is not entirely true. Over the years much of it has been replaced with OO C++ which has allowed us to offer a much wider choice of products and solutions to the end-user. Without the C++ infrastructure I would not want to try to fit new regulatory requirements or design methods into the software. But the way it is designed, doing this is simple. We have changed various components of the design engine over the years with very little impact to the overall software architecture.
Our application has a very complex (from the programming standpoint) user interface, but it is very simple for the end user to sit down with, even if they only use it a couple times a year. The C++ UI and interface to the business rules and engineering components is very clean, provides an abnormally high level of feedback and information to the user including but not limited to drawings, reports, and renderings.
It is worth mentioning that due to the OO nature of our model the same code is used for engineering drawings and for presenting an interactive 3D model on the screen. Once a programmer codes how something should be drawn, it may be presented in ways they never anticipated. The interactive 3D modelling was added six years into the project without having to make changes to the drawing routines for the various products and parts.
Given the complexity of the software an iterative approach is the only one that is feasible for handling the engineering of out projects, but it benefits greatly from the OO design of the application. It does not have to know specifically which product is being used for a certain component, nor does it have to know what that products constraints or requirements are, it just asks the product for the information that it needs given certain criteria.
I hope this makes some sense without explaining exactly what the software is or does. I wish I could go into specific examples and details but my employer would have a cow. I will try to review this posting and see what other responses crop up.
nice examples of the LISP OOP used in engineering are just a hyperlink away :)
alternatively you could give a random website a hit just by clicking here... it would really make their day
I haven't looked at NAG, but you're not getting all the source code? Actually, I find it weird that one does rely on closed source in science, when science depends on the full disclosure of all relevant material. Well, the computations done is arguably the most important aspect of most analysis done today, so all source code should be available for public scrutiny.
I would recommend R for many applications. It has some lightweight OO that is very efficient, it's a really beautiful language. It is also very rigorous, you will find the best things in Numerical Recipes there, but there is also a lot of code that has been through formal peer review.
Employee of Inrupt, Project Release Manager and Community Manager for Solid
In engineering applications, I have found the principles of OOP to be most useful when my problem is not simply to solve a problem in modelling something, but in creating a system.
Let me give a simple example. You have a vessel containing some liquid. This liquid must be maintained at a specific temperature and a there is a certain level. At the same time you have to allow for some liquid to be removed and new liquid to replenish it. This liquid must be removed at certain times, controlled by a certain algorithm, and replenished at other times. As well, the level of the liquid in the vessel must only be allowed to be now lower than (say) half full and no higher then (say) 75% full.
You have guages and valves to control and monitor. As well you also want to be able to display what's going on in your system and have certain control over it (like overriding the low/high levels or the times that liquid is added and removed) as needed.
This, in other words, is a control system. In my experience, control systems make ideal applications to be considered as OOP candidates.
Naturally, this is a simple example, and in so-called real-life applications, the requirements are usually more complex. My experience tells me that the more complex a control problem, the easier it is to solve it using the OOP model.
There are commercial packages you can buy that allow you to build control systems using OOPs and to be able to programme guages and set alarms points and what not.
But all you were looking for was an example of an engineering app that are suited to OOP.
True, most engineering problems are solved with procedural code. But this is not necessarily because procedural code is the best tool for the job. At the University attended, the CS programmers were taught OO, and those with an engineering major were taught no more and no less than how to write procedural spaghetti code. But just because the majority of engineering classes teach procedural code doesn't mean that it's the best practice. - objects are great for maintaining/encapsulating state. - as problems get larger and more complex, they are much more easily solved/maintained using a basis of simple objects. "Complex systems that work are invariably built on simple systems that work" (paraphrasing Booch). - true, you can write lots of simple procedures, but they will almost always be more complex than they have to be because of lack of inheritance, encapsulation, etc. Of course, I know lots of people who write objects that are really nothing more than a bunch of spaghetti-code procedures packed in a class. But once you learn to do it right, there are very few problems that are better solved procedurally.
The visualization toolkit (VTK) (www.kitware.com) is a technical visualization tool with bindings to C++, tcl and Python. It is completely object oriented and modeled on a dataflow structure. You may well find it indispensable to visualize your results. VTK also provides an excellent model of how enginering data structures may be represented in a purely OO form. My personal experience in OO programming is primarily Python based with a strong emphasis on the use of mathematical operators to define objects and classes.
A lot of people seem to be forgetting that objects can be used to represent algorithms or protocols instead of GUI widgets or physical things, and that subclassing still applies. It's very easy to imagine, for example, a MonteCarlo class or a FiniteElement class with virtual methods for the equations to be applied to each element/unit/whatever. It's much cleaner and more maintainable than explicit dispatch tables and function pointers, and never even mind the cut-and-paste approaches that many scientific code is still based on. Various notational conveniences such as function overloading and default arguments could also be useful.
Sure, the OOP literature tends to give different sorts of examples, but the basic tools are still useful if you just allow yourself to think in terms of relationships between algorithms instead of between actual objects.
Slashdot - News for Herds. Stuff that Splatters.
The short answer to your question is yes, OO techniques can be used to build better engineering (i.e. numeric) codes.
The longer answer is that applying OO techniques have been adopted very slowly by the numeric computing community because there are some difficult problems in marrying the two that are still being actively researched.
A very good resource for OO numerical computing is here
just stop doing mechanical engineering problems. :)
BAM! problem solved
IMHO the value of OOP techniques is mostly for the management of complexity. In my experience these techniques are most useful when complexity arises from
:)
a) the problem domain for which you are writing software
b) the process of software development and *maintenance*
Loosely defined the problem domain is the environment into which your software will be deployed. The users of your software may be mechanical engineers, bank tellers, etc. They understand the elements of their environment quite well and frequently do not understand computer systems. OO design and programming techniques facilitate embedding the translation between these concepts into the software (as opposed to training the users of the system to do so).
Two (related) exaples of engineering applications that benefit from OO techniques are computer aided design (CAD) and process simulation. OO techniques make is easier to create classes that represent the various elements of a chemical plant and proposed VLSI design and can evaluate interraction using different modeling techniques like those from the original example. I'm not claiming that one couldn't develop either type of system without OO techniques, they just make it easier.
The process of software development can create its own complexity depending on the size of the project and resulting size of the development/deployment team. OO techniques facilitate the division of labor required to distribute a large amount of work over the members of a large team. In addition, by grouping code into segements that have similar rates of change maintenance effort can be reduced reletive to monolithic, procedural coding efforts.
As someone has already stated the use of OO techniques is not limited to OOP languages. I'd argue that most of the value of the features added by these languages (reletive to their procedural ancestors) existed in techniques that predate them. Mostly these newer languages (C++, Java, et al) provide more efficient syntax and better enforcement for these techniques.
In the end, however, if you a creating a few simple tools for your own use I think you should develop your software in whatever environment is comfortable. Also, these OO techniques do have a performance cost. Of course, software tends to last a whole lot longer than the original developers think (remember Y2K
Ciao,
Maui
Number crunching and productivity apps are in two different worlds. The latter benefits greatly from OO because OO encourages consistent interfaces and code-reuse. The former often has no use for it. In some cases, where you are using things like matrix algebra libraries or any number of other tools, it may be of great benefit to use an OO language, just because the tool set benefits from being written in an OO language. But when you want to throw together a one-time use program which does a bunch of number crunching and where you're pretty much writing all of the code yourself, then it's better to use a procedural language which cuts away all of the OO wrappings and lets you get down to business. Furthermore, FORTRAN has been around SO LONG that it's hard to find a C compiler which can optimize as well. FORTRAN has always been used for heavy number-crunching, and as a result, its compilers have been optimized almost exclusively for that purpose.
I don't have any experience programming engineering problems period, much less doing it in C++. I read somewhere that strictly numerical problems don't translate very well into OO terms, so you might just be trying to apply a design technique that doesn't fit. On the other hand, it seems some people are programming engineering probolems using OO and publishing books about it. I went to the Barnes & Noble website and searched the book section with the keywords "numerical C++" and turned up half a dozen titles. Numerical Recipes in C++. There were links at the bottom of the web page that even looked more interesting, like C++ and Object Oriented Numeric Computing for Scientists and Engineers. Good luck!
from <a href="http://www.python.org/psa/Users.html">pyt hon.org</a>
<blockquote>
Johnson Space Center uses Python in its Integrated Planning System as the standard scripting language. Efforts are underway to develop a modular collection of tools for assisting shuttle pre-mission planning and to replace older tools written in PERL and shell dialects. Python will also be installed in the new Mission Control Center to perform auxiliary processing integrated with a user interface shell. Ongoing developments include an automated grammar based system whereby C++ libraries may be interfaced directly to Python via compiler techniques. This technology can be extended to other languages in the future.
</blockquote>
C's style is procedural or imperative.
The terms are confusing, but functional implies more than just functions.
Other examples of languages that _can_ be used in a functional style are Perl, Python, and Ruby.
Because there is no engineering problem that can only be solved by OO programming. In my experience though, OO programming allows for much faster development and easier maintenance. As an example, I recently started a new job, and there, using C++, was able to do in a matter of weeks what the company had been trying to do for many months. The code is much cleaner than it would have been using a C-only approach. Unfortunately many people look at OO and/or C++ either as a solution that they want to use (for no apparent reason, they just want to use it), or as something that should be avoided because it is perceived as slow or bloated. Both viewpoints are incorrect. C++ is neither slow nor is it a tool that you *must* use because it is "better". It is simply a tool, and as with any tool, you should only use it when you a) know how to use it and b) it is suitable for the job at hand.
Now the real question is "should you?" Probably not if you're doing scientific calculations. You're better off optimizing the code and writing detailed documentation than generalizing the structure. Like others have said, "OO is a tool." That's all it is, nothing more, nothing less. Try to think of it as building a house or an office building.
There are reasons why office buildings have large open spaces with cubicles. This allow reconfiguration of the furniture to fit each renter's needs. For the same reasons you wouldn't try to cram 50 person company into a 4 bedroom house, you shouldn't force OOP principles on a problem that doesn't call for it.
From your post, it sounds like you're interested in OOP, so maybe the question really is "should you get a new job that gives you an opportunity to find out first hand what OOP can do for you?"
What is OOP? Its a way of abstracting a problem in to something simpler that is easier to work with.
What is mathematics? Its a way of abstracting a problem into something simpler that is easier to work with.
Rather than work with the actual quantities of things in question, we can abstract them to numbers. Rather than work with actual processes and physical things, we can work with mathematical representations of these things, equations and procedures.
This is very similar to what oop does. Rather than work with piles of unabstracted data, we work with abstracted data in the form of objects.
But if the problem you are trying to solve has already been abstracted after years of work in to a nice set of equations and processes, whats the benefit to abstracting it further? The math is already an abstraction, and a good one at that.
So in this type of problem, the most natural abstraction is already there, the math, and can be used directly in a non oop way. adding an unnatural layer of abstration overtop of that one will likely just make things more work.
Thats not to say that the overall structure of the program cant be improved by the abstraction and orginization that OOP can bring to the table, but the actual calculations, the math, is already a huge level of abstraction over the real entity anyway. Why add more to it?
What about mathematica? I swear that bad boy can solve any problem...
I have always thought of OOP as fundamentally a procedural programming technique but extended to give you better ability to organise and manage larger projects. C++ is a superset of C - you don't have to use the OOP features but they can help you enormously in the right situation.
:-). In this case, all the code that used the object would remain the same, possibly saving you a load of work.
OOP also encourages good programming practices like producing well-defined interfaces, implementation hiding and code re-use. I actually think these are crucial to the effectiveness of OOP. These are all good things, and I'm sufficienctly lazy that I would never write anything other than a trivial program in purely procedural style.
However, OOP is still best suited to particular domains. Modelling, GUIs, enterprise applications, games etc. are perfect because they all require the manipulation of discrete and readily identifiable "objects" that map onto the OOP model very well.
If you're writing network drivers, you could use OOP, but as other posters have been keen to point out the (very small) overhead of most OOP languages actually becomes a problem for very low-level code. Hence OOP isn't so well suited for OS kernel code, network protocols, hand optimised inner loops and embedded applications.
The difference between procedural and OOP is mainly a trade-off between low level control of the machine and having a semi-automated system to manage the complexity for you. Interestingly, for larger projects, good programmers in procedural langauages often end up having lots of function calls that take the "object to be acted on" as an argument and are therefore effecively emulating method calls. Once they start putting in switch statements in those functions to branch on the type of object encountered, they have effectively emulated virtual methods.
Your case is an interesting one. You are dealing with mathematical/engineering problems that are often tackled in a procedural style.
If you're feeling adventurous, I would actually suggest you head off to look at functional langauges. Reason is that these langauges are ideally suited for representing functions and other mathematical constructs, just as OOP is geared towards representing and manipulating "objects". Haskell would be my no.1 choice if you're looking for elegance and flexibility, O'Caml if you are more concerened about raw performance.
If these seem too radical a departure, then I still think that OOP could make sense for a major project. You probably wouldn't need inheritance, but implementation hiding can be very useful. Let's say you're modelling fluid dynamics, and do it procedural style with a big array. Works fine until you decide that in fact you want to store the data in an octree so that you can get a couple of orders of magnitude better resultion in the particular areas you are interested in. At that point you have to change everything that accesses the data structure, including the 100 or so simulation programs you've been developing. Not fun. If OTOH you had encapsulated it all in an object, you would just change the object's private implementation, keeping all accessor methods the same (e.g. getFluidVelocity(x,y,z), getPressure(x,y,z) or whatever, I'm not an engineer
It's also often useful to have data represented as objects just so you can do useful things like pass the around, build larger data structures etc. Not that you can't do this in procedural style, but OOP takes away all the pain. I've lost track of the number of times I have taken advantage of all the useful features like object serialization in Java, which saves you all the hassle of having to write import/export functions to store your data structures on disk.
Ultimately, use what seems right for your application. But remember that OOP and other techniques such as functional programming aren't just fads, they are ways to solve problems that procedural style just isn't well suited for. If you find yourself spending too much time writing the "glue" to hold a big application together, then it's a good sign that you've actually picked the wrong tool.
A 4/5 years ago I took an open university corse on software design and the like... (computing and object oriantated approach).
The main content of the corse was small talk.
I remember a video for the corse where someone was using a OO CAD application for designing buildings, each object not only new about it's cost etc.. but health and saftey regulations, construction time.
The whole thing ended up in detailed construction and deconstruction plans for the building, all the health and saftey documentation.
I can't remember what the application was called, but it seemed very good, especially for 4/5 years ago.
_technology_or_methodology_ is not a silver bullet. It will not magically turn bad managers into good managers, or poor programmers into competent programmers. It will not stop balding. It will not improve my sex life. I cannot solve the halting problem in polynomial time using _technology_or_methodology_.
What _technology_or_methodology_ is, is a useful tool for certain problems, and I will use it as appropriate to improve my communications with other human beings, which is what programming is really about. I will not dogmatically use _technology_or_methodology_, and I will keep an open mind to new ways of expressing myself and solving problems.
I'm proud of my Northern Tibetian Heritage
We use object oriented technology (C++) specifically for its constructs that allow a better large-scale, long-term project development cycle. Ideally, it lets us develop software by addition and subtracting code modules instead of modifying existing ones.
Work as if you might live forever, Live as if you might die tomorrow.
'scuse me, but are you interested in OOP, or OOD?
These are completely separate topics. You can design a program using the OOD approach, and not write it in an OO language, and you can write an OOP in C++ but not use any OOD.
So which is it?
Assuming it's OOD, you can use this technique in engineering problems to solve things like concurrency or identify interactions between/properties of "objects" or systems that would be too difficult to identify if another approach was used. However, like any tool, it will only be as useful as the application of it will allow; hammers and screwdrivers come to mind. If you're looking into things like RTS (real time systems) OOD may have its uses but nothing beats a good circuit diagram for clarity.
Assuming its OOP, what are you trying to acheive? Obviously, you will have to use OOD to design your system (one would hope so, anyway) but what is your system trying to acheive? Its no good trying to force a screw in where a pin would do. OOP allows reuse of code, clarity of code, and happens to be useful for organising your program as well. However, if you only have 2k of memory, whats the point?
You need to think about your application before you commit to a design/programming methodology. Sure, OOD and OOP don't always fit the bill, and they may not be right for you. But thats why you have to do an analysis of the system, perhaps applying OOD to it, and if you fail, try some other approach. After a while it comes with experience.
"So there he is, risen from the dead. Like that fella, E. T." - Father Ted Crilly
There's also inertia in the teaching world. What percentage of the Mech. E. professors were arround before OOP was widely accepted? How many of them have gone back and learned to do OOP properly? If the profs and masters of industry haven't learned OOP, then the advanced codes will be in C/F77. You go to learn about the advanced coding, and you end up learning how to do all of the advanced stuff in functional languages.
For the beginning student, the fastest way to learn to code up some problem is C or Java with only one object. Once a student is proficient in one language, most of them will push as far and fast as they can in their subject matter instead of learning to code better or learning a new language.
OOP is mainly necessary as a tool to clean up large programming projects to make them manageable and to help keep you from hurting yourself through disorganization. OOP really shines when you're doing a lot of dynamic allocation and freeing of data, as destructor methods are a big help in preventing memory leaks. The really big Mech. E. codes (FEA) are gigantic matrix inversions. (There are some other methods, but FEA is by far dominant.) There are plenty of C and F77/F90 libraries out there to handle the messiness of matrix manipulation for the coder. And, truth be told, matrix manipulation is not messy at all by comparison. You have a large ammount of memory allocation at the beginning of the executable, but then you just manipulate the data you have for a while, save your results, and exit, perhapse without even free()ing your matricies.
On the extreme end, some people may not want to take the small performance hit in going from C to C++. For compuationally intensive tasks, I believe you still take a 10x hit going from C/C++ to Java. The MIT 6.270 Lego robotics contest still gets won by teams that use purely mechanical methods of steering (the winner ~3 years ago) or use a single java object and do functional programming inside that object. The boards are still a bit too underpowered to pull a full JVM on top of NetBSD and not care about the various OOP overheads. Some teams use huge switch statements to virtually illiminate method calls. For small projects, this can be done without sacrificing too much robustness, and the performance gains are noticable.
Copyright Violation:"theft, piracy"::Anti-Trust Violation:"thermonuclear price terrorism"<-Overly dramatic language.
Problems of the type you descripe wouldn't benefit much from OOP. I'd solve them myself in C, but that's mainly just because I don't *know* Fortran (fortran is very good at math problems with straightforward methods of solution, and parallelizes easily).
My most recent project, on the other hand, involved simulating a computer system (I won't go into detail; wait until after I've published). This is a perfect scenario for OO - a computer system is built up out of many parts, many with similarities, but with different implementations. If you need a cycle-by-cycle or event-by-event simulation of a computer system, it makes sense to build up models of all of the parts that will be interacting and put them into an OO hierarchy. This lets you avoid copying code, and lets you change things much more easily than in a straight C environment.
In a previous project, I was building the skeleton for a program that would have to be rewritten for many different purposes. Some parts would stay the same between instances, and these were what I was building. I made the mistake of writing it in C, with the idea of upgrading it to C++ later. I ended up faking OO-isms by calling function pointers hither and yon to abstract things. When maintenance of the project was finally turned over to someone else, they started the migration to C++.
In a complex program where you have a lot of abstraction going on between different types of component, an explicitly OO language will almost always make life much easier.
This guy has described OO in as clear and
accurate language as I've ever heard.
Moderators, do what you must do.
*sigh* back to work...
Engineering solutions via GUI
The reason why I learned OOP is pretty much that I had to. I'm at the University of Oslo in Norway, and OOP was invented here and implemented in SIMULA. So they really forced us to use SIMULA and program OO, but in just a couple of basic courses, so I didn't a prolonged forced exposure.
Examples where OO concepts are clear include SIMULA and the S system (my favorite implementation R). SIMULA is a full-blown OOP system (but there are various reasons why it failed), while S has just a few OO features, but the features that have been implemented are easy to understand, they incorporate some essential concepts, and they are very powerful.
Then, you have C++ which is also a full featured language, but where the concepts are not that clear and easy to grasp.
When OO gets muddy is usually when it is built on the top of existing languages. Perl OO is a bit muddy, but not too bad, but if you look at e.g. IDL it gets rather bad IMHO.
Employee of Inrupt, Project Release Manager and Community Manager for Solid
I started out in C, but converted to C++ when it became clear there would be a serious advantage for that particular code.
Looking at the header file, I see that I ended up with a class SampleInfo that contained basic info like the sampling rate and a dozen other items of interest. This basic type was useful as a parameter to constructors and converters throughout the package.
Then there was a class HeaderInfo, which inherited from SampleInfo. It added information such as whether the data was a stream of bytes, complex numbers, or in phase-magnitude form.
Using that starting point, several other classes inherited from HeaderInfo to add still more specialization: VectorHeaderInfo (information about an array of arrays of samples) plus associated implementation classes: ByteVector (just an array of samples of type byte), ComplexVector, ComplexVectorOfVectors, etc.
The class hierarchy and associated inheritance doesn't sound especially impressive, but it immediately cleaned up the code and made it easier to experiment and easier to find certain kinds of conceptual bugs.
Actual transformations were made easy by always returning a pointer to 'this', so a typical usage would look like:
This style of pipelining data through transformation stages makes experimentation a breeze...just insert/delete pipeline stages.
Even design of core algorithms like fft() itself benefited somewhat from reimplementation in C++, although the benefit there was a little smaller.
Basically the added value of OO is small (but non-zero) if you look at converting just one function implementing a single numeric technique, but becomes larger and larger as you implement a family of related techniques, such as matrix arithmetic, multiple transforms, diff eq techniques, etc.
P.S. the biggest optimization advantage for using Fortran is on things like vector processors. And in any case, the right way to optimize is to re-code only inner loops. Thus one could have a package written mostly in C++, but with inner loops recoded in Fortran, if necessary.
Coding whole apps in Fortran is neolithic.
Professional Wild-Eyed Visionary
The information technology guys at NIST (Pozo et al.) have done a lot.
http://math.nist.gov/tnt/
The template numerical toolkit is supposed to allow one to write C++ that looks more mathematical in appearance.
e.g. X=A*M*B;
where A and B are vectors and M is a matrix.
OOP, in a broad sense, is used to abstract away the actual implementations of vectors and matrices. Since the naive and most general implementation is too slow, something like the strategy pattern is used to call the most efficient algorithm. For example, if M is huge, but upper diagonal, you can save yourself a lot of time by picking the right method. TNT does that for you depending on how you instantiated the vectors and matrices.
C++ buffs may get a kick out looking at the source. Numerical people should look at it to understand that templates, although tempting, don't solve every issue and create a lot of their own!
There is but one small difference between the two languages. Speed is not it. Granted C++ does have a small overhead. But nothing compared to the difference between other languages like java and some others... For my purposes, and yes I do use C++ and C in large scale programs that take weeks to run, I make no distinction in speed.
time is a mjow advanage in oop, you can save days for every week of work.
Been there and done it...
I wrote CAD software for five years and simulation sofware for another six and I guarantee that if you master what makes OO useful, you can shine. The main difficulty is getting this type of code past the old timers who swear that fortran is it and will be it for ever but then start using the latest OO construction that exist in fortran 90 (or who knows what the latest number is).
Using OO you can create bridges that would cause a complete redesign in a procedural language. Those bridges end up as features and that is what makes the difference! Look into the leading commercial CAD or simulation software out there, I would bet that most is OO because that is what allowed the features that people bought
You wrote:
...
...
... ignore the fact that I used a template ( angle brackets got stripped by the formatter :-( )of course ...
... read: "Design Patterns", Elements of Reuseable Design, Gamma et al., Addison Wesley, 1995.
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.
Well and what about this:
// I don't know if you use square pipes
// or round pipes
// or oval pipes
calcTotalFlowRate(Array_of_Pipe* pipe) {
double sum = 0;
for (int i=0; i leth_than pipe.length; i++) {
sum += pipe[i].calculateFlowRate();
}
You wrote:
I've also never been a big believer of the whole "code-reuse" argument.
I say:
Then write my above loop in C
For the problem you are bringing up: adding later a SurfaceArea calculation, OO is exactly THE solution.
And if you are to tired to modify all classes where a calcSurface method would be needed write a Visitor. OOPS, thats a design pattern
Regards,
angel'o'sphere
Cost free eBook I read (by iBook/Kobo/Amazon/ObookO/Gutenberg etc.): "The Green Odyssey" by Philip Jose Farmer.
OOP requires a different organizational view of the problem you're working with. I've seen a tiny few people coming out of college who appear to have been introduced to the necessary concepts in college. For old school programmers or people whose degree program was still geared toward 1970s era, there's going to be a learning curve. Moreover you can't just go off on your own and start programming in C++ or Java willy nilly. You'll just reinforce bad habits while not developing any good ones. A year in a shop with good solid programmers who are willing to mentor you would probably give you a pretty good feel for what works and what doesn't. Assuming you're willing to really study the dicipline.
One of the first things your mentors will probably tell you to do is go out and get a few books. Design Patterns, Antipatterns and Refactoring books make good introductory reading. None of these things are magic bullets either, and you should refrain from viewing them a such. If you don't have Programmer Nature, none of that stuff will help you.
After all that you'll be able to write code that should be easily maintainable and flexible for new problems. Whether or not that will actually solve the problems you want solved is another question entirely.
I'm trying to teach myself to set people on fire with my mind... Is it hot in here?
The primary advantange of Fortran is its incredible compilers. Fortran compilers can handle all sorts of optimizations automatically that can't be done by most C or C++ compilers.
On the other hand, managing complex data structures is a beast with Fortran (who wants function calls with 75 arguments? I've seen it done).
The best solution is to use OOP languages (C++ being the prime example in scientific computing) for handling the data structures, dynamic memor management, I/O, UI, etc. and use Fortran for all the inner loops where 90%+ of the execution time is spent.
All is Number -Pythagoras.
you can actually gain a lot from OOP in scientific applications. Beware: IANASC (I am not a serious coder). However, I am an econometrician (for the majority: roughly speaking, halfway between an economist and a statistician) who often does his estimations in high-level languages such as Gauss or Ox rather than using prepackaged solutions.
In the last two years I have been using Ox quite a bit, whose syntax resembles C++, and encourages the use of objects. My eperience is that performance and ease of code writing are comparable, but what really makes the difference is code maintainability: once you've got something that works, WHAM!, you wrap it into a class and forget about it. With other packages, the population of global variables and such made it a nightmare to go through code you had written months earlier and re-use it for a related task.
The first OOP system I ever used was Digitalk's Smalltalk V, a quite successful adaptation of the ur-OO language to DOS, and later to 16-bit Windows. I was impressed by its power and expressiveness -- and frustrated by the difficulty of dealing with the huge mass of new concepts. It would have been much easier if there were a clear distinction between things I needed to know in order to extend the framework, and things I needed to know in order to create applications.
Anyone interested in OOP should download one of the many Smalltalk implementations available just to play with it. But there's a limit to the serious work you can do. There are still Smalltalk developers out there, but most people just don't have the mindset.
Modern OOP systems are mainly extensions of procedural programming languages. This disgusts OOP purists, but makes for a more shallow learning curve, and helps sharpen the distinction between features for designing objects, and features for using them.
C++ is the fanciest of these. But it's extremely complex, and should be approched slowly, if at all. C++ enthusiasts never seem to tire of finding new and obscure idioms to invent.
There are lots of OOP languages out there, but I think two recommend themselves to the newbie -- especially the newbie who wants to actually makes things. There's Java, which no longer seems likely to change the world, but is still a dominant force in some applications.
And there's Object Pascal, which outsiders consider an antiquated curiousity, but which is considered a powerful and highly usable tool by its rabid fans. OP compiles very quickly, which makes it particularly useful for RAD tools.
Which brings me to the commercial: I help document the two big Object Pascal RAD tools, Delphi (Windows), and Kylix (Linux). Both are extremely accessible to the OOP newbie, while having all the power and expressiveness of a serious OOP system. And both have versions you can download for free.
Some people down the hall do a similar tool for Java. I hear its pretty good.
Yes, of course OOPLs can solve engineering problems. Does that mean you need to use it to solve engineering problems, or that it is always the best solution? No, in fact a lot of time it is unwieldy to design an object framework, and it complicates the problem. If there is a clear objectification of the problem, an OOPL would be a good choice.
Languages are just a toolbox - pick the right tool for the problem. People too often jump on the newest hyped language and think it will make everything easier and better.
At it's most primitive layer, OOP is a coding thing, a syntactic sugar as so many professors like to say. A way to keep code clean. It's quite nice in that capacity, I don't mind writing "c = a + b;" and under the covers mpz_add is getting called and adding the arbitrary precision number a to the arbitrary precision number b and storing the out put in c. This isn't true OOP, I only include it becuase it's the OOPLs that have made it popularly available.
The next level is encapsulation and reuse. It's pretty damn nice to be able to write "d = {}" in python and create a hashtable dictionary. I do that is literally dozens of python programs. I could easily produce the same thing with list primitives or vectors and what have you and I might even be able to make it better for my particular use but for the most part the dictionary object in python or any of the STL objects are insanely useful, they are easy to use, quick and they are building blocks you can use to build bigger programs. You're already using this kind of code whether you know it or now, the C library is the same thing, it doesn't have the same syntactic sugar though and the things it does are generally more simple where some of these objects are higher level components. I wouldn't call the C library object oriented, per se, but might call a component that does the job of half a dozen C library calls an object.
The final layer of OOP as I see it is modeling. Again it's not well defined outside of a few circles and even then Grady Booch and Bertrand Meyer and the other gurus spend countless hours and books bickering about it. The modeling part is how we break a problem down and implement a solution for it. This I would say is a universal area where OOP has won and will continue to. When programs reach certain sizes, the human mind can really only deal with the complexity by building heirarchies and mapping the problems to solvable isomorphs and then trying to reuse ideas as you move through the heirarchies. If you're trying to multiply a few matrices and then hit them with the Gauss stick to tell if the bridge is going to work, it's probably not a good example of a problem to model that way. A GUI on the other hand is a perfect example where you can have a very clean hierarchy of windows of different types with different functions that behave differently. In my experience, I haven't seen any large scale projects started in the last 15 years that weren't object modeled, even if they were implemented in C or some other non-OOPL, I have seen a fair amount of code from the 1960s and 1970s that was very very complex because it didn't have any real object modeling. The linux kernel has a fair amount of object modeling in it, there are abstract block devices and character devices and they can all be treated the same way, buffering is an abstract concept regardless of the device. Even functionally implemented programs have some degree of object modeling in them.
Now what kind of OOP are you looking for? If you're looking for some kind of advanced object model with reflection and a complex object hierarchy, then maybe it's not being used to solve some engineering problems, it takes a certain size problem before that kind of effort really pays off in the implementation. If you're looking for code reuse then there are numerics packages and probably tons of other packages the will do that.
OOP is just another tool. It is a tool that takes some time to master, but can greatly simplify complex software projects.
For a very simple program such as a numeric program that executes a tight loop, there is probably not much benifit. It might be more important to be compatible with some library that meets your needs. If the library was not designed with OOP in mind or was implemented in a languge that does not have strong support for OOP, then it may be more trouble than it is worth.
If the program is more complex, then if you take the time to master OOP, you might find the program is simpler and more logical. But, watch out for the trap of trying to go overboard on OPP. Many programers that are new to OOP get tangled up in trying to do it the "right" way and wind up with a program that is very complicated and slow, defeating the point.
I like to to use OOP tools like C++ and Java because I have used them so long, it is simpler for me. But, I could acomplish the same thing using K&R C.
Either way, the job gets done. Sometimes it just comes down to what you prefer.
I have been on projects that insist on OO for there engineering projects. its good for reuse within THAT project, but thats about it.
Very few people can write good OO. but even the good ones often end up with too much indirection, which can seriously hurt a "low level" program.
Each project had specific needs for that chip set, or product, so anything but the most basic needs wasn't reusable without more tweaking.
Compilers are pretty darn good these days, so thing that use to be a selling point for OO aren't anymore.
In my real world experience, there is nothing OO can give you, that good coding practices don't.
The main advantge thats bandied about these days is re-use, but That can be done with a function just as easily.
The Kruger Dunning explains most post on
I've been doing java and C++ programming. Your experience with simula holds true for them too : very rarely do language issues make much of a difference in terms of difficulty of an OO design. (although they surface occasionally) You usually face language limitations in the coding phase (because, if you're like me, you aren't smart enough to recognize them in the design phase). Or in the maintenance phase, when you realize a section of code could be much more elegant with the help of some language feature not present in the current language.
Jack Valenti and the MPAA are to technology as the Boston strangler is to the woman home alone
You can use OOP without a noticeable slowdown.
You just have to program efficiently.
(Procedural applications won't run quick either without efficient code)
Try the book:
Scientific and Engineering C++: An Introduction with Advanced Techniques and Examples. John J. Barton and Lee R. Nackman.
You see OOP is not a solution to an engineering problem- it is a solution to a people problem. It helps people to see and design solutions more efficiently. People have trouble seeing a link between the technical and the practical problem at hand. OOP helps people bridge the gap in their mind so that they can model a solution to a problem in a more understandable "natural" way. You could argue that this is a cop out.... that people should overcome the blocks in their mind between the technical and abstract to the practical, physical problem... but the truth is, people have limitations..... companies have deadlines... and not many people are intelligent enough to overcome these boundaries without significant cost.
Please help! I'm stuck inside my virtual reality headset!
Object Oriented Software Construction by Bertand Meyer - don't be put off by examples in Eiffel, this book very thoroughly runs down all the standard OO features and demonstrates/explains why the features are useful. Personally I don't know a lick of Eiffel and have no intention of ever learning it, but found it very easy to follow the examples and map them to my language of choice.
Design Patterns by Gamma et al - This book simply runs through a lot of problems and demonstrates at a nice high level how one might use OO design to solve the problems in elegant ways.
If you read these 2 books, you should 'get' OO programming, and understand where you will and will not reap benefits in using OO techniques.
You've described good OO boundaries in some ways. I've seen good OO and bad OO in the engeering field. I've seen good OO where the stats stuff was written once and everybody used it. I've seen bad OO where stats were rewritten all over the place by people of different skill levels.
Stats is just one example of several. We do control systems and have control system base classes that allow us to model the control system by breaking it up into a measurement side and a control side and treating things generically. It works very well.
As you gain a wider experience, you'll find that most systems can be modeled with a good set of abstract concepts. We've found it has helped up tremendously. For example, when we write a new control system, generally all we need to do is to write measurement and control objects for the hardware that we don't already have these objects for and then write some custom plumbing code to tie all the objects together to match the wiring of the actual system (well, more or less, but that gives the right flavor). We don't have to write PID controllers each time, or simple alignment operations or any of the more complex data filtering algorithms we use to keep the control systems stable.
Yes, I know I'm being a little vague, but to fully describe things would take more space than is appropriate for this forum. Then again, the question was kinda vague...
It just depends on how you look at it. There can be significant advantages in going OO. One is that it can simplify parallelization of the code if written correctly. Take a look at the molecular dynamics program NAMD and you will see what I mean.
http://www.WinWithRealEstate.com/
I don't think it really matters whether you're writing an engineering program, a game, or even an embedded application. It's a question of execution speed and code size versus the ability to manage the project. If you want something quick and dirty, procedural languages are the way to go. However, as the complexity and size of your code increases, the benefits of OOP (ease of debugging, high level of abstraction) far outweigh the extra development time and additional execution overhead in the compiled code.
Assuming that one agrees with the above statements (they are only theories about OOP vs. procedural languages), it should also be noted that the most expensive aspect of developing software is man-power. Thus, if a project is large, with lot's of people working on it, it becomes crucial to reduce the amount of time programmers spend communicating with each other. It follows that if OOP is easier to understand than procedural code, then you want to lower your costs by using OOP to reduce development time (because time == dollars paid to programmers). Naturally, there is an antithesis to this idea. If your project is small, with few programmers and already easy to understand, then using a procedural language will get the job done quickly, once again mimimizing programmer time.
We did this by creating classes containing only static member functions. One class worked on matrices, one on polynomials, etc...
This is basically C with some grouping of related functions.
It also allows you to do high level objects for math objects and then do C like low level computation routines.
Also gets rid of all of the C++ to C name mangling time wasters.
"maybe OOP is mostly used for its inheritance in data structure"
A lot of bad OO programmers seem to use inheritance for inheritance sake. Personally, I find OO is more than just how you express something in the language, but rather a complete way of thinking or a mind set.
OOP, when done correctly (and when you don't go overboard and forget that you're using it to make your life *easier* :-), encourages programming in a general way, and organizes things so that they are easier to morph and add to later without breaking your original sound design.
Contrary to what many OOP zealots would tell you, my experience is that this actually takes more time up front (again, if done right), rather than less. You spend a lot of time on seemingly useless activities, such as coming up with good names for your objects (if you can't name it succinctly and accurately, you haven't designed it properly).
There is one situation in which OOP can result in faster implementation, and that is when the project gets big enough that you need multiple programmers in order meet the schedule. In many ways, OOP is a reaction to "The Mythical Man Month". It's an extremely useful paradigm for splitting up tasks and defining interfaces that can be independently implemented. This is probably why people tend to think of it as only applying to large projects.
But even small projects need maintaining, upgrading, and resuing later on in life, and OOP helps tremendously with this.
I think the answer to your question is cultural. We all know many OO
weenies who have spent years improving their programming. They have
jobs, and build useful applications sometimes, but I think the thing
that really motivates these people (hey, I'm one of them), is the goal
of becoming a better programmer, and writing ever more beautiful code.
I think that folks working on engineering problems spend similar
amounts of time trying to solve the real-world problem.
From my own educational background, (undergrad, grad school, faculty
member before joining the real world), I observe that the split between
these two approaches to software occurs pretty early. People who focus on the
advanced numeric stuff spend their time on that. People who focus on
the underlying tools seem to have a better chance of becoming object
weenies.
Can OO help out with (non-software) engineering problems? I'd be
surprised if they couldn't. Personally, I don't know enough about that
set of problems to offer an opinion. I think the reason that OO isn't
used more in mechanical engineering (for example) is that there are
many more people like me who specialize in one or the other, and very
few people broad enough to have enough of an understanding of both
worlds to know how they can be combined.
While the guts of the programs were well-established FORTRAN routines (inverting huge arrays, solving difference equations and partial differential equations, just like you described), there where vast layers above that that used OO concepts to organize things like MaterialProperties, Geometries, EngineComponents, Assemblies, and other elements of the problem set. Different classes broke the simulation down into three-to-twelve simultaneous sub-simulations, distributed them accros the Unix network, ran them in parallel, and coordinated each iteration's results with the other parts of the run.
Basically, both functional programming and OOP were used where each works best: OOP provided reusable software components and levels of abstraction that allowed the engineering problem to be rapidly mapped to these components, and functional programming routines performed the well-understood mathematical processing.
As stated in a previous post, OOP is a superset of functional programming, because (in the end) each method must be coded using functional programming techniques. OOP is a way of abstracting related, underlying functions into a coherent object (or class of objects) that maps more easily to the problem domain.
Engineering problems are problems that fall under a domain of discrete solutions, which have very specific algorithms by which they are solved.
Object Oriented Design doesn't work to well with discrete solutions because, in part, the design philosophy is one of generalization.
That is why Linus for example holds to the belief that OOD principles in system level software is wasteful, for a variety of reasons. Primarily because there is no need to write the functions of a scheduler for as OS anything other than what it is.
However, that doesn't mean that all aspects of OOD, such as reuse, simplicity, and maintainability don't have anything to offer to discrete solutions. Just that OOD can't realize all the benefits a discrete solution to a problem can give you. Also, should you decide to choose an OOD for a discrete solution for an OS kernel or tracking asteroids, you have to realize hopefully through experience what the relative meager benefits are in doing so for your discrete OOD solution.
That doesn't mean you can't try though!
For example, at the moment I am writing an extension to a number of problems to track asteroids for a telescope via computer automagically.
Most of the tracking software was or is originally written in FORTRAN and is in the book "Fundamentals of Celestial Mechanics" by JMA Danby. Publisher is William-Bell by the way.
RK5 methods are highly specialized mathematical algorithms specifically tailored for N body problems in calculating or predicting orbits. They are for the most part functionally reduced to FORTRAN IV in the form of highly NON OOD function libraries.
(It is not OOD because the functions rely on a number of shared data structures which is a no no in OOD. As a result, since code is not easily isolated between data and function calls, it is VERY hard to figure out the source code by hand and very structured design oriented.)
Also, might I add, checking the answers are literally BEYOND your ability as a human being EVEN WITH a calculator! For example, an RK5 method might have over 1,000 iterations of a integration or differential mathematical procedure. There is simply no way you could check it by hand. I solve this problem by using Mathematica, from Wolfram Research. I transpose the algorithms from Fortran into Mathemtica until I get the right numbers and to make sure I understand exactly what the algorithm is doing.
I then transpose it to Java, which is the target platform and Object Design language I am using to forever banish the constant rewriting of code from computer to computer!!!
Java has been a GOD SEND to astronomy by the way in cutting costs! Especially for a society that woops and screams about cutting all scientific research while at the same time spending hundreds of millions too see Harry Potter. (How sad. I hope one of these rocks doesn't fall on your city anytime soon.)
However, lets not be decieved. For although OOD and OOP practices in generalization of programs yields better reuse, in principal, each specific method of an object is built using well known Structured Design practices.
So, with that I set out to generalize a highly specific piece of code and layer on top of it, an OOD that would attempt to turn what appears to be a highly specific set of functions in FORTRAN that solves a standard N Body problem, with a set of Objects which define what an "N-body" IS as well as the functions that can give the solution to that bodies orbit.
The goal is to maximize the ability of OOD to simplify the understanding and theoretically increase the reliability of the very complex code. This is the benefits I am looking for rather, that OOD promises and delivers in building complicated programs. Notice I am not interested in reusability.
So although resuse is meaningless to me in this context, I still want those advantages of an OOD design, maintainability, and more reliable code on a level that structured design/functional approach can't give me.
What is interesting is the "IS" part. In standard structured design which FORTRAN is readily able to implement any algorithm, you have isolated discrete function calls that operate on global data sets.
With an OOD approach, however, I found at least that OOD does provide the following benefits:
1) Taking the simple FORTRAN function library and building it around a unified object that represents the many different properties of the asteroid simplifies the understanding of the algorithms involved.
I wish it could do the same for the mathematics, but that part is still very hard, no matter what language you use.
2) The OOD principles of reuse don't really help here. Primarily because in the context of the problem, there is only one solution. I highly doubt people could reuse this in other ways than it was intended. Except of course, to calculate the orbit of another body.
3) The OOD characteristic of privatization of data organized the code in ways that made the source code, not only easier to understand, but also unexpectedly suggested ways to improve the implementation of the computer algorithms to do the mathematics.
Unlike a GUI library, the spectrum of reusability is much narrower in this case. As I said before, because the computing requirements for the application in question are so highly specific. It is highly unlikely they could be used for any other purpose, except calculating the orbit of a different body. I guess that is SOME reuse.
A GUI library however, you can use a OK button code in all sorts of applications from word processors to web pages, to spreadsheets...using Java for example which is what I am using.
So to summarize this is what I have learned:
1) OOD principles in discrete areas of engineering or system level operating system design have lots of pitfalls, and require a careful consideration of the clear benefits of OOD vs the performance requirements of the application.
Primarily, because OOD is expensive upfront, and lets face it. If you are not going to get all the benefits from that expense, why use it? In may case, I didn't benefit from the generalization of code, for other application use other than the very strict focus on other specific applications of orbital calculations.
2) Reusability in the broad spectrum of coding using OOD in discrete applications in certain fields don't buy you much, because it is rarely a requirement that the code be generalized for resuse. In fact, it is just the opposite, it is highly specific, and only for a given solution.
Such is the case with Operating Systems and discrete engineering applications or scientific applications, for the above reasons.
3) Finally OOD can however, provide clues into relationships of an algorithm to its data not normally gleemed through the narrow lens of structured design. Specifically, such as cited above such revelations may provide clues in how to store data more effectively and reduce memory consumption.
Therefore even if you are specifically choosing structured design as an implementation framework for your computer algorithms, OOD might shed new light on how to code a structured design solution more effectively to handle data storage and its reuse.
Which coould save disk space, cpu time, memory requirements..etc.
Then again, it may not!
-gc
Got Geometrodynamics? Awe, too hard to figure out? Too bad.
I think what you're really questioning is the granularity or detail of the solution to your problems. Remember, at the assembly level, there really aren't any OOP constructs.
Basically, all software boils down to binary, from assembly. Then you have higher level languages like C, which can be used to create other languages and constructs, whether they are procedural or OOP. The higher you go, you begin to form reusable objects, design patterns, frameworks and architectures. Think of this as an inverted pyramid.
It may be that the solution to your numeric problem is best coded in assembly, in which case you don't need OOP. However, if you are creating several modules that each solve a specific problem, you may want to combine them into a generic application framework. If this is a batch processing application that uses a particular module based on the data it encounters, you might use polymorphism and abstraction to deal with objects generically.
At this level, you are concerned with reusability and maintainability. When your boss sees this wonderful application and asks you to add a GUI for non-3133t5 or to add additional modules, you can say "No problem!"
It's an industrial boiler design system in which each meaningful component is modelled as an object.. Then these objects are parts of subsystems of the boiler, and the subsystems all comprise the boiler itself..
I put in a bunch of data files read by the loader object, and used to set the parameters of the internal objects.. Then I simply look at boiler.getEfficiency(), and the necessary computations in all the subjugate objects are done, and there it is..
OOP is more about the architecture of your program and about the way you concieve of the data.. If you think of it as ripping through tables of numbers, you'll at best have a procedural, iterative solution that uses arrays or structs..
If you extend the concept of a struct to be an analogue of a 'thing', and then tell the 'thing' to solve for some attribute of itself based on other internal, and external, factors, you're thinking in OO.
That's all there is to it, in a nutshell.
The REAL jabber has the user id: 13196
What you do today will cost you a day of your life
You might want to check out the OpenSees Project - they've built an OO tool for structural analysis.s .html.
An API listing is available at:
http://opensees.berkeley.edu/OpenSees/api/content
Have fun, Peter
First of all, I'd like to apologize for the "I can't believe someone asked this question!" tone most of the replies have.
Secondly, there seems to be a lot of confusion over object oriented programming versus languages which allow one to program in an object oriented style. It's been a while, but as far as I can remember there are three characteristics which define object oriented programing: encapsulation, polymorphism and inheritance. I am not going to define them here; any textbook can do that, but in general they are not terribly useful in a scientific/technical computing environment. For example, a lot of people get excited about making matrices or complex numbers into "objects". This is a poor choice in the case of matrices because it precludes the ability of a compiler/interpreter to make intelligent decisions about space/time tradoffs. For example A=A+B+C where A, B and C are matrices should avoid teomporary storage for B+C and simply accumulate the result in the storage allocated for A. Within the traditional object oriented paradigm there is no way to do this. Futhermore in packages which operate on values from the real, integer and complex sets the number of methods that need to be defined to handle the mixing of types is so large as to actually increase programming effort when done in a pure object oriented style. In general, binary operations and operations which change type like absolute value of a complex number are difficult to use efficiently in an object oriented style.
Generic programming which C++ supports through its template facility and therefore often gets lumped into the object oriented paradigm is generally more useful in these cases as one can define a single function like addition for example and not have to worry about the nature of the types being added. Functional languages also generally support this style hence the frequent recommendations to use that paradigm as well. However in my experience with languages that support a functional programming style: Mathematica and LISP primarily, you generally pay a price in memory usage for the ease of development.
That said, for programs with a lot of function entry points (ie, a large API), which is not generally the case in scientific/technical computing. The organizing principles of OO can be useful. Similarly for problem sets in which there are a few general operations applied to a wide variety of types functional programming techniques are useful, especially when intermediate results can be discarded. Scientific/technical programmers should be aware of all programming styles (as any programmer should) but the better programmers are aware of the tradeoffs involved in each style.
The only difference between the OO methodology and a procedural methodology is how the /HUMAN/ on the other end has to think about the problem.
Then again, isn't that how everything is? Convienent metaphores to keep poor little humans from having to comprehend too much stuff at once.
Hierarchal file display VS flat file display. If humans could take in data faster the flat display would work better, albiet with a bit more waste in data tranfer (excess data on each directory listing.)
Hell, the only reason you have to WRITE DOWN the intermediate steps of design and brainstorming and such is because the human mind (in most cases) is unable to deal with all of the complexities of, say, a motherboard, mentaly.
Hell get a smart enough brain and you could design anything Fast As Shit.
Annoying sucker that brain is, on a thirty minute math problem it can take me 5 minutes of actual math and 25 minutes of writting down the intermediat steps. . . . . bleh.
Need help treating your acne? Come here!
Think of it this way, a C++ class is basically a C structure on steroids. Functions in the class are like pointers to functions in a structure. Both can do signals and callbacks. The difference is that one was made to make doing OOP easier (C++).
Ada is another option for OOP programming as well as Java.
Do you think that mathcad is all C? I'd imagine that it contains C++ and possibly com objects and it is an engineering program. I'm sure there are others, in fact I remember when I used to read spectrum magazine from IEEE they had adds for many engineering programs and some of the newer ones were in C++.
I think it is your application probably does not call for it.
Only 'flamers' flame!
Real bloat comes from libraries like STL...
First let me say that I have not used the STL much at all. However, I remembered reading an article about the design and goals of the STL which claimed that STL code, when compiled, was almost as efficient as a version written in assembly. Can any more experienced STL/C++ programmers comment on the validity of the claims? I dug up what I think is the article in the byte archives. Its by Alexander Stepanov. Here's an interesting quote from the article:
"I found that efficiency and generality were not mutually exclusive. In fact, quite the reverse is true. If a component is not efficient enough, it usually means that it's not abstract enough. This is because efficiency and abstractness both require a clean, orthogonal design. A similar phenomenon occurs in mathematics: Making a proof more abstract makes it more concise and elegant."
Move on. There's nothing to see here.
Seems to me that you would like to see OOP, really more OOAD for that matter, manage to solve equations or systems of equations.
... "What happens when we swap this part that has a 3db loss?", etc.) This is an example of where OOP can help. Basically, OOAD can help people to design solutions that may better relfect real-world systems, or will be easier to modify.
What you are asking is analagous to asking if you could use an assembly line to tighten a loose nut.
It can't be done. It doesn't work that way.
OO is a technique for handling and solving more general problems than that of solving a system of equations for optimizing a dampening coefficient (pick your favorite problem).
OOP allows engineers and programmers to create systems/simulations/programs/etc. that are less prone to error, and easier to adapt and modify.
The common mistake many engineers and programmers make is to think of computer programs as entirely either a little whipped-up something that can get you the answer to a particular problem, or as a system that is put together to solve every problem under the sun (or to be capable of being easily modified to do so). Programs come in many flavors, really.
OOAD (OOP) allows people to create solid designs of solutions to engineering problems. For example, let's say you are creating a simulation for determining the signal quality for an output from a particular circuit. Basically, you model the circuit, then monte carlo over some noisy variants in the system, average your results, and Viola!: there's your answer.
That's all great and swell until you start getting fun things, like feature creep (aka "Make it do this, too",
OOP is not a panacea.
First of all, for those individuals who refer to C++ as an OO language, please stop. You're wrong. C++ can be used for an OO project, but it is a multi-paradigm language. At least that's what Bjarne Stroustrup calls it. But what does he know about C++?
Second, use of C++'s STL does not equate to OO programming. It is an example of generic programming. Here's a hint: the STL has very little inheritance except for iterators and iostreams -- most evaluation is handled at compile-time. And even iterators and iostreams are just as much generic as OO.
Finally, please dispel the rumor that C is automatically faster than C++ because of C++'s excessive overhead. Need proof? Please read this article about treating C++ as its own language and not a variation of C. Yes, it's a PDF. Get over it.
Think the article is FUD? Prove it! Take the examples from the article and tune them better than he did. Compile them with trusty ol' gcc and g++ on your box. Measure the results. After you do so, can show that C is faster, does not contain any potential buffer-overflow bugs, handles error conditions, and wasn't at least five times more code to do it, then reply back with your results. I have a feeling I won't be getting any replies from people who actually try it.
That said, use whatever language you like best. Studies have shown that people will always perform better in languages they know intimately well than languages in which they have a general familiarity.
But if you want to use OO and C++, check out this numeric library
Have a nice day
- I don't need to go outside, my CRT tan'll do me just fine.
It's called NPSS and it stands for Numerical Propulsion System Simulation. The basic idea behind it is to be able to build a simulation of a jet engine by linking together different objects (fan, compressor, burner, turbine, nozzle, etc) whose properties you can change (fan area, burner temp, fuel flow), in order to theoretically model any engine you want.
I played with it some, and it's very cool. My BS is in Mechanical Engineering, and they didn't start letting engineering students take C/C++ until the year after I started, so I know the FORTRAN woes you suffer.
The thing is that for years engineers have had to use FORTRAN to do stuff it shouldn't really be doing, so they've gotten into habits of trying to think of problems as more complex than they really are, just because the programming language they have to use is unsuited to the problems.
Anyway, NASA has been at it for a few years, and they've done a great job (IMHO) at implementing OO for what they're doing. Using the software to build and simulate an engine is incredibly easy, and you can simulate all kinds of manuevers and engine configurations really fast.
-ristoril
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.
I was taking a few numerical methods classes in my engineering classwork not *too* long ago. At the same time, I was trying to learn how to apply OO concepts to new problems as well as learn the finer points of Java. So I started doing my various homework assignments and projects in an OO fashion with Java. Maybe a few ideas can be a starting point. (Bear in mind what I did was somewhat crude, but it was personal homework assignments, not full-on production code releases. I'm also not advocating use Java for high-performance-demanding code per se; I was only killing several birds with a single stone
For a finite element methods class, I created classes to represent various element types. (Bars, thin triangles, thin quads, etc.) There was also a "matrix" object. Now, each element type object would have a method to populate its coefficients into the matrix, and the matrix would have a method with which to solve itself. Now, the implementation of this particular method is quite procedural if you only look at that part; the OO comes about providing a more abstracted method of assembling the matrix, dealing with neighbor-to-neighbor effects, and the like. Ultimately, I had different classes to solve matrix objects by different techniques, so I could easily change how the problem was being solved by just tossing the matrix object to a different object/method (which was already fairly polished in the more general numerical methods class).
For things similar to CFD solutions (a la your finite volume question), you can likely use OO to organize your flow domain into different region objects, each of which has some notional grid object (or perhaps collection of volume objects). The methods in these classes can give you the ability, again, to assemble matrix objects which can be passed off to a particular solver. (Again, this implementation of the solver will likely appear quite procedural; I didn't carry the idea too much farther before gradution to know if the various matrix inversion techniques could be cleverly OO-ized.)
So in other words, use OO where the principles can help you. It does take some amount of thought to redesign your approach to the problem. Hope this gives a few things to think about.
I'm late joining this thread, so my comment will probably be lost in the noise... I hope that someone who cares sees this and mods it up.
A better question would be 'what is Object-Oriented Programming for". It is *not* for the computer... a computer will happily execute any machine code, no matter what its source.
Object oriented programming techniques, and in fact ALL PROGRAMMING LANGUAGES are abstractions that help HUMANS.
The human mind can only keep track of 'so much' at any one time. That is why we tend to 'package' information up into simpler representations, like analogies and stereotypes. These 'wrappers' around the complexity allow us to manage more at a time.
This is what OOP is for... helping the developer manage the details of the implementation.
Now, we as humans are better at representing some problems and 'procedural' and others as 'objects'. The writers question 'Can OO Solve Engineering Problems?' is bizarre in this context... of COURSE it can... it is just a matter of the human thinking of it that way... the question might better be put 'is there a good way for us to think of these as OO problems?" That is a defferent question... Some problems will be better handled procedurally, some will be better handled as OO. And it has as much to do with the person decomosing the problem and their skill set as it does with the problem domain.
I find your view of what comprises an "engineering problem" too limited. In this limitation lies the reason why you never found OOP tools useful yet --- for those particular problems you consider, you really don't need them. For problems dealing with number-crunching based on matrices and vectors, FORTRAN is still a good choice of tools, even these days. But by far not all engineering problems worthy of using a computer program for are of this type. These days, finding the optimal layout of base stations for a cellphone network based on lots of geographical and electromagnetical facts is a hugely important engineering problem. No matrices involved at all.
;-)
In other words, you're facing the inverse of the old saying: "Once you've bought a new hammer, all kinds of things start looking like nails". You have had nothing but that hammer for so long you got used to thinking only driving in nails is important work.
Now, seriously: OOP is not for (your selection of ) "engineering software", but rather for "software engineering". Its gains are in projects where the difference between craft and engineering becomes truly important.
Let me try illustrating this by a reference to the history of technology. There's a reason one of those OOP languages is named after Mr. Eiffel, the engineer who built that famous iron tower in Paris. Mr. Eiffel's real revolutionary achievement at the time was that he constructed his tower by combining relatively few types of well-designed and tested elements. In a similar way OOP techniques help you to create well-designed and testable building blocks out of which you can then construct your software system. The key is that these building blocks are *isolated* from each other as completely as possible, and that using them is considerably easier, and less error-prone, than a classical Fortran function library can ever be. In this way, OO techniques help you to manage problems whose sheer size would normally make them impossible to tackle.
Well in the above case OOP does not seem to offer much benefit. However after programming for several years in Java I just naturally deal with problems in an OOP way (not a purist, use right tool for the right job is my motto). The biggest help is that instead of thinking of the code problem in the code space I am thinking of the code problem in the real world sense. Currently I am working on an online classroom and grouping all the code into its real world counter parts is very helpful (There is a student object that handles all the student code, a teacher object that handles all the teacher code, a reports object etc). OOP also helps with readability and code isolation, in having only the code for specific problem in the algorithm at hand. So in dealing with each specific instance of engineering problems it is probably not helpfully, but if you were to make a program that was more a library of solutions then it might come into play.
It seems you have convinced yourself that the world should be modeled in terms of procedures. This is typical for people who have programmed using procedural languages. The same happens to people who program OO: they see classes everywhere. Then you have people who like functional languages: suddenly everything seems a function.
The sad part is that all these paradigms have problems where they can be applied very well and none of them can be applied to all problems well.
Now back to OO. What is it good for: it's a good way to structure complex systems. If you have a complex system, you can probably make its structure more explicit by using objects, design patterns and so on.
Mind you, it is no silver bullet and you wouldn't be the first one to build a super complex, flexible OO everything system that doesn't perform well and is impossible to maintain.
Symptoms that indicate you might benefit from OO:
- There's a lot of commonalities between the programs you write: this indicates that you can generalize functionality.
- There's a lot of dependencies between your modules: you need to encapsulate and hide stuff
- You have a lot of complex data structures and lots of functionality around those data structures: hmm objects???
If you are serious about adopting OO you should spent some time with books about OO design such as for example Gammma's excellent book about design patterns.
As for your question regarding engineering problems. I have worked with companies involved in building embedded stuff like fire alarms, haemo dialysis machines (medical machines), mobile phones, digital radio systems and embedded server products. All of them use OO based designs to their advantage so it can be done. And in case you are wondering: all of these systems were very large systems (500 KLOC - 5 MLOC). Using OO is a necessity for these companies since it is the only tool they have to keep complexity under control.
Jilles
I haven't worked _on_ this project but I did work with it a little bit, and tried to write a small analysis routine for a class I took. Check out the OpenSEES Project at Berkeley for a good example of a OOP solution to an engineering problem. Every portion of the analysis, from equation solvers and matrix routines to structural elements and material models are broken into objects. It's an ambitious project but it's moving quickly. And it's even open source!
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.
m l
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.ht
Being a former embedded systems software engineer who did a fair amount of work in the modeling & simulation environment, I've seen a lot of engineering problems "solved" through code. And let me tell you that you're right, few if any are done in an OOP language. Why?
:) I'm not trying to imply that C++ should stand as a definition for all OOP languages) are not deterministic, and don't typically run too efficently.
Perforance, plain & simple. OOP languages (I'm simply going to use C++ in place of OOP as it's easier for me to type
There are several reasons for this, but two stand out in my mind. Memory Management, and what I'll call Bloat.
First off, C++ code tends to make use of a LOT of dynamically allocated memory. Lots of structures passed back and forth between procedures (methods), things on the heap, and so on. All of this adds overhead to the code. It takes time to do all of that. Just puttng a structure on the stack can result in thousnads of ops (read mem, write mem...). THen there's garbage collection (GC), this runs async to everything else and can eat up more CPU cycles you process needs to run. it may also make some sections of code run longer than others because the code has to wait for the GC to finish. Enough of that.
Bloat. In order to meet one goal (quicker code development, and lots of reuse of code) C++ has added many layers on top of C. function tables, polymorphism, abstraction, overloading... these things all add more execution time to the code, and make it less deterministic. When I add 2 variables in C or FORTRAN, I know about how long that takes. if I do it in C++ with abstract datatypes, who knows? The complier has to generate logic that can to figure out what function to use, call it (copy the data onto the stack) perform the operation, and return the result. That logic all takes time to run.
For solving a complicated problem in a timely manner, like say modeling the amount of radar energy reflected off the complex surface of an aircraft, and returning that result to a flight sim C++ might take too long. By the time the code figures out if you can see the other guy, he's already sent a missile your way!
More complicated problems, like modeling a weather pattern, FEA, or hydrodynamics caan take very long times to run without all of the overhead of C++. The also tend to be fairly straight forward problems to solve, just very compute intensive. Many business apps on the other hand (which is what C++ is good at) have a myriad of nuances and abstractions that aren't comput intensive, but require lots of logic and code to figure out which path to take. Like generating the financial statements for a company. it may only be a list of numbers to add up, but where to find the numbers? what do they mean? What about depreciation, partially owned assets, and one time charges. Lots to figure out what to do with, but little calculation to be done.
ENOUGH! that's just my $0.02
Personally I would consider this article to be a troll.
Befor eyou mod me down as a troll, think for a moment. The software engineering world is completely dominated by OOP concepts, and the foundations of OOP (encapsulation, inheritance, polymorphism) save thousands of man hours / year / developer when people understand how they actually work.
The reason I call the article a troll is the highly C based leanings of the /. crowd. The most vocal people here still wish they were allowed to hate KDE, and love only gnome (C based Gnome, C++ based KDE) and the language of implementation carries over to general principles for most people
And before someone says it, yes you can do OOP in ANSI C, but it is ugly as sin (basically function points on structs for methods, etc).
-Frums
Example 1:Vector Math
Ok, here is probably the simplest example of where object oriented programming can come in handy. Say that you are working with vectors. Now, vector math isn't all that complicated. You can do it rather easily through function calls, such as (in C)
vec3 = addVectors(vec1, vec2);
But, it can be a little nicer to have your code reflect a formula that you've developed or are utilizing. Programming the same problem in C++ (you can probably do this in other languages too, I'm just familliar with C++) allows you to change your problem to
vec3 = vec1 + vec2;
The way you do this is you overload the + operator (the function named operator+()) in your vector class. Your vector class holds all of the information about the vector and has operations that know how to work on that data. You could further extend your class so that you could do subtraction (vec2 - vec1), division (vec2 / 5), multiplication (vec2 * 5), translation (vec2.translate(5,5,1) ), intersection detection (vec1.intersects(vec2)) and so on.
Example 2:Matrix Math
The same sorts of things can be done with matrix classes. Create a matrix class that you populate with data and has operations for performing mathematical operations on that data.
matrix3 = matrix1 + matrix2
matrix3 = matrix1 * matrix2
matrix1.rref();
etc.
Could you do the same operations using structures and functions? Sure, but it wouldn't look nearly as clean. The added benefit here is that the interface for performing these operations on your new data types (matrix and vector) are consistent. You didn't have to learn that matrix operations are carried out by matrix_add style functions where vector operations are carried out by vector_add style functions.
something clever
There is an interesting (and rather negative) review about OOP here (OOP Criticism).
OOP is by no means a magic solution to programming problems.
MOD THE CHILD UP!
OOP can work very well with engineering problems in principle. The difficulty has been that most OOP languages have either been too slow (e.g. Smalltalk) or aren't that easy to use for engineers (C++ is pretty messy in terms of OOP and memory management and what you have to do to build good OOP models, in my view).
Where OOP could help is in the extensibility of code. An example would be in molecular modelling where particles and the interactions between them fit very nicely into the OOP paradigm. The great thing about using objects is that if you want to add new particles or new interactions, you just extend existing classes. OOP tends to make finding and applying changes to a system very much easier and less error prone.
Even with systems that are less based on 'things' such as particles, and more based on 'processes', such as calculations, OOP allows such systems to be broken down into distinct modules with clearly specified 'interfaces' between the modules, so it becomes very easy to update and extend the system.
Java could have a lot of potential for OOP in engineering, as its a simple enough language so that the developer doesn't get distracted with memory allocation, and with the huge amount of work being put into optimization of VMs, Java is likely to match the speed of Fortran in many cases
It's job security for people who don't understand business rules, e.g. programming majors.
Most people seem to be talking about OO and engineering in the abstract, so I thought I'd add some facts from a real-world case study. (* ducks out of the way as screaming ./'ers flee for the exits ;-) *)
When I was a Senior Economist with the Law and Economics Consulting Group, I worked on an electricity deregulation project. We had to model the electricity market, including the flows from sellers to buyers and constraints on the flows. Individual generating plants had run rate upper and lower bounds, and there were varying loads depending on time of day and time of year.
This was modelled by using the following main classes: electricity generating plants, utility companies, and transmission lines, plus some minor helpers. Each electricity generating plant had its own capacity and marginal cost of operation, and there were various sub-classes of generating plant for the different types: coal-fired, gas-fired, gas turbine, hydro, each of which had different characteristics; e.g. hydro plants had lower capacities in autumn than in the spring. Transactions between utilities were modelled as another sub-class of generating plant, whose capacity was the amount of the transaction and whose cost to run was the price of the electricity sale. All of this was subject to the transmission constraints between nodes.
Utility companies had loads that they needed to supply, either using their own generation capacity or by purchased power. They would attempt to reduce the cost of supplying their loads by purchasing electricity on the open market instead of running their own plants. They would also attempt to generate additional profits by selling electricity to other utilities whose costs were higher. The market was run via multiple rounds of bidding, until the cost of electricity in all of the different areas had stabilized. There was a special case (although in the programming world no sub-class was needed) of energy marketing companies, e.g. Enron, which had no native loads that must be supplied but which did own generating plants.
So you say, OK, why is this an engineering problem? Isn't it an economics problem? Well, it is in fact a superset of the engineering problem. In fact, there were several software packages that we investigated that -- given the operating characteristics of the plants, the transmission constraints, and the loads to be supplied -- would calculate the most cost-efficient combination of generators that could supply that load. However, none of these would have given us any insight into the necessary market interactions that would happen under deregulation. Writing our own model in C++ using OO methods enabled us not only to solve the engineering problem of supplying electricity to the region, but also to study the way that the companies would behave in a deregulated environment.
--Paul
As many other people have pointed out, it's not so much the type of problem that matters for whether or not you choose OO technologies.
If you are by yourself, writing a small single-purpose, one-shot, low-state program that requires maximum performance, then by all means write in some procedural language.
If you are working with a large, distributed team, writing a large, complex, high-state program where performance takes a back seat to flexibility, evolvability, and maintainability, then choosing the right OO language can help a lot.
And if you're somewhere in between, the choice depends a lot on your circumstances.
But if you do pick an OO language, please take it seriously and really learn how to do OO design well. I saw a team write a million-line procedural program in Java, entirely missing the point of using Java in the first place. They would have been better off using the Visual Basic they knew and loved. Or they would have been better off going whole hog and actually writing OO code in Java. But their Procedurized OOP killed them.
Switching from a procedural style of design to an OO style of design will take you a couple of years before you're as good in OO as you were in your favorite procedural language. To get a good start, rummage around in Ward Cunningham's Wiki. And check out books like Martin Fowler's "Refactoring". Also consider using something like JUnit or CppUnit and the XP-style test-first programming, which will speed your learning considerably.
And regardless of what you pick, good luck!
Some of these will be applicable to managing your algorithyms or making your software more flexible.
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?
It is possible that your key algorythyms will remain lumps of procedural code, OO languages allow this. There is advantage in an application of any size in the judicious use of OO techniques.
My Karma: ran over your Dogma
StrawberryFrog
It boils down to where the complexity in your problem is:
- If the data structures are rich and manyfold, you model the data types first (Has-a and Is-a relationships). Then you spread your algorithms around it. That's what OOP is about in really big systems.
- If the data structures are trivial, but the algorithms working on it are complex, you put all your energy into the algorithms, decompose them, look for coupling and reuse and end up with structured programming. Then you spread the few data structures in that you have and move them around as parameters. That's what procedural programming is all about.
In my experience, commercial applications are rich in data structures but trivial in algorithms (only add and subtract) whereas engineering applications only have matrices as their data structures, and calculation and visualisation is complex.
for (int i = 0; i
You use OOP techniques and patterns to model the problem domain itself, not perform simple (or even complex
Look at, for example, MPQC, a parallel quantum chemistry code that several times in recent years has held the record for largest QC computation ever performed (QC is one of the most computationally demanding branches of scientific research.) MPQC is built on a modular library called SC, for "Scientific Computing," which includes all sorts of tools for parallel communications, parallel file I/O, vector and matrix math, etc. SC and MPQC are written in a very O-O style in 99% C++ (a bit of legacy FORTRAN still in there.)
Cantankerous old coot since 1957.
> I appreciate the concepts of OOP and see its applicability in managing records
2 89482,sid13_tax284872,00.html -- there are also some interesting articles at http://dmoz.org/Computers/Software/Databases/Relat ional/ and subdirectories, including an early version of the Third Manifesto.
Then unfortunately you haven't quite understood neither OOP, nor databases -- and databases are essential to many kinds of programming, including engineering.
Please read http://www.firstsql.com/dbdebunk/, as well as Fabian Pascal's articles at http://searchdatabase.techtarget.com/tipsIndex/0,
Leandro Guimarães Faria Corcete DUTRA
DA, DBA, SysAdmin, Data Modeller
GNU Project, Debian GNU/Lin
http://ptsg.eecs.berkeley.edu/ has a plasma PIC code based on OO principles.
i agree w/ others- you seem confused about what OO actually means, though i won't beat that dead horse.
as a physicist, i'm using f90/95 so that i can keep the fast fortran compilers (and yes, fortran is still faster than c/c++ in heavy floating point calculations w/ functional calls- sin, exp, etc.) and yet still use OO methods to keep things contained and portable.
to take your heat transfer. that's a simple elliptical equation. so is Poisson, Laplace, diffusion, etc equations. so i have an object that does just that, given a list of 'structures', the object constructs a mesh, constructs the finite difference (or element) coefficients and then solves the bloody mess. so from the rest of the code, all i have to do it get.field(structures) or get.temp(structures) and either Poisson or the heat equation is solved. the calling routine doesn't know how this is done and it doesn't matter. the object itself decides what type of mesh (structured/unstructured) depending on the equation and shapes of structures. there are sub-objects for individual numerical precedures (e.g. cg for symmetric matrics, ADI for structured mesh, etc.).
it's elegant in the sense that you can seperate the nuts and bolts of numerics from the physics. the main code is usually very readable (who reads comments anyways?). once you have the objects and sub-object debugged- they are portable and don't have to be touch.
OO is a wonderful way to go for physics problems when you're faced w/ writing a large code which will have to evolve in time in ways you can't possibly predict. which is what i seem to do...
Haskell is an often overlooked yet interesting and powerful procedural language. I've used it for some engineering math and also implemented an ARM processor VM with it for a class. Just thought I'd mention it :)
Use the Z-modem protocol between Information Superhighway routers to compress the plaintext. ~LordOfYourPants
While OOP has some advantages in a traditional setting, where it really shines is when you use OOA/D (OO Analysis and Design) as well. If you do a traditional functional analysis and design, then you get a procedurally oriented design. Any OOP benefits you get out of that will be minimal.
However, if you do OOA/D, then you come up with an object-based design, and at that point using OOP really helps a lot.
The question then becomes one of how do you want to perform your requirements analysis. If your requirements are strictly functional, then you don't get much benefit.
On the other hand, even with a functional design, you can still benefit from some features of OOP (the Pipe/SquarePipe/RoundPipe examples above come to mind).
As several people have mentioned, if you can factor your problem and find the commonalities (remembering to distinguish IS-A relationships from HAS-A relationships), you may be able to take some advantage.
Many of the problems you mention (Monte Carlo simulation of XXX, finite difference solutions to DiffEqs, etc...) are at too low a level to use OOP. If you look at them, they're really more a means than an end in and of themselves. The question you need to look at is, "What am I using these low-level 'primitives' to do? What is the big picture?"
For example, you mention radiative heat transfer. Maybe you're designing an engine. You could put the (procedurally oriented) radiative heat transfer routines inside the Radiator object (note, I have no background in engineering -- I'm guessing...), and use it that way in an OO manner.
However, in the end, it all comes down to your analysis and design.
Incidentally, there's one more thing to consider: IF IT AIN'T BROKE, DON'T FIX IT! I know that engineers have tons and tons of debugged, working FORTRAN code. If you use that, you don't have to worry about the typo you made in re-implementing the FFT.... Always a consideration.
Fascism starts when the efficiency of the government becomes more important than the rights of the people.
OOP was introduced with the Fortran 90/F95 standards. This is included in EVERY commercial compiler. Unfortunately it is not in the GNU F77 compiler which no-one seriously uses. Even "Numerical Recipies" has been updated to the new standards.
I have programmed in most modern languages starting with C++. Transition to F90 is very easy. The key features are Data/Function objects and Operator overloading. While the true OOP purist may not find "Garbage Collection" or advanced inheritance, OOP Fortran is plenty "Good Enough" for real world problems. The old F77 standard is used only by people who "don't know any better". The advantage of Fortran is its powerful out-of-the-box matrix handling. Since matricies and vectors are native concepts to fortran, it can run far more efficiently on super computers. No other language expept perhaps IDL have these features.
I would NEVER program any substantial scientific analysis program in C++ or JAVA. Fortran has 30 YEARS of math/science library routines built up. Nothing like this exists in the C++/Java worlds. Most C++ advanced math libraries (there aren't many) are just ports from fortran.
Sadly, I see a real push away from Fortran promoted mainly by CS departments. Through 4 years of engineering school at a major university, I never heard even one thing about Fortran 90. It is sad since Fortran really has kept up with the times. The problem is that Fortran 90 is backward compatible with F77 so there is usually more than one way to do things. (Like C++ is backward compatible with C) Another problem is that the F90 language arrived somewhat late, which gave C++ a foothold. Still, without question OOP based F90 is THE PREMIER language of scientific computation.
Question: What programming language will engineers be using in 20 years?
Answer: I don't know, but they will call it Fortran.
(That joke is funnier if you were around when Fortran 8X, er 90, came into being.)
"Rub her feet." -- L.L.
Design Patterns and Refactoring.
,Abstract Factory...all these are tools to help you use and ruse code that get's the job done. Refactoring allows you to get there from what you have.
Design patterns help you to orgabnize your code. Refactoring allows you to postpone doing so until it is required.
You write code to solve a problem. As an engineer, you write it procedurally, focusing more on the process than on the objects. That is OK. You are not really happy with it, but it does the job.
Now you come across another problem. Really similar, but slightly different. You have two choices. (Well more, but I'll focus on two)
Copy the old code, change the few places that are different. Solve the new problem.
Or, you apply a refactoring. Perhaps the difference is just a process that needs to be run . Extract it into it's own method, extract the moethod into an object, swap it out, and you have a strategy pattern. Or perhaps it is more complext than that, there are 4 or five steps to be completed, but details are different in each place. Refactor to a template method.
Or where input before came from a file, it now needs to come from the network. Abstract your input, and extend using inheritance. Now you can have file input, network input, and others as they come up.
Or your buddy next lab over has a really cool process he cobbled up that you can use but your code initializes a complex object one way, his another. Adapter, Builder
It breaks my heart to hear that they are no longer requiring ADA. Although I only learned the pre 95 version, it was my intro to OO, and I find it shares many of the things I really like about Java. And, without the Sun issues that bother so many. It really is a nice language
Open Source Identity Management: FreeIPA.org
The point of OOP is to protect you from yourself. There is nothing you can do with OOP that cannot be accomplised in structural or procedural languages. For instance a class in C++ really gives you nothing more than a structure and functions designed to operate on that structure in C. The difference being that the programmer must use the member functions to manipulate the data (unless they are public of course). This is more of a hinderence than a help on complex problems, as there are times that you will need to make many small manipulations to the data but, they do not need to be reused (making them worthless as a function, unless you think it makes the code clearer in some way.) Stick with C for complex problems. Use C++ when the staff is inexperienced (or not very good), or when your problem will fit very nicely into an OO framework (which does not happen often with complex problems.)
I'm a signature virus. Please copy me to your signature so I can replicate.
When I port a C program into Python, I take the 100 global variables and make them members of a dummy class, so I only have to feed 1 variable into each function. Oh the wonders of OO :) :)
Operator overloading is just syntactic sugar, it has nothing to do with object-oriented development. There are a number of non-OO languages that implement this feature. I dislike most uses of operator overloading anyways. Sure, it may "look cleaner" for the above trivial examples, but with multiple overloads and implicit casts, it can be difficult to figure out which function ends up being called. Better to keep things as explicit as you can.
The definitive benefit of object oriented languages is caller-reuse as implemented through polymorphism. In procedural programming, I can reuse called code (a.k.a. functions), but in OO programing I can reuse *caller* code. The shapes example is great to illustrate this: if squares and circles both inheret from a base shape, who implements a "draw" function, I can easily add triangles later, pass them around as references to the base class "shape", and any code that asks a shape to draw it self remains untouched, whereas in procedural programming I have to touch each instance of code that has to do with drawing, and account for the newly added triangle case.
Invisible Agent
This post is a mirror; when a monkey stares in, no hacker gazes out.
I used to write financial software in C++. We has objects for Interest Rates that handled conversions to and from various types (Annualized, Continuous, Bond Equivalent Yield, etc) and could work as normal double floating point values. We had a class hierarchy for option evaluation functions. At the base a parent class had the features common to all options and their evaluation formulas. Children classes then implmented specific evaluation formulas. Sometimes tweaks were needed to those formulas for specific situations and another level of inheritance was used. We found that the OO C++ code was much easier to maintain and add on to then the previous functional C version.
As other posters have said, to really use OO you have to break the problem down into objects. What are the features of these objects? What do they do? How do they interact? Another good idea is to see what certain objects have in common. This allows you push these common features and functions into a parent class that both objects inherit from.
-- soldack
What is the difference between C as a procedural language and C as a functional language.
As far as *I* know, C is functional language being that every part of it is a function. What makes a language procedural anyway? When you really get down to where the rubber meets the road, all code is procedural is it not?
Codifex Maximus ~ In search of... a shorter sig.
OO and functional programming is not so new in the scientific (numerical) community. Take for example IDL (from Reseach Systems), a scripting language very commonplace in astrophysical data analysis: Data arrays behave like objects with their own methods.
Another example is vtk (visualisation toolkit) from www.kitware.com: a numerical visualisation library that can be used from c++, tcl, java and python.
And speaking about python: the numerical extension NumPy is very OO, too. (or check out scipy.org)
I also know about some large plasma simulations that are written in c++ using oo-techniques.
The problem is that many scientists are still using code from the 80's written in FORTRAN 77.
OOP techniques can provide amazing advantages for numerical computing, and I'm surprised that there isn't more written about it. When you deal with scientific computing, it's a combination of numerical computation and the usual comp-sci stuff figuring out how to implement simulations and the like. For "the usual stuff", we know very well how OOP can help. But for numerical programming, the benefits are still there.
In numerical work, you deal with a variety of mathematical objects such as complex numbers, vectors, matrices, tensors, algebras, and so on. In working with the math, we tend to use the more sophisticated objects because they are easier to deal with (laziness) and more meaningful. But when you go to code it up in, say, Fortran, all the beauty vanishes and the nitty-gritty details become a menace. Or, you could use OOP and make up things like vector classes, matrix classes, and so on. Then the code suddenly becomes simpler, you save a little time writing the code, and make many fewer mistakes. The code looks more like the math.
I hear that rogue wave makes some very fast C++ libraries for numerical work, though I haven't used them personally. There are other collections out there as well, I'm sure. My main beef about other languages such as C++ and Java is that there is a blatant lack of concern for numerical programming. Here are some rants:
I hate Fortran, I really do. But when doing pure numerical work Fortran's actually a lot better than most other languages I've seen. There's no good reason why other languages couldn't be reasonable in this regard.
Okay, I'll admit that the only two genuinely OO languages I know are Java and C++. And these both derive much of their behavior from C, which is not a very "modern" language any more. But it is still a lot younger than Fortran. (Yeah, Kernigan and Ritchie were going for speed and simplicity in the mid-70s, I understand.) Anyway, in spite of wanting to borrow syntax from C, why can't anyone simply decide to improve on the bad old features of C like those mentioned above?
Whew, okay. I'm done ranting now. I feel much better.
This may be useful in the broader perspective of applying OOP to real life. Their are plenty of papers up on the IBM site that are worthwhile, even if searching for them could be inconvenient.
"It is a greater offense to steal men's labor, than their clothes"
MOUSE (GPL) -- an OO framework for finite volume computations on unstructured grids.
Also, finite element analysis comes to mind as a fertile realm for OO. In fact there's a book on it:
Object Oriented Methods and Finite Element Analysis
That was the turning point of my life--I went from negative zero to positive zero.
Great explanation. Succinct and informative.
I'm an engineer who programmed for many years in Fortran, was interested in OO languages, but always reverted to Fortran for real work. My first real OO code was a library to do Automatic Differentiation for uncertainty analysis. This has been done very successfully in Fortran 77 (ADIFOR for example), but the result is essential a preprocessor that reads a Fortran code and outputs new code Fortran code with extra statements for calculating derivatives. In an OO language that supports operator overloading, such as C++ or Python (not Java), no preprocessing step is needed, you just redefine math operations and functions to include the calculation of derivatives. In all, a much cleaner, easier and more elegant solution. Functions and operators for matrices and even more complicated data structures are relatively easy to develop and can really simplify programs that are written to solve engineering problems.
Since this first effort at using an OO language I have since given up on Fortran to write engineering code. I mostly use Python (which has a very good numerics library) and occasionally use C or C++ when extra speed is needed. I really hate going back to Fortran because it now seems so restricting. I personally would recommend looking at Python as very nice OO language for engineering calculations.
Sorry, but I think that's a bad example. Using an OO design has gained nothing over a simple function or two here, but has probably generated much more clutter as a result.
If I dared propose a more appropriate example in a similar vein, one thing OO is quite good at is providing and working with a representation for complicated and interrelated data items, such as a mathematical expression. Suppose I'm writing a mathematical tool to process these. I will represent an expression as an object of type Expression. Subtypes of that might be ConstantExpression (representing a numeric constant, say 2 or e), AdditionExpression (representing a+b, where a and b are themselves Expressions), etc.
Now I have a clear structure for representing these, I can parse whatever input I have into this format, and work with it. Need to display it using pretty graphics? No problem, add a Display() method to Expression's interface, and provide a suitable implementation for each subtype. Need to evaluate the expression? Eval(), here we come.
So far, so good. You've used OO to provide a nice representation of a problem, at least as clearly as a procedural solution would have done. It's pretty much a draw so far, and a matter of personal preference which style you prefer.
However, the OO framework is much more easily extensible than its procedural counterpart. You can add new subtypes of Expression, and have them immediately fit into your existing framework, without changing any of your existing code (or even having access to it, for that matter). To do this procedurally, you often wind up writing some clever switching logic, but OO does it all for you behind the scenes.
It's also easier for the outside world to work with your code, because you can provide nice, clean interfaces, such that all Expressions look the same to the outside world, however they are composed.
Finally, this approach helps organise your code. If all your types of Expression provide an Eval() interface, the implementation of that interface is in a known place, and probably quite straightforward for each subtype. This maintains a degree of clarity that is easily lost when you don't have the organisational framework an OO design supports.
If you disagree, post your argument. (-1, Overrated) isn't your personal censorship tool for views you don't like.
I agree with most of what you wrote, but I think bundling C++ templates in as "fluff" is grossly unfair. Templates are responsible for a lot of the good things about C++, and many of those aren't necessarily OO at all. The ability to write generic algorithms, but also specialise them for cases where's it's useful, is a godsend to those writing mathematical functions. The use of expression templates to generate highly optimised code with no programmer effort means C++ programs can now equal or beat the sort of code produced by a decent FORTRAN compiler. And, of course, the use of class templates means you can define generic mathematical structures such as matrices over any type you like, which makes such structures far more useful than vanilla OO designs would allow. Finally, there is the use of templates to provide traits classes, policy classes, and other tools of general use. None of these things is "fluff" if you're trying to develop a serious application!
If you disagree, post your argument. (-1, Overrated) isn't your personal censorship tool for views you don't like.
First of all, as it's been pointed out a million times: OO doesn't necessarily mean C++!
I've worked with C++ on a very large 3D application, Maya (3D packages are one of the best candidates for OO design) and I decided that C is a much better solution for this type of an app.
You can create OO solutions extremely well in C!
Having 8+ years of experience in the field, I would actually argue that you can do it more efficiently in C than in C++!
Some facts & numbers:
A few co-workers of mine are using C++ for a moderate sized (both for functionality and code size) project that's about 30K lines of C++ code.
Compile time: ~2min 40sec
I'm working on a quite large 3D application in C that's about 10-15 bigger as far as functionality goes and is composed of about 300K lines of dense C code (tons of objects, template functions, embedded macros etc.).
Compile time: ~ 2min 30sec on the same system!!!
I find it a lot easier to keep track of things, to reuse code and to debug the application.
And the users definitely appreciate the fact that it starts up in 1-2 seconds with about 50 plugins loaded at runtime
:)
This 3D app would DEFINITELY NOT have this much functionality and/or would not be as stable as it is, had I developed it in C++. If for nothing else: sheer COMPILE TIME!
I know that C++ is "fashionable" nowadays, but I think, it is being way over-used.
Though I'm sure it's a better solution for some projects...
I maintain an old mechanical engineering simulation package that was originally written in FORTRAN 66 way back in the 60's. It is a major pain in the a$$.
;)
It uses "arithmetic if's" and "gotos" which really generate spaghetti. It also uses a huge "common block" for global data (which is basically every variable). Any function or subroutine can change any global variable. Variables have different meaning at different times in the program to save memory. Fixed array sizes. The list goes on and on.
I wish we had the budget to move this beast to C++ where it would be easier to add features to objects without having to delve into the guts of the program to make changes.
The program is fast at what it does though
-"The early bird catches the worm, but the late bird sleeps the most"
This actually made Ask Slashdot? Why?
Which is why you can't see OO for what it is.
Now, looking at the disassembly of OO programs makes it clear that the only real functionality difference between C and C++ programs is that a "this" pointer is sometimes passed around. The purpose of "this" is to associate an "instantiation with the currecnt context". Or said in another way, its a conventient way to solve some re-entrancy and multitasking problems.
Now of course the higher level OO paradigms added, like namespaces, templates, derived classes and so forth are nice. However, they are all just some syntactic sugar that hiding what is essentially just the C language.
As an intermediate solution I would suggest that you take a look at the more modern variants of FORTRAN. In particular, I just recently finished a rather large project which was written in Fortran 90 and found that it has some very nice object-oriented'ish properties that were very handy. It was a good deal less extreme than going to a true OOP language.
However, I should comment that some of the big accelerator codes (check out the work done at www.lanl.gov - Los alamos accelerator code group) using MASSIVE oop to push billions of particles
are written (I believe) using OOP languages and
symplectic maps...It's really quite amazing what they've done.
Imagine that you want to simulate the thermal behavior of a solid. You can build an object, a class if you want, called "solid". Then define a method (procedural programation) to simulate radiation exchanges, another for conductive ones and a third method for convectives. The way OOP can help you is that if you want to simulate the thermal behavior and ink per page consumption of a pen, you can create an object called "pen", write down the code for the ink part of the problem, and just instruct that your "pen" object is a "solid" kind of object, making use of the existent methods for such an solid object. Imagine that you want to simulate the thermal behavior of a solid. You can build an object, a class if you want, called "solid". Then define a method (procedural programation) to simulate radiation exchanges, another for conductive ones and a third method for convective. The way OOP can help you is that if you want to simulate the thermal behavior and ink per page consumption of a pen, you can create an object called "pen", write down the code for the ink part of the problem, and just instruct that your "pen" object is a "solid" kind of object, making use of the existent methods for such an solid object.
Read Marx Mrvelous answer at Jan 03 11:38 AM
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
go to www.dromeydesign.com
our main product "DESS"
is all Object oriented
where we model entire power systems in an oo model
Regarding the SQLPlus code written very Fortran-like, Doesn't the saying go "A FORTRAN programmer can program FORTRAN in any language"
I've been doing OO programming in physics and engineering (mostly Monte Carlo simulation, but also statistical analyis of data) since the late '80's. The trick is to reconceptualize your problem, which is independent of the language you're writing in. My early OO efforts were in FORTRAN77 and C, now long abandoned in favor of C++.
I've since seen a lot of what passes for OO programming in the sciences, and most of it isn't--it's thinly disguised procedural programming with clean and well-specfiied interfaces.
The difference between OO and procedural programming at the design level is the way in which programs are structured. Procedural programs are at their core a collection of algorithms that operate on data. OO programs (should) have at their core representations of real-world objects, with neither data nor algorithms being the primary abstraction. The be an object a thing must have both state (data) and behavior (algorithms).
We are still in very early days yet in applying OO principles to science and engineering problems. Even "OO" numerical libraries are to my mind a very, very small step: they represent traditional, procedural algorithms in slightly richer and more maintainable ways. Having a matrix "object" for instance, is a definite gain ove having a flat array and bunch of procedures that work on it, but the success of the STL suggests that generic programming is a much better approach to this sort of problem than OO programming.
The place where OO programming will come to the fore is in allowing rich and intelligent representations of real-world objects in engineering software.
For example, I once wrote an OO layer overtop of a Levenberg-Marquardt minimizer that allows me to represent the objective function in terms of physically meaningful components that can take constraint objects that prevent the minimizer from entering physically impossible parts of the parameter space. In one sense this is a trivial problem, but in a larger sense it allows me to quickly specify components and constraints without ever having to think about array indices and other error-prone nonsense.
It is this aspect of OO--its ability to produce rich and natural representations of complex problems--that we have hardly begun to explore, and where the real strength of the approach lies for science and engineering.
--Tom
Blasphemy is a human right. Blasphemophobia kills.
A couple of books on the subject, available from Amazon.com:
Scientific C++ : Building Numerical Libraries the Object- Oriented Way by Guido Buzzi-Ferraris
Scientific and Engineering C++ : An Introduction With Advanced Techniques and Examples by John J. Barton, Lee R. Nackman
I've got Scientific C++. Its not bad. He gives an idea of creating matrix classes and solvers to greatly simplify the writing of even procedural matrix problems.
Its been so long since I've had creative input to slashdot that I forgot my nick. :)
Look into the model, view, controller paradigm. It seems this is well suited toward OOP and could apply to a variety of mechanical systems.
The biggest problem people have, in my expirence, is in applying OOAD correctly to the domain they are working in. You can model anything you want to using OOAD but it can often take some time and a good deal of knowledge about whatever field you are working in. It can be hard to find talented people who also have enough knowledge about what specific engineering task you have them writing software for.
Although that is the biggest problem I have noticed, I don't think its a problem of OOAD at all. You run into this problem using any programming method. Its not a problem of OOAD at all.
OOAD can be applied to problems in any field. However, OOAD does not solve any problems itself. Its a method modeling and developing a solution. OOAD is not specific to any programing language in particular, think of it more like a methodology. You still need to create an efficetve solution. Its a tool for doing that, not a solution in and of itself.
If you can map out some goals of what you want, I don't see why you should not be able to produce an effective design to do it. There are many sources of information about this (you can find links to quite a few on http://www.cetus-links.org)
If your not comfortable with object oriented design, then I would suggest that the problem may be in choosing a problem solving approach you are not comfortable with; and not a problem with OOAD itself. If the people who will be ultimately responible for maintaining this software are not OO people, then it doesn't seem like the right tool for the job. You can't attribute that problem to OOAD, though.
-- Eric
Why use sledgehammer to swat fly?
C++ contains a special type of construct called a template which can be used in a "who would have thought of that" way to perform math functions like FFT's and sorts EXTREMELY quickly.
. htm
r ograms/meta-art.html
They are called template metaprograms and what they essentially do is completely unroll large mathematical operations at compile time and give you a big blob of machine code that is hardcoded to do your operation. Todd Velhuizen seems to be the patron saint of these constructions, and he claims in the links below that a metaprogrammed FFT runs at 3 times the speed of an optimized regular FFT routine. The caveat seems to be that the larger the operation (like a sort for 100 elements as opposed to 10) the larger the unrolled code generated, and hence the lower the processor cache hit rate and the less that things like function call overhead (which unrolling completely removes) matter. Here are some good links to the subject:
http://www.ddj.com/documents/s=958/ddj9608d/9608d
http://osl.iu.edu/~tveldhui/papers/Template-Metap
However, if you're looking for flat out performance, even these kinds of simulation systems are still better done in FORTRAN. It's just that unlike fluid dynamics models, the models in most DTS's change over the lifetime of the program (just as the core algorithms don't), so maintainability is more of an issue.
That is all.
If OOP seems like overkill for small and specific engineering problems but you're facing the problem of maintaining and enhancing a large procedural code base, then there's a nice solution.
One of the most efficient ways of tackling this kind of problem is to keep your existing investment in procedural code but wrap it using a scripting language - preferably something like Python. Python has enough classical OO built in to keep your front end clean and maintainable but interfaces easily to programs written in C or C++. There are also tools to do this wrapping automatically for you. Your engineering data and equations will just look like normal Python objects but of course run at the same speed - minus a small amount of call overhead.
Example: after experimenting with Ken Perlin's source code for the 1, 2 and 3d noise which now bears his name, I found that the code was becoming hard to maintain and enhance without changing bits all over the place. Messy. Rewriting it all in Python or C++ would have been a pain because it was optimised C with lots of inline Asm. The solution was to keep the existing code base doing what it did best - calculating perlin noise functions at full speed - and just create a Python wrapper for the interface functions. In the end I got the best of both worlds - Python kept the frontend testbed clean and easy to maintain, the back-end code was unchanged. Time taken to convert the lib - a couple of hours reading the Extending and Embedding part of the Python manual.
Try it - you might like it. I don't know if Python talks to Fortran though.
--- Hot Shot City is particularly good.
One of the most common misconceptions in the industry is that C++ is 'an OOP language.' For that matter, it is similiarly incorrect to label C a procedural language. Paradigms like Object Oriented or Procedural are exactly that
The first C++ compilers were merely front ends for C ones, which took C++ constructs and generated C code, which was then compiled and linked into an executable. It is true that C++ was developed to assist in making OOP constructs with clarity and ease (let's not argue the success or lack therof here, please.) Still, nothing stops one from OOP modelling in Assembly Language and procedural was always openly supported by Bjarne Stroustrup when he invented C++.
You call the problem on the head when you say "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." When your problems lend themselves to procedural solutions then you want to think about them that way, just as when your problems lend themselves to Object Oriented models, you want to model them that way.
The right tool for the right job. If you want to implemet a Fast Fourier Transform you want to look at it procedurally. If you want to model a Robot, in which thousands of components performing those FFTs interact, you probably want to take your procedural code, wrap it in some Object Oriented code, and get your model.
OOP and Procedural are complementary analytical methods, not competitors. It is an abuse on the part of any software engineer to view or discuss them otherwise!
Guns don't kill people; Physics kills people! - John Lithgow as Dick Solomon on Third Rock From The Sun
Amazing it took as long as it did for somebody to state that OOP existis in FORTRAN.
I have actually written a couple of optics/engineering type programs for work using OOP.
1) A data modelling program. The program reads large data files and creates an object using each one as input. The object type is based on the needed curvefitting/modelling algorithm for the given data set. The advantage of using OOP here is that I am currently developing new curvefit algorithms and data models, and the object based structure of the program allows the main program to remain essentially unchanged no matter how many different models are included in the program. It has allowed me to do some detailed comparisons between the accuracy of the various models. Procedure/Function based programming would do just fine, but OO based allows me a bit more flexibility.
2) A large scale development project that I hope to spend more time on in the future: A software package allowing one to develop photolithographic masks. In a certain sense it would have some limited CAD capabilities, but would allow one to work with a number of different masks (essentially images to be etched into glass or metal substrates later on) and mask types. An OO model is ideal in this situation since I could set up a "Mask" base type and have derived classes for each of the different lithographic mask representations. Again, this lets the main program work with essentially one type of data, even though it may represent any number of different things. And I can add as many different mask types as I need too.
Don't know if either of those made much sense, but the point is, OOP can be useful depending on your application. Usually you can make do just fine without it, but it can dramatically simplify certain tasks.
Many OO books contain an example of how to model the car in OO. The "Car" object is a container of Engine, Transmission, etc. The engine can be of different types like V6, V8, Turbo-charged etc..
How use inheritance to model that. OO is comes in obvious when you have to do lot of simulation work in your engineering field. I find your question ironical because I frequently read the analogy of the software components and engineering components (like IC, nut, bold) and having standard interfaces between the components so the COTS software components can be assembled together just like the hardware components. To model, algorithms use the "Template" pattern from GoF pattern book. In fact OO would be very ideal. Only field where I don't see OO to be very helpful as you mention in your question is in the field of Mathematics. Well, I guess even there is a standard example like Complex numbers and operator overloading. OO is good. I like it. I see no reason why anyone want to program in procedural paradigm.
It's not OOP that saves the day, but the OO Analysis and Design. You can't just write code using an OO language and expect every problem to just solve itself unless you have a thorough understanding of the problem (discovered during the Analysis phase) and a sound strategy for solving
the problem (created during the Design phase).
In walking, just walk. In sitting, just sit. Above all, don't wobble.
-- Yun-Men
"Let's just say you'll have a hard time finding a senior engineer who knows C++, and an equally hard time finding one who doesn't know ForTran. And, often, the senior engineers are among your better resources."
Well-phrased. Yes, older engineers (and scientists) are better versed in FORTRAN. Of course, by "FORTRAN" we really mean that these folks know FORTRAN 77, and you have to ask yourself--do you really want to begin any new coding project in a language as primitive as F77? It's a bit like saying: "we're going to code in BASIC, because that's what the staff knows." Sure, you gain in developer training, but you lose many times more in code management, reuse and maintenance. And what about newer FORTRANs, like F90? Well, if you're going to retrain on that rats-nest of a language, you might as well just stick with the industry-standard rats-nest, and use C++. For an F77 programmer, the learning curve will be the same.
Another funny thing is, most truly senior engineers and scientists aren't the ones writing code anymore. So it becomes even more absurd to suggest that new code should be developed in a language they understand. Indeed, develop in a language the new engineers know, because they're the ones who will be maintaining it well after Dr. Cranky is eating tapioca in the nursing home, babbling on about COMMON blocks, hollerith strings, and how "back in the good old days, all we had was GOTO, and dammit, we LIKED it!"
Let's try not to let fact interfere with our speculation here, OK?
To carry on your car analogy -- yes, OOP is good for modeling the interactions between cars, but first you have to model _one_ car. And this, depending on the level of detail you are looking for, may be simultaneously too simple and too calculation-intensive to fit well into a general purpose OO language. (Simula is a special case -- since it has the required math built-in, it might be competitive.)
To get to something like the problems he was concerned with, let's say you drill down until you need a complete simulation of the air/fuel mixture flow through the intake manifold. "Objects" are irrelevant at this point, all you are concerned with now are many little chunks of gas ("cells"), represented by numbers in a big multi-dimensional array, and related by a massive set of partial differential equations. There are going to be billions or even trillions of floating point operations, taking minutes to hours to complete no matter how efficiently programmed.
You need a language in which you can easily input those equations, and which will very, very quickly go through all the calculations on each cell in that array. FORTRAN excels at this sort of calculation, basically because the language is so unsophisticated that the compiler can do great optimizations. The one issue is that FORTRAN natively understands only basic algebra. The calculus and the process of turning a continuous set of equations into discrete cells of air and steps in time has to be programmed in; there are libraries you can call, but you've got to understand how to pick the right library function and to translate the problem for it.
The second choice is to go to a specialized simulation language like Simula, where the compiler understands discrete integration operations, so you feed in the equations and the geometry and it picks a method of solving it. It might not be the best method, but there's a pretty good chance you'll get usable results without doing a whole lot of work yourself. It's unlikely to run anywhere near as fast as a properly tuned FORTRAN program, but you'll usually get the first-run results much quicker than the FORTRAN could be written. But if you need to try 10,00 different configurations, and FORTRAN runs each one in 2 minutes while other languages take 3 or 4 minutes each...
Though this was very cool, and actually worked, the conclusion at the end of the project was that a strict OO implementation was much less efficient than a traditional, procedural approach. I assume that this finding has probably been repeated across other areas of engineering and modelling as well.
One way of looking at software engineering divides it into levels of abstraction at which people work. In the traditional view, engineering proceeded by starting at the highest level and proceeding in a orderly manner towards code. We're coming to realise that approach is wrong, but the levels of abstraction still exist. You can use OO at all these levels, by modelling things in terms of classes.
At the highest level, often called analysis, classes, objects and the relationships between them should correspond to concepts in the problem domain. Implementation issues should not come into it. An analysis model should end up representing the system as the user thinks about it.
At the code level, objects are indeed methods combined with data, but while the analysis model won't have captured all, or even most, of the code you end up writing, the concepts in it should still be present in the code.
People still teach that ? I give OO training courses, and we mock that stuff mercilessly. Thats just a (bad) way of doing analysis. If you try to go straight from that to code, you'll end up with a poor, naive implementation, probably with all the "real work" done by one method and all the OO superstructure looking like useless fussiness. Its that kind of thing puts people off OO.
It's not so much about managing engineering problems as it is about managing engineers. Imagine you have two engineers with big egos. If you were to try to get them to work together on the same piece of code, they would probably spend all their time fighting. OOP lets you separate the problem into smaller 'objects' that each can work on. You could do the same thing with function and procedure definitions, OOP just provides a more formalized way to accomplish the separation. This would not totally solve your problem, but it would help.
I know, I know, it's slightly offtopic... sorry 'bout that.
"Anything is better than IE, and you can quote me on that." -- Wil Wheaton.
For those too busy fawning over OOP here is some help:
http://www.embedded.com/1999/9908/9908feat1.htm
And if you're a bit too enamored with the C++ new operator try this:
http://www.scs.cs.nyu.edu/~dm/c++-new.html
And to see how STL guy A. Stepanov feels about OOP proponents see this:
http://www.stlport.org/resources/StepanovUSA.html
Although I have met quite a few talented (and effective) practicioners of OOP, much more often I run into hyper-political, resume-stacking, rabid and incompetent advocates of OOP. Mostly, they never finish what they start.
Who cares what Grady Booch and his two quack partners say anyway? I mean besides the rabid advocates...
But there's a bit more to it than that. OO is just a way of acheiving well designed software. It has its failings, but its the best I know of. So what does it mean for software to be well designed ? Well (and this goes back much further than OO), it should consist of loosely coupled components, each of which is highly cohesive internally. Each component should hide a small group of closely related design decisions (ideally one) so that the rest of the system can be built independent of its details.
In the end, OO is not about being able to write better algorithms, but about how long your software will last, of how much value it will be to its users, and how much grief it will cause its maintainers. These are principally concerns in commercial environments (where value==price and hassle==cost), but they're relevant everywhere software is written and used more than once.
Now, looking at your problems and your question, here are some random thoughts. I'll be the first to admit to not having the faintest idea what most of those problems are, so some of this is about the peripheral aspects.
Firstly, all OO language in common use are procedural. The opposite of procedural is declarative, but there are very few declarative languages and they are principally of academic interest. In the end, code in OO languages is just like code in C, Pascal or Fortran.
So, thinking about your algorithms: does the algorithm always operate on the same domain ? For instance, do your fluid dynamics always model fluids ? or might it be modelling some complex economic system ? If so, you can split the domain off from the algorithm uding the techniques off OO, by representing it as a set of abstract classes or interfaces. Of course, this is only of interest if the algorithm is part of a larger system with some purpose, and not just an academic toy.
Similarly, are there several algorithms for solving a problem ? or can the algorithm be tuned differently. I know this is the case with some stochastic methods (I used to work on a system that used simulated annealing for place and route - in Smalltalk). In these cases the abstract properties of the algorithm can be encapsulated in an abstract base class, and concrete specialisations used to offer a choise of implementations.
I hope that helps somewhat. Just one thing to bare in mind: beware of C++. Java is unnfortunately inappropriate for heavy numerical lifting, but C++ contains many pitfalls for the unwary. Its worth learning a more rigorously OO language - like Java - and then going back to C++.
Excellent book on OO principles as well as applying them to diverse engineering problems. Includes special emphasis for FORTRAN programmers, as well as how to interface C++ with FORTRAN libs.
"Scientific & Engineering C++", Barton & Nackman, ISBN 0201533936
Enjoy.
Too funny!
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.
Perhaps I can help. A few years ago, I ran a team to write a large scientific visualization program called SciAn, which was all object-oriented. We did stuff like this. Although most of the time the calculation was saved in a file that we read, we also did calculations within it, sometimes using distributed objects.
One problem you may have been having is that nearly all O-O books are crappy and ignore the real power of objects. Here's a heuristic: when a book talks more about "classes" than it does about "objects," throw it away. Vigorously. Anyway, here's how we did it, and you can maybe decide how you could do it.
Take the case of a grid. (Please!) Just to be simple, first let's take 2-D. The points may be connected with edges to form either a non-structured grid or a structured grid. A non-structured grid may be triangular, such a grid may also be a Delauney triangulation. Or it may be a structured grid, in which case it might be a rectilinear grid. You might want to have the grid denser near the boundaries, I called these "separable" grids because I couldn't think of a better word. Or the grid might be curvilinear, wrapped around, say, an airfoil.
Immediately, an object structure emerges, fairly cleanly, like this:
Grid
Structured Grid
Curvilinear Grid
Rectilinear Grid
Separable Grid
Regular Grid
Non-Structured Grid
Triangular Grid
Delauney Triangulation
This probably isn't the hierarchy that I used, exactly, because we had a lot more different kinds. We had multiple grids linked together, data in separate objects linked to the grids, N-dimensional grids with M-dimensional data, time-dependence, etc. But you get the idea.
Would you want to use a bunch of little objects to implement your Navier-Stokes calculations or whatever? No, of course not. Put them as methods within the object.
Once you do this, the objects make sense. You might have a method to initialize the data and a method to calculate one step in the calculation. Another method might be used to switch between, say, a simple projection integration and second-order Runge-Kutta. Call setReynoldsNumber(double x) and see what happens. You might have a method to construct another grid that contains the gradients. You might have a method that resamples any grid as a regular grid. You might have a method that constructs a Delauney triangulation of a point cloud. You might construct an M-1-dimensional slice from an M-dimensional grid, or return a snapshot of a time-dependent data set. Different implementations of these methods may live at different points in the hierarchy.
At our height, we supported about 20 different file formats for the most diverse kinds of data you can imagine: HDF files, protein structure files, EEG recordings, particle traces, for meteorology, chemistry, quantum chemistry, economics, high-energy physics, QCD, you name it, and internally, all the datasets were in the same kind of object and behaved largely the same. As a joke, I deformed an EEG brain by a mountain terrain field. It took about five minutes.
Alas, the research institute went defunct, and now I have to spend my time writing financial and HR reports. On the other hand, I make a lot more money.
Beyond this, you can think in terms of having multiple objects interact. Nearly all of the big stuff that we did involved interactions between grid, dataset, and visualization objects, but there were many others. Want to run your simulation with an isothermal top instead of an adiabatic one? Don't rewrite the equation solver. Slap an isothermal cap on one face of your grid; it knows to clamp the temperatures at each time step. Or whatever: invent your own. Once you start thinking of these things in terms of objects, there's a lot that can be done.
The guy who said that your problems are too small and specialized to benefit from O-O actually had a point. I'm not saying that they are, of course. But if your mindset is that once you have an array of values then you're totally done and eveything's known and you just throw it at a postprocessing package called Graduate Student 3.0, collect your Nobel prize and retire, then there won't be much use for O-O programming. Alas, I've worked with a lot of scientists who thought this way. However, if you work on several problems that are both similar and different, a carefully designed (and redesigned when it doesn't work--don't laugh; it happens) object framework can help you put together something synchronistic that builds up over time and really does save work.
Certainly if you don't try to write a system like that, but just use it to get the idea, then its harmless. I was particularly worried that the original poster mentioned it in the context of being taught Java, though. Unless it was a "your first language" course, in which case he probably should not have attended.
One course I teach is basically "OO for beginners", which is intended for new graduate recruits (not CS grads), and for non-engineerings managers. In that, we get over the brain friction with a role playing exercise that involves people first simulating a business sytem by passing bits of paper around, and then simulating the same system as an OO system, with each person playing an object, by passing messages around. After that, they seem to get the idea of objects, messages and most importantly, classes and polymorphism, quite well.
I have had the pleasure of working on and using an OO software package at an engineering consulting firm for a number of years. We do a lot of system analysis, namely power cycles, so the software is used for modeling a network of engineering processes. We were able to make use of an OOD that brought several advantages:
:)
- Generic procedures define I/O, curve implementation, etc at a high level and are inherited to the process specific objects.
- Easy extensibility. It has been very easy to add new processes to the model's library by focusing the attention on writing code for a particular object procedure. You don't need to be an expert on OO and all of the other object functionality is already taken care of. Makes us engineers think we are real hackers.
I wish I could share it with you but this is an internal tool and a closed shop. I just wanted to share a success story for using OOP on an engineering problem.
When it comes down to coding or problem solving, who really cares. But when you need to design a maintainable software product and hope for some code reuse, OO is the best. Functional has worked and will continue to work but OO is better. The benefits of OO are not obvious when coding but are emerge in design. That is a down side to some who would prefer to just start hacking and forget design.
Civil Engineer
Mechanical Engineer
Software Engineer
What do the above have in common?
They are all the application of proven scientific methods to produce a result that achieves some objective and works safely within specified limits&criteria with repeatable reproducable results.
Civil Engineers build bridges & buildings
Mechanical Engineers build turbines & engines
Software Engineers build software for nuclear reactors and apollo moon missions.
Software Programmers build software for space probes that crash into mars because of no formal validation.
Engineers dont/cannot afford to make mistakes.
Lives are at stake.
---
Now, what does all this have to do with OO:
----
The difference between a software developer and a software engineer is that an engineer will have some formal process and paradigms to ensure that the process of development is safe and that the result has no alternative side effects.
Object Orientation makes LARGE systems so much more architecturally flexible entirely due to formal reusability and potential reflection/descovery.
Once objects have been engineered to some formal generalized state, they should be reusable across a business and the customized subclasses should be the implementation of all custom business logic.
In addition, an object is not like a 'library' in that while two of the same libraries may not be linked to a program, a program may have references to the two live instances of an object which are the same, except in version and revision (theoretically it should work this way, but i think only the latest J2EE stuff is capable of this).
In addition, OO legacy goal is to invisibly extend the system, while not breaking the contract on which binds process, and provide support for current methodologies on legacy systems... this is not successfull.
-=-
OO does not calculate information quicker.
In fact, it will definately be slower if you make everything, and every process an object.
The only possibly good effect that OO will have in a procedural calculation is version control and the magnification and seperation of abstract mechanics.
Think raycasting, think process transformation, think mechanical dials, think resources in a 'machine', think realtime execution, think of more than one analysis that one wants to work with within the same machine framework.
Importantly, Objects are expected to have a contract which they enforce. Breach of this contract should be impossible.
When it comes to raw processing such as:
for each step
for particle 1 to google do
interact field
push particle
end
calculate field
end
There are no major architectural components.
Sure, you could use OO for datatype abstraction, but a library is just as sufficient.
One important thing to rememeber is that a scientific tool does not need to be robust. It's designed for a specific purpose, calculate an answer. One does not care about the instance of implementation, or the process of implementation, but only, that the answer is correct.
You throw the program away after you have the answer.
Something like mathematica or IDL, which are both meta-scientific tools that aid in the calculation of calculations will use objects extensively. They have procedural/functional syntax to solve problems. Using the tools are functional.
You throw the program away after you have the answer; so WHY use OO ? There is no real reason. You can use OO libraries in your procedural process. You can use OO in designing an application that executes your procedural process, but unless you're process is massive, I wouldnt use OO for the implementation of the procedural process.
Infact, i'd put the entire procedural process within one object.
class myanalysis {
Graph calculate(int x, int y);
}
Calculate is clearly procedural.
The output, eg: Graph, and the means for viewing the result may be in the application domain, in which case OO is used extensively.
EG: windowing components and visual graphing components.
But you're analysis is very much procedural.
Dont foolyourself, use the best tool/paradigm for the job. If its perl, php, parot, prolog, lisp, visual basic or Java then use it.
=== sidenote ===
A Software Engineer is not currently a formalized profession, but I do believe that there is some work going on to make this so. Those that have the understanding on what it takes for a process to be formally proved to work, and have the means to implement the process, are Software Engineers.
For those wondering: Most programmers are just software developers, the [software] engineer is just a tag aquired to sound good. This (formal definition of a software engineer and the means to aquire said title) may have changed at the time of me writing this.
Yes, electronics engineers write software in electronics components, no, they arnt software engineers, but they are (commonly) programmers.
with formal acreditation... unless i'm mistaken.
=== sidenote 2 ====
Formal Object Reuse on a massive scale has not lived up to the hype'ed expectations.
Components dont just 'fit' together as easily as one would like. This makes the formal process very difficult. Java makes this easier in terms of a formal, well guided implementation, but there are better formal languages out there, unfortunately some are only research projects or have lacked the mainstream support.
Taking two components: one from vendor A, one from vendor B, do not currently 'just work' without some intermediate interface marshalling... a goal of current thinkers is to solve this problem. Hence reflection, beans, visual components. Important component/process such as the various banking processes and company ledgers always need to be customized and information is not usually consistent between different implementations of ledgers and supporting APIs, thus one cannot just swap ledger components from two accounting packages as they're too different, on an implementation level.
Lots of problems.
-Tim
Cheers,
A FORTRAN advocate
Currently I'm finalizing an Excel version of what will be a program that my co. will be producing later this year. Began in excel as simple method of rapidly producing reports with inputs, and over the last year has turned into a 15 MB ssheet with a 4 MB report generated. Main reason we've kept it in excel all this time is that everyone in our office can work with excel and can easily comment and change formulas (except where I've had to use VBA functions to simplify or do multiple iterations w/o using the Solver func). What this does is take a 12 month history of data and run nine different simulations based on input data and produces an overall project cost, operating cost, and financial outlook for 15 years. About 6 man-years of work in the making and still more to go to make the final standalone program. This year we'll port it to VC/VB. Would have started sooner but last year accounting wouldn't pay for the compiler. Main thing I've wanted to be able to do is the database functions of VC++/VB as every time we've come up with a new feature I've had to redesign our layout and output.
I saw a talk presented by the scientific computation group at the University of Waterloo about 5 years ago on the advantages of implementing a fluid flow solver in C++ vs. FORTRAN.
The conclusion was that you lost a tiny bit of performance (about 3%) but your code maintainability went *way* up. The example presented was a simple 2D navier-stokes solver, and adding a new element type to the C++ version took a few hours of effort, but adding a new element type to the FORTRAN version took a couple of days.
on their webpage they say that they are now doing all of their scientific computation work in C++
It is very easy to write poorly performing code in an OO language. Everything from complex copy constructors to unexpected copies on function calls can both exact a large amount of cycles to perform and destroy your cache working sets. I have seen very fast, very efficient turbomachinery simulation code writen in C++, but it was written with *great* care and knowledge. Unfortunately, programmers who are not aware of many of the pitfalls of C++ (usually those who migrate from one of the various FORTRAN flavors or who simply learn C++ from one of the books on their own) can easily write a program that is a complete failure performance wise.
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.
My first experience with something like object oriented program was back in the 60's using SIMSCRIPT, a simulation language similar to SIMULA. The language was actually a preprocessor to a Fortran compiler. The code generation idioms used in the translation were very interesting and could be used as a way of writing object oriented Fortran.
I'm not sure whether SIMSCRIPT came before or after SIMULA but I believe they were developed around the same time with similar ideas in mind. In SIMSCRIPT objects were called "entities" and classes were called "entity types". Entities had most of the features of what we now call objects. They had attributes, behaviours, agregation and a limited form of inheritance. There was a particular base class of entities called event-notices that were used wre used to schedule events in simulated time.
The power of this object orient approach to simulation comes into focus on problems where the behaviour of individual entities is well understood but consequences of interaction between entities boggles the mind. You write subroutines to model the response of each entity type to each event type, set some initial conditions, and let it rip. There are a significant number of engineering problems that fit this pattern.
This type of simulation can easily be written in C++, or any language that supports classes, by writing a simple scheduler that sequences event objects in simulated time.
Some examples are useful to illustrate the point. In each cases, it is relatively easy to imagine modelling the behaviour of each individual class in spite of the fact that the overall problem seems daunting. (These are actual problems that have been simulated with this technique.)
Simulation of an aircraft running a gauntlet of air defences. Classes: missiles, launch events, flares, manuever events, tracking radars, jammers, etc
Network traffic simulation. Classes: packets, routers, transmission lines, store events, forward events etc
Simulation of mutual interference among cell phone users. Classes: Cell phones, Base stations, calls, start of call events, end of call events etc
Disaster casualty evacuation. Classes: ambulences, dead, wounded, ambulence arrival events, street obstructions etc
is Matlab! We're not computer scientists, Matlab is an engineer's tool Its strengths: 1. matrix math, nothing beats it 2. numerical analysis 3. nonlinear systems if you need a gui, it has built in GUI features, and if you have functions built in other languages, it has modules for C, C++, java, fortran and if it isn't fast enough for you, then you probably could write the whole thing in C/ C++ only if you needed a GUI it's the best tool for college engineers, got me through EE just my 2 cents
That's why you've never seen a good, useful, large-scale, general-purpose application written in a language that forces OO on everything (like Java). It just falls on its face for a small, but noticable subset of the CS problems out there.
For engineering and scientific work, nothing beats a functional language like Scheme, if you have the time to get over the learning curve. If not, traditional structured programming does well (Fortran, C, Basic, Pascal, etc.)
I think we need another compiled language with Python's syntax. I started using Python again after using Perl and C++ for a while, and I found it incredibly clean and easy to use. It's just so clean compared to C++.
I'm just going to add another "Dead on" response.
I'm an OOP fanatic myself. OOP is a wonderful tool for most tasks. The article author's tasks however aren't among those.
A good example of his issues is a Mandelbrot program. If you want code to solve a single problem, like rendering a Mandelbrot set, OOP is not going to give you any advantage. The problem is specific to matching a set of input data (the set boundaries) to its corresponding result (the set). If you wrote this using OO, the meat of the software would be a single Mandelbrot object. Everything else would be necessary fluff for display and handling mouse clicks.
However, if you needed something that would render Mandelbrots, Julias, and Recursive Serpentine something-or-others then OOP would be an appropriate tool. The fractal itself is an object and the higher level managing code doesn't need to know anything about the fractal objects except that they are derivatives of a base fractal class and therefore support an intelligent set of generic methods.
My experience with engineering software written in Fortran has been that the program is tightly coupled to one narrowly scoped problem (like the Mandelbrot example) and doesn't lend itself to an OOP implementation.
Education is a better safeguard of liberty than a standing army.
Edward Everett (1794 - 1865)
there is a very nice OO program that has just been released under GPL by EDF (électricité de france) written in Python & Fortran to solve engineering problems (finite element modeling ) that you might want to check as an example
:-)
http://www.code-aster.org/
(the doc is in french though !)
an other good place for scientific applications under linux is:
http://sal.KachinaTech.com
check it out
& happy new year
However this is a man that writes in Fortran 90. And Fortran 90 does contain pointers (very ugly syntax) and OO stuff if he would ever need to use them. (I would complain about the ugliness of his code too, but I know my shit stunk too when the deadline was coming in)
On the other hand I have met a professor that prefered C++ because he had many projects and they all very large. He wanted maximum code reuse and all self contained pieces.
And also it is obvious that classes are extremely valuable for other types of math than basic arithmetic like linear algebra and some abstract algegras.
I myself prefer C for its speed/simplicity/size and always having a compiler. I generally make very ugly use of inlines, macros, and global variables to cut code size down without having classes. For bad example
int e
#define VECTOR(X) for(e=0;e<3;++e) {X;}
(and then unroll the loops) which applies some statement X component wise, so I could add vectors like VECTOR(a[e]+b[e]). Yes, I know it is ugly, but damnit I have had code that took a month on 9 computers and I just didn't have any extra time for the performance hit of C++.
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?
Sure. Here's the quote from An Interview with A. Stepanov:
STL is not object oriented. I think that object orientedness is almost as much of a hoax as Artificial Intelligence. I have yet to see an interesting piece of code that comes from these OO people... I find OOP technically unsound. It attempts to decompose the world in terms of interfaces that vary on a single type. To deal with the real problems you need multisorted algebras - families of interfaces that span multiple types. I find OOP philosophically unsound. It claims that everything is an object. Even if it is true it is not very interesting - saying that everything is an object is saying nothing at all. I find OOP methodologically wrong. It starts with classes. It is as if mathematicians would start with axioms. You do not start with axioms - you start with proofs. Only when you have found a bunch of related proofs, can you come up with axioms. You end with axioms. The same thing is true in programming: you have to start with interesting algorithms. Only when you understand them well, can you come up with an interface that will let them work.
I am originally a mechanical egngineer and have some expereince with finite element/finite difference work . The short answer is that no OO techniques, don't apply to many engineering tasks. I can remeber not that long ago that entering a bookstore or technical bookstore there would be three of so book cases covering 20-40 languages, now there is one bookcase of C/C++, one of java and half a bookcase of other which seems to mean scripting languages more that anything else like Perl,Tck, Ruby etc... . Those 20-40 languages each had a specialty .....
Fortran for math/engineering
C for systems programming
Prolog for expert systems
LISP for AI
Snobol for text processing
Cobol for business
Pascal for learning
Ada for formal systems
etc
Now the answer is always C/C++/Java, C is realitively general purpose, but C++ is generally 20% slower and larger than a equivalent C application. Java is easier, but I find it strange reasoning that garbage collection is prefered, isn't writing your application correctly a better solution than having the computer clean up after you, kinda like a teenager not putting thier dirty underwear in the hamper becasue Mum will do it eventually. Assembly is always going to be fastest, but the hardest to debug/maintain, the OO languages make life easier, but all the abstraction causes significant speed loss and code bloat. I keep on hearing poeple say that code size and effiency don't matter as thier machine is fast enough and memory is cheap, but Intel is selling faster processors because of inefficient code and people are always adding more memory. C++/Java are fine and are the best solution to some problems, just not all problems. The market is contracting to the point that non C++/Java compilers are rare, and the options will not exist. SW people seem to spend an inordinate amount of time debugging and this is the area that would have the biggest payoff, but heavily typed languages haven't seem much sucess in the market. I spent 6 years, working in Occam a parallel processing language, that have very tight rules and was a formal language, such that there was only one possible solution to given code. We always used to say that in 'C' code, if you got your code to compile you were 20% done, and required the next 80% for debug, while Occam compilation was more painful, getting it to compile you were 80% done, that sort of help makes you more productive than anything else. People hated the compiler complaining about seeming insignificant errors, but the compiler was finding mistakes and helping me rather than hoping that I knew what I was doing. This helped me build 80 processor sonar systems in 11 months, well before any beowolf cluster.
This post is dead on, but unfortunately too far down the post list to be seen by anyone.
/.
OOP vs. Procedural there's an original question.
Let's see what else has been up on Ask Slashdot lately:
Satellite Command Security? -- Security through Obscurity, definitely a new one for
Handling Discrimination in the IT Workplace? -- This one was a guy claiming he was being discriminated for his age, and then explaining how this happens from everyone he meets, after a period of time on the job. Yeah its everyone but him.
MS Office for OSX? Why not for Unix as Well? -- Troll the unix crowd with M$ and Apple in the same sentence.
Is Assembler Still Relevant? -- I am sure that this was a stunner to most, but to the few in the dark, an NT sys admin was arguing that not knowing computer architecture didn't hinder his job. Really useful topic, could this be any more subjective?
Fast Track to a CS Degree? -- This one was good. A self taught programmer asking where he could pick up a degree in a year. That wasn't a troll honest.
Responsible Handling of Billing Information? -- This was my favorite, a guy picks up an independent cowboy hack job. In over his head, he turns to slashdot for advice on how to architect the application that some poor schmucks are too ignorant, or too cheap to realize how much it is really going to cost them.
Its a shame, because every once in a while there are questions that pertain to more than just the poster and the prima-donnas who feel the need to show off what they know in response to subjective and often religious topics.
Cliff, get a grip man, its starting to look like the National Enquirer or Jerry Springer around here.
(Mod me down. who cares. It won't improve the quality around here either way)
We are agents of the free
It will give you the best of both worlds - www.wolframresearch.com PS I don't work for them, just think its a great tool an has a very powerful multi-paradigm programming language
Aspect Oriented Programming.
I understand that google has good notes on this.
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.
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.
1) You are doing a numeric simulation/computation that involves a lot of state that ends up as global data structures. A class is a nifty way of bundling that state together with the operators on that state.
2) Model-view-controller pattern allows a clean separation between model (your platform-independent engineering calculations) and view (your GUI data visualization).
3) You have an optimization method (conjugate-gradient, Newton-Raphson) that you want to make generic. Making your function an abstract class with a virtual EvalFunction method allows you to plug-in any function into your optimizer -- this is run-time generacity -- templates are the compile time counterpart.
4) (mentioned by other posters) -- STL or STL style classes for collections -- application to sparse matrices, etc.
Glad to read about your applications! Of course, you are hardly alone in such endeavors! Half of the October 2001 issue of the Communications of the ACM was dedicated to High Performance Computing using Java. For a more immediate and applied example of using O-O methods for engineering type problems, have a look at the excellent recent book Object-Oriented Implementation of Numerical Methods: An Introduction using Java and Smalltalk by Dibier H. Bessett (Academic Press, 2001). I am sure it isn't too hard to find lots of other examples.
Look at "The Incredible Machine" by Sierra.
A bit old but a very fine example of object
orientation applied to physics.
Not quite. When you yawn, the hairs inside your ear which resonate to give you the impression of sound flex. Their resonant frequency is briefly altered. This results in you perceiving a higher tone than is being played. There is no time-dilation.
You do not need OOM because he has a lot
of equations that have to apply to different data.
This is the opposite of what OOM is designed to do.
OOM takes data as the central concept, while you
need procedures to be the central concept. Luckily
C++ was designed to be a multi-paradigmed Language.
It is actually among the best language for doing
generic programming. Maybe Simula can also be
as good. If you have read "Design and Evolution of
C++" you would know that C++ was inspired by Simula
not C. C was taken as the base because it was the
most popular of the languages.
STL of C++ is an example of Generic Programming.
If you are going to use C++ for your work, you
could start with a book on the design of STL. I
couldn't recommend you one because I haven't really
done any STL programming.
Not really. You might be doing what some OO guys call "object-based" programming (and other non-OO guys call myriad other things), but it's not really OOP. OOP implies rather more than just using your own data types.
If you disagree, post your argument. (-1, Overrated) isn't your personal censorship tool for views you don't like.
I'm sorry, but anyone who claims C++ has "too much overhead" over C doesn't know what they're talking about.
There is no reason that this must be the case. C++ strongly adheres to the "zero overhead principle", which says that if you don't use a feature, you shouldn't pay for it. This is directly relevant to things like virtuality (which is optional in C++) and exceptions.
The only major difference between C++ and C code to do the same thing is the quality of the compiler. C compilers used to have a big headstart in the optimisation stakes, but this is no longer the case (at least, not nearly as much).
And before anyone replies and claims that virtual functions, exceptions and such are all horribly slow, just stop and think what you'd have to do to get the same results in C, and tell me how that's going to be faster than a highly optimised, compiler-generated version of the same thing. :-)
If you disagree, post your argument. (-1, Overrated) isn't your personal censorship tool for views you don't like.
...because engineering and mathematics problems are almost certain to need deeply-nested loops eventually. Alas, memory allocators (for C++, anyway) are still painfully slow, and because of this, the speed of your program will be inversely proportional to the level of granularity to which you OO-ify your problem. We all know how slow simple algorithms can be if you have an object for an 'integer'...that gets new'd and deleted a zillion times all over the program.
Not in some cases. Generic programming in C++ would be heavily limited without it, and some of it is used implicitly.
If you disagree, post your argument. (-1, Overrated) isn't your personal censorship tool for views you don't like.
The simple answer is yes. In fact C++ is a very powerful tool for scientific programming. Solid scientific programming rests on structures such as abstract data types (i.e., containers) such as multi-dimensional arrays, maps, linked-lists, trees; concepts such as common structure; data encapsulation, templates, etc. One book that I would recommend is Scientific and Engineering C++: An Introduction With Advanced Techniques and Examples by John J. Barton, Lee R. Nackman ISBN: 0201533936, 1994. This is one of the best and literally breath-taking books on scientific C++ programming; the chapters on Arrays and Templates are worth the price alone. Do not be fooled by the publication date of 1994, the template concepts illustrate are only now coming into use. Some of the material is advanced, however, the books web site allows down loading of all example source code. Lorenz H. Menke, Jr. Lockheed-Martin
You have heard enough from those brain washed academics who had more theory then practise, now try the following:
http://www.embedded.com/1999/9908/9908feat1.htm
...here we are at work, seven years after starting a major project in C++, with about 50 man-years of development on the project behind us, and OO is still working very well indeed. For comparison, we now match the previous incarnation of software (written in C) on almost all features, but that took nearly five times as long to write, and wound up so unmaintainable that we've come in to clean up. Looking at the spaghetti they made out of a complex design, and the number of bugs they never did manage to fix, and comparing it with the nice OO framework we have in place, it's easy to see why, too.
This is an instrument control application, BTW, with a lot of mathematical analysis of data obtained through the instruments and a pretty powerful GUI/macro language on the front end. The use of OO has allowed us to design careful frameworks for the IC, maths and GUI, into which new components plug. One of the major claimed benefits of OO -- the ability to have code you haven't even written yet work with what you're writing now -- has paid off for us big-time.
I agree with some of Stepanov's points; there are indeed some fundamental flaws in a pure OO methodology. However, being pragmatic, they are relatively insignificant and you can work around them. If you choose a mixed-paradigm language such as C++, several of them immediately disappear anyway.
If you disagree, post your argument. (-1, Overrated) isn't your personal censorship tool for views you don't like.
Yep, some of us are still slogging on, writing our MLOC projects in C++; there's no reason for us not to.
The thing is, we use C++ in a smart way. You keep the low level stuff at low levels, instead of polluting your whole code base with it. That immediately kills most anti-C++ "it's not safe" arguments. You then write mid level building blocks from the low level stuff, and you write high level code using those building blocks. Most of the code we write today uses concepts every bit as high level as most other mainstream languages, often more so, because we use the tools for abstraction that C++ provides appropriately.
IME, the reason many people give up on C++, and switch to "higher level" languages, is that they've never really understood the abstraction tools in C++, and have always just used it as a "better C" with a few objects around in a badly designed hierarchy. Our friends over at MS showed the world how not to do it when they designed (and I use the term loosely) the MFC, which is a thin wrapper around C code, and not a proper OO framework at all.
If a few more programmers went out and learned their craft, instead of trying to use a powerful tool like C++ without learning the ropes first (but it's OK, they program C, so they don't need any more training to know C++) then fewer of them would decide that "C++ sux" and run away.
Of course, the target audience for C++ is, and really always has been, the programmers at the top who are prepared to make the effort to learn to use it. Those who do, reap the rewards, and find many "higher level languages" horribly limited in comparison.
Just MHO, of course, but I've certainly seen it often enough to be sure of that opinion.
If you disagree, post your argument. (-1, Overrated) isn't your personal censorship tool for views you don't like.
...because you're hurting me. ;-)
I think you just single-handedly proved the value of OO features in the language itself. The difference in readability between the previous C++, and your C implementation is, frankly, striking.
-- Mike Greaves
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.
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.
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.
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++.
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?
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.
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.
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?
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.
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.
*blush* I went home and read my copy of Booch's (well, the beginning), and Budd's "Object-Oriented Programming".
:)
I now remember the existence of object-based systems. Forgive me for saying you were wrong. You were not. Now I even understand (again) why you stated OOP != encapsulation! (Quick learner, aren't I? =)
Also, reading my comment again, I noticed that the part of polymorphism was also, if not utter crap, easily misinterpreted, again because I seem to have a bit different view of polymorphism than the rest of the world - well, I have my state, behaviour and identity
Polymorphism as in pure polymorphism is essential for object-orientation. I thought of polymorphism as it was only "ad hoc polymorphism" (overloading), and not pure polymorphism.
But now I'm corrected, thanks to you, igrek. Feel free to point out any other unbelievably crappy opinions in my previous (or this!) comment.
(* OO languages exist at the "high" end of the language-level spectrum. They're geared toward managing code complexity in the face of a problem domain which is conceptually complicated, primarily by encapsulating bits of the problem domain into digestible and self-contained sub-problems. *)
That is a bunch of brOOchure hot air. There is no public evidence that OOP is "higher" nor "better" than other paradigms. (See Yourdon's research.) Often OOP books and hype-rags compare decent OOP to *bad* code/design in other paradigms to fudge the results.
The idea that OOP breaks things down into "easier to digest parts" (more than other paradigms) is also hogwash. The problem is that truly complex things have no *one* border of division. They are multidimensional. The borders or boundaries needed by one user are likely insufficient or inappropriate for another user/viewer.
IOW, "one encapsulation fits all" is a tough goal. OOP's encapsulation borders are one-dimensional in a multi-dimensional world.
More OOP reality checks:
http://geocities.com/tablizer/oopbad.htm
Table-ized A.I.
This often leads to a terminology battle. OOP is relatively easy to define: using classes. OOP also has historical roots in Simula-67 and Smalltalk.
However, talking about analysis and conceptual model gets into how an individual's grey matter works, and the grey matter is a grey area (pun intended).
IOW, defining something based on a moving target, differences in individual's heads, is risky biz. (Another approach is with charts, but this has definition problems also.)
Just something to keep in mind.
Table-ized A.I.
(* [rules] are not fair.*)
Again, if you don't like my rules, suggest your own. Anybody can complain. The hard part is presenting good alternatives.
(* I posted a counterexample to this from my own work, just the other day. *)
This field needs Yet Another Anecdote like a hole in the head.
(* The previous effort was written in C *)
I hardly consider C the pinnicle of procedural/relational programming. Further, many C experts cannot or don't know how to use tables to better organize and manage code projects. I agree that procedural *alone* does not scale very well without speggetti. Tables are the Scaling Glue of procedural IMO.
(* Their code is the type of spaghetti that is sadly common in real world procedural work *)
I agree that much of real world code (in all paradigms) if often crap. However, this is usually because lack of incentives and/or punishment. The reality is that bad code is job security.
I would also point out that you have the benefit of hind-sight in this case for the OO side.
Also, I would like to see some snippets of this alleged bad procedural code. Put your code where your mouth is.
Note that your "case study" (anecdote) did not tilt the score in Yourdon's work. Why should one believe you over Yourdon?
(* Here you make numerous clear statements about what OOP experts say, and what people think about OOP. And yet, you provide no evidence to support any of it; not a single citation is present in that section. *)
What use is "Bob said on webgroup X in 1998 that......". Everybody has an opinion. If you disagree with a quoted OO fan, then simply ignore it. Opinions of OO proponents are all over the map. Making every OO fan happy is impossible.
If you want quotes from an "expert", may I suggest my commentary to Bertrand Meyer's work.
(* You drum up some old arguments long since given up as if everyone today still believed them *)
As a frenquentor to comp.object, I can tell you that there is *no concensus* OOP opinion/definition/methodology. Lack of consistency is one of the main problems with OO these days.
Table-ized A.I.
And again, I repeat that I don't have to. I'm not the one trying to justify my claims about OOP.
On the other hand, if you refuse to accept anecdotes from the many OO developers who use the technology every day in the field, how can you possibly claim to have formed a useful, unbiased opinion? There are many such anecdotes around. In persisting in ignoring them, and attacking what you perceive OO theory to be based on your own theories, you are detaching yourself from reality. The reality is that while not perfect, OOP works very well for a lot of people in a lot of situations.
Hardly. When the procedural code was written, our clients had double figures of experts in the field concerned to help them derive the algorithms and check the details. Now, they have two, whose knowledge doesn't even cover the whole field. Details frequently come to light months or even years after we first support a piece of hardware or analysis, and require fundamental changes to our instrument control or mathematical algorithms. Our need to adapt to changing requirements is way, way higher than that of the original procedural code. This can be objectively demonstrated simply by counting the change requests made over time. And we're succeeding, where they failed.
And you know damn well that any industrial-scale example is going to be both too unwieldy to show you, and certainly the public, and also covered by copyright meaning it can't be shown outside of the companies concerned. Where are your industrial-scale examples of OOP failing? Where are your industrial-scale examples of OOP projects failing? Even given that projects fail, if you're going to have a go at OOP, you need to show convincing evidence that more OOP projects fail than those using other methodologies, and that the cause of that failure was definitely OOP. I don't see even the slightest evidence of such research on your site, and without it, your arguments are purely academic.
Yep, and those of us whose opinions come from real experience using the technology concerned, they have rather more validity in any sensible study than those from people whose arguments are based on theory, not practice.
Sure, just as soon as you issue a similar critique of procedural programming, based on the books written many years ago when it first came out, instead of the current, vastly different state of the art.
You think all programmers should agree about tools and technologies, and there should be no discussion or disagreement? How are we to make progress then?
If you disagree, post your argument. (-1, Overrated) isn't your personal censorship tool for views you don't like.
with the vtable being defined by running code you can load modules into the c program during runtime that define new classes.
You could literally have a module for round pipe and a module for rectangular pipe and load them while your program is running.
The C++ definitions are all static and you can't extend them once they are compiled, except maybe by loading in a module that is a subclass of base class that is already loaded.
And you could have a multidimensional vtable if you have complex data types that can't be expressed in a single dimension.
This gives you a lot more flexibilty than C++ offers, at the cost of having code that is slightly harder to read.
(* However, the OO framework is much more easily extensible than its procedural counterpart. You can add new subtypes of Expression, and have them immediately fit into your existing framework, without changing any of your existing code *)
OOP generally favors adding new "types", while procedural favors adding new operations (WRT change effort). It is generally a zero sum situation in past "contests" like this. (Unless it can be shown that one is signif more likely than another.)
However, at least in my domain, "types" are too fat a granularity of division. I tend to let features be able to combine independently of any notion of "type". This creates greater extensibility, especially for combinations of features that could not be foreseen in advance.
Table-ized A.I.
(* I'm not the one trying to justify my claims about OOP *)
Make up your mind. Do you claim OOP is objectively better than procedural/relational or not? If so, then present evidence beyond pet anecdotes.
(* On the other hand, if you refuse to accept anecdotes from the many OO developers... *)
Anecdotes point both ways. People who survey anecdotes both ways, like Edward Yourdon's group, find no detectable advantage.
One anecdote is insufficient evidence, no matter how much you talk about it.
(* And you know damn well that any industrial-scale example is going to be both too unwieldy to show you, and certainly the public, and also covered by copyright meaning it can't be shown outside of the companies concerned. *)
That is your problem, not mine. If you can't show the code you rag on, then don't bring it up.
Note that I *don't* claim that procedural/relational is objectively better. I suspect it is *subjective*. After all, software engineering (making software more change-friendly) is mostly about communicating with other developers and not so much machines. However, OO proponents often extract how best to manage/communicate with their *own* neurons onto everybody else's neurons.
(* they have rather more validity in any sensible study than those from people whose arguments are based on theory, not practice. *)
Again, anecdote surveys don't support OOP.
(* Sure, just as soon as you issue a similar critique of procedural programming, based on the books written many years ago when it first came out, instead of the current, vastly different state of the art. *)
I am not sure what you mean. Meyer's book is dated 1997. Is this already "legacy"?
(* You think all programmers should agree about tools and technologies, and there should be no discussion or disagreement? How are we to make progress then? *)
You are putting words in my mouth. I am simply responding to complaints that I allegedly don't represent "mainstream" OO viewpoints by saying that there is *no* mainstream OO viewpoint. I am just the messenger.
Table-ized A.I.
People keep claiming that Fortran is faster. But is it really so much faster that this is important?
It is more important to choose the proper algorith here than the language you choose. A bash script using O(n) and a large data set is faster than a hand tuned assembler algorith that is O(n^2).
And even if Fortran was only 10% faster then with todays processors the fact that a job runs in 11 seconds instead of 10 isn't all that big a deal. It probably isn't even noticable. It might have been a big deal back in 1975 when it took 11 hours instead of 10 hours on a 286. But not anymore.
I think that other features than performance matter with Fortran. It looks like the data structure sizes are fixed across all implementations and that the math functions are optimized to use IEEE standards. But there are libraries for these same purposes in C and C++ that are probably just as good.
Here is an example entitled Identifying Objects: A Case Study and Class Exercise giving an example of waveform rendering on an oscilloscope (see page 5), appropriately enough based on work done at Tektronix. Is that enough of an "engineering problem" for you?
(* Procedural and OO both have their strengths and weaknesses *)
Perhaps, but I never get a strait answer about when, where, and why. If it is not clear when to use what and the usage opinions overlap, then it makes more sense to stick with *one* paradigm for consistency and training's sake.
(* What I have done is demonstrate that OO design can be markedly more successful than procedural under some circumstances *)
Perhaps, but you expose very little specific insight into this single case. We can't learn from it. Perhaps somebody could spot key flaws in those guys' procedural code if we could actually see it and make it better procedural/relational code. There is a dearth of published info on how to make procedural/relational code change-friendly.
(* which is the impression you are clearly trying to give, in spite of the little disclaimer you keep conveniently inserting. *)
So, how long have you been a mind-reader?
(* That sounds pretty darn much like an "objectively better" claim to me *)
It is a personal observation. A "cliche" if you will, similar to the sound-byte cliches people use to justify OOP to PHB's and other vapor-heads.
I would note that my 1-D "type" observation is similar to Stepanov's (a nearby message), and independently concluded.
(* So you keep saying, yet your anonymous and uncited surveys offer vastly different conclusions to my own experience *)
I often get emails from people who see OO projects fail or go over budget and bloat up. Summary anecdotes are completely useless for decent comparisons, I am sorry to say. I *did* cite Edward Yourdon. Perhaps the details of his work is not available on the web, but it is at least as much as you guys have to offer.
(* In software development terms? [1997 is] ancient history. Much of the OO technique being developed in real applications today come from the current popularity of
*)
So all the bragging about OOP before 1998+ was all wrong and now revised?
If the hype before 1998 was mostly crap, then how do we know that post 97 is *not* crap?
You are defecating in your own room.
Shouldn't it be perfected in isolation first, and THEN shoved down everybody's throats? Or, are we just all Sun's Guinney Pigs?
(* (COM, CORBA, etc.) that are essentially simple OO frameworks *)
I have rarely heard these referred to as "simple". So for, they mostly get lip service instead of actual use in the trenches. (And don't bother citing exceptions. I don't question their existence.)
(* Their very existence is based, by definition, on the fact that people are discovering OO solutions to recurring problems. *)
Most OOP "patterns" are *trivial* Boolean and/or relational formulas in the non-OO world. They are a big deal in OOP because OOP makes them complicated and have thus become an intellectual status symbol.
(* The opinions you express, and the claims you make about "expert opinion", are quite opposed to anything I've seen on comp.object recently. *)
I suggest you bring them up there. I rarely find a consensus on ANYTHING there. For example, the issue of whether OOP models the real world or should model the real world goes round and round for months among OO fans.
Table-ized A.I.
Remind me not to hire you to do any carpentry for me, Bryce...
Christian R. Conrad
mail me at iki.fi ; same user ID as here
So what you're saying is pretty much "If you're too dumb to figure out when to use a hammer and when to use a wrench or a screwdriver, then it makes more sense to stick with *only* a hammer for consistency and training's sake.", right?
And every requirement becomes a nail to be beaten into submission. lol:)
p.s. This is a well known usenet troll.
http://groups.google.com/groups?q=%22topmind@te
http://groups.google.com/groups?as_uauthors=top
I could not figure out why the mod values suddenly dropped after a few days of relatively stable levels. Then I saw your handle. You and the Zenvague gang over at the Z have barged in and done a little score trolling it seems.
Regarding your worn-out hammer cliche, it would be like OO expert A uses a hammer on part 1 and a screwdriver on part 2, but OO expert B uses a screwdriver on part 1 but a hammer on part 2. It seems fairly clear that one could use *just* a screwdriver on both parts (assuming good experts) and get similar results WRT quality.
Mixing paradigms may give say a 5 percent benefit, but at the cost of less consistency and double the training and almost double the complexity of the language. You sacrifice consistency, training costs, and language complexity for a really minor gain. That is not logical, Captain.
BTW, I see you chose to ridicule me instead of address the Yourdon and Stepanov issues. How CRC of you.
Table-ized A.I.
This is a well known usenet troll.
Tell me something. Is a "troll" somebody who is wrong, or just somebody who is annoying?
I may indeed be annoying, but nobody has shown any decent evidence that OOP is better other than vague cliches and feel-good statements about it.
In the end, someday distant they will discover that it is probably mostly subjective. OOP maps to some people's heads better than others it seems. However, there is nothing about it that objectively fits the real (external) world better nor real world change-patterns better. (At least in my domain.)
Table-ized A.I.
I missed some paragraphs on the first pass.
(* The database is at the core of our whole application, and the APIs we designed to access it are still standing, *)
Care to list the interfaces here?
(* You can write data from an OO program out to any format file you like, just as you can with procedural languages *)
This greatly depends. I would be glad to take the issue up at comp.object.
(* Writing a good wrapper, which provides a mapping from your OO system's concepts onto the procedural API, can take much longer, of course, but adds value in the process. *)
Such as?
(* Do you know what multiple inheritance is? *)
Using multiple inheritance for many of the problems I describe does not seem very popular even with the OOP crowd. It generally seems to be used for *diverse* properties being inherited, not potentially overlapping or interfering properties.
(* And yet, every serious OOP instruction I have ever experienced, in print, at a training course or from senior staff at work, has been quick to stress that inheritance should not be overused. *)
Well, such warnings did not make it into most of the OOP books on my shelf. It is a well-known "newbie fault". If it is such a common disclaimer, then why are all the newbies missing it?
(* Those would be pretty similar to the "ideal" conditions for any programming paradigm. *)
OOP seems *more* sensitive to such imperfect conditions than p/r. Richard McDonald, an OOP proponent on comp.object holds that opinion more or less. I suggest you take it up with him since you two probably think more alike.
(* I've got to about halfway down the page now. I could go on, and I'm half tempted to have a go at your final conclusions, but I don't see much point. *)
I would rather see an OOP business example and/or code kicking p/r's ass using whatever metrics you choose (and can justify). My cliche pages to counter OO cliches are simply bonus information. The burden of public evidence of objective OO benefits is in your hands. Are you up to it, or just another talking head? (Remember, I don't have the same burden because my viewpoint is that they are subjective.)
Table-ized A.I.
(* OK, so what were his credentials? *)
Creditentials are no guarentee of better software design anyhow. I wanna see self-standing open evidence, not puffery.
BTW, the originator is an author of many C++ books.
(* It's bad modelling in my book, too. That's why I suggested using multiple inheritance, to combine the two indepedent aspects as necessary. *)
This tends to only work if they are *completely* independent. If there is dynamic overlap, then you may constantly be doing the "noun shuffle" as described on my webpage.
Other OO proponents would probably recommend the (bloated) decorator pattern over multi inher for such, BTW.
Table-ized A.I.
(* for example, is modelled as operations on the instrument types concerned. *)
....*)
:-)
Like I said, I am highly skeptical of anything modeled with "types". Anyhow, show us your code and amaze my procedural/relational ass. Talk is cheap. I get email of anecdotes of OO failures also.
(* Well, you're entitled to your opinion, of course. However, noting the number of OO GUI toolkits out there, and the fact that so much software is written using them, clearly others do find an OO model for a GUI useful. *)
Or, it could be a fad. API providers tend to clone each other's approach to play it safe.
(* And then they provide absurd and vastly overcomplicated idioms to do what would be trivial with proper MI *)
Example?
(* Maybe it's because they lack experience, and tend to overuse "flashy" features. *)
So you indirectly admit that some of OO's popularity may be due to a "fad factor".
(* Most decent examples of this, certainly industrial scale projects, aren't open source. If you genuinely want to get useful information here, don't start by cutting off the vast majority of your possible sources. *)
You seemed to have cut off Yourdon's research.
(* And yet, here I have a large-scale, long-term project, where an OO and a procedural approach are directly comparable. *)
I am not even sure C is capable of "decent p/r". (I know I will alienate C fans, but I cannot see how it can be competitive from a SE standpoint. It just does not gel with me.)
(* Your only replies seem to be "It doesn't count if we can't see the code" and "Well, maybe the procedural guys sucked". Those are hardly convincing arguments. *)
And your one anecdote is more convincing than other's, including Yourdon's surveys? Double standard? If you are so hellbent on anecdotes, why ignore Yourdon's work?
(* The procedural guys sucked so much that it took them ten times longer to write their version,
I had a similar experience between C and a higher-level procedural/relational language. I started writing a hobby MIDI sequencer in C. Although I got it working, I abandoned C for the other language when PC's got fast enough. My productivity was many-fold higher.
(* The major benefits don't come from individual features. The strength of the system comes from having a clear overall design, something that deteriorated in its procedural predecessor. *)
Well, then they did something wrong. The 3-graph p/r model works and scales. Perhaps they deviated from it for some odd reason, or your domain is somehow different in that regard.
(* For example, to change the way something works for all instruments in a particular series, you know immediately that the common functionality will be in the base class for that series, and you also know immediately that changing that base class will affect all instruments that don't specifically override the behavior (but you still have the latter option if you don't want your change to be made everywhere)......*)
Like I keep saying, variations do *not* fit naturally into trees nor align on clean method boundaries in my domain (Overriding 1/3 of a method is a royal pain). I have asked for biz taxonomies that can take advantage of such WRT to variation-management. They have all failed.
Maybe for some reason your "instruments" have a stable and granularity-predictive taxonomy about them. I don't know, I never worked there. It would be interesting to analyze the change patterns to see which organizational schemes require the fewest changes, etc.
(* It also, to an extent, helps to enforce the overall architecture. *)
My apps are *not* willy-nilly (except maybe to those who only know how to grok OO).
(* You can do any of this in procedural as well, of course, but in my experience it's harder work and more error prone. *)
Could that be subjective (person-dependant)? People make different kinds and patterns of mistakes. Human errors are as distinctive as faces. (And some faces are errors
Table-ized A.I.
(* Of course, I agree that it would be great to find some concrete and well-evidenced guidelines for this, but in the meantime, experience will have to do. *)
Well, individual anecdotes are barely better than no evidence. I know it bothers you, but I have to reject "closed" anecdotes. Science has learned the hard way that they are only good for investigation leads, and generally not evidence itself.
(* However, OO was too much of a buzzword in the mid-90s, too many idiots got involved, and started claiming it was magic, *)
Do you really think that idiots dissappear that fast? Especially when OO cliches still work on PHB's.
BTW, my procedural/relational version of some of the GOF (and popular) patterns are at:
http://geocities.com/tablizer/prpats.htm
Table-ized A.I.
I have some further questions and comments about your example.
(* For example, to change the way something works for all instruments in a particular series, you know immediately that the common functionality will be in the base class for that series, and you also know immediately that changing that base class will affect all instruments that don't specifically override the behaviour (but you still have the latter option if you don't want your change to be made everywhere). *)
What I find works better for my domain is to "classify" things using sets, and not trees (inheritance). You specify which set a thing belongs to. Then it can "inherit" anything that it's given set(s) is supposed to inherit.
I realize that multiple inheritance is roughly a set mechanism, but it does not manage overlaps very well IMO. For example, class A may do action X for operation 1, and class B may do action Y for operation 1. However, what if we had a rule like:
If in set A and in set B, then do Z.
The set membership does not change, but the behavior might. In procedural programming generally only the rule would be changed, not the position of the code that implements Z. OO would likely try to associate Z with *what* gets that operation. The problem is that rules for "triggering" a given operation are fairly likely to change. Thus, grouping by task instead of by the thing being operated on results in less code rearrangement it would follow.
(* In comparison, the procedural version of the project would have several versions of the algorithm concerned, but each instrument's code must explicitly call the correct algorithm for that instrument, every time. *)
I am not sure what you mean here by "explicit". Like I said, if a given group shares something in common, then use set membership (such as a Group-X checkmark in an Instrument table. Tablizing such allows association changes to be made without recompilation).
Are you also saying that the OOP version would *not* have "several versions"?
I didn't indirectly admit it, I said it outright several posts ago. However, my comment quoted above is not in any way evidence to support that, as you seem to be implying. OO has been around for decades and it's still here, so I find any claim about it being a fad to be a little laughable.
I'm still waiting to see a citation so I can go read it. I'm also still waiting to hear any other evidence. Most of your argument so far seems to have been based either on your own subjective views, which I don't share, on this survey of Yourdon's, which you haven't cited that I've seen, or on pure faith. My argument is based on personal experience, both theoretical and practical, which suggests that while some of your criticisms are valid, the big picture is far from as bleak as you make out.
Sure they did. They lost control of their design, and the project failed. That happens frequently in software development. However, given that their project failed and ours didn't, we must ask why. The major differences are in the teams who wrote the code and the technologies used. Given that we know the original team was both bigger and more highly qualified in the domain concerned, we can only conclude that the different technologies and techniques used in development were the deciding factor.
Did it occur to you that your "business applications" domain is only a significant minority of all programming that gets done? The rest of the world is different. If you're going to go around criticising OOP in a limited case, you need to make a prominent disclaimer that your comments apply only to using OOP for writing applications in your domain every time.
I also note that you continuously lump relational programming techniques in as if they were part and parcel of procedural programming. They are not. Few of the languages I would say support procedural programming have built-in support for relational operations, so I claim that the two are separate. It is unfair to claim that OOP does not much improve upon procedural techniques, when you yourself use table-driven methods instead because the simple procedural approach doesn't work for you, either.
Moreover, your table-driven approach is right at home in the database world, but I claim that it is largely or totally irrelevant in many other fields. The instrument control system in my example is not full of separately configurable parts, it's full of things that are clearly and necessarily dependent. OO models this perfectly. A table-based approach to the sort of dispatching we do would only allow for needless errors as a result of invalid or missing data. It is simply the wrong tool for the job, while OO is a suitable one, in this particular case.
There you go again: in your domain. The rest of the world works differently. In the domain of the example I gave earlier, we control a whole family of instruments. Each has some basic properties, such as uniform interfaces to talk to the hardware and GUI. There are several series of instrument, used to measure different types of property, and these do not (and will never) overlap, since it makes no sense in the area of science concerned for them to do so. There are then several instruments in each series, of varying capabilities. We model this using a simple inheritance hierarchy, and it works very well. Each class genuinely is a type of the parent class, which is the only correct use of full inheritance in an OO system. Our whole application rests on several such hierarchies, but because we only use inheritance in appropriate places (containment is a far more common relation between classes in our model), we rarely have problems with this.
If you disagree, post your argument. (-1, Overrated) isn't your personal censorship tool for views you don't like.
Then you shouldn't be using decorator. That pattern is most useful when you want to add things at will and the order is significant. Attributes cannot cope with such a situation. You would need some sort of ordered list(s) of functions to iterate to get a straightforward procedural equivalent to decorator, but that equivalent then must have some centralised controlling logic to co-ordinate traversing the list(s) and acting on the contents. That can be a nasty limitation, introducing unwanted dependences on some artificial "central control", which is why we opted to use decorator in the first place on our project.
If you disagree, post your argument. (-1, Overrated) isn't your personal censorship tool for views you don't like.
Unfortunately, being neither American nor in search of rebirth, I've never read that one. Can you provide a citation here? It sounds like it would make interesting reading.
OK, but since surely the way forward is to allow judicious combination of useful techniques, why must they always be mutually exclusive? I can (and often do) use simple table-based techniques in my application at work, precisely because of the benefits you cite in terms of independent variation of features.
The overall design is broken into hierarchies related by containment, inheritance, etc., but this does not preclude the use of table-based techniques as well for the "little details" where extra classes or method overrides are overkill. In fact, they go together quite nicely, since you can incorporate a suitable table or two into your top level base class, and provide a nice controlled interface to access and update the table should any derived classes need to do so.
We don't, on the current project, use a full-scale relational table system, because that, too, would be overkill for our purposes. I see no reason that it couldn't be incorporated, and just as complementary to the OOP main design, if it were needed, though.
Well, if you're going to have multiple, related tables to model something like this, then you're going to have to impose certain restrictions yourself. Just as with OOP, if the model later changes and moves outside of your initial constraints, you need to do a little reorganising. I really don't see much difference between OOP or a table-based approach here; either is more helpful than a simple procedural approach, and obviously neither is guaranteed to give you the perfect design that never changes. In neither case is it particularly difficult to modify the design when new requirements come in, so I don't see the problem.
I wouldn't dream of it. For a start, Java has an underpowered OO model. It trades off simplicity against power in favour of simplicity. Usually, that works, and the simplicity is probably one reason for Java's popularity. But for serious OO modelling, I find things like the lack of a value/reference distinction and crippled MI mechanism to be very limiting.
My argument is not, and never has been, that OO is universally superior. As I said at the start, I use a mix of paradigms, and draw on them as appropriate. I simply contend that under the right circumstances, OO can and does provide a better basis for a model than procedural, or indeed purely table-driven, programming techniques. Under those circumstances, many of the claims you reject on your web site are actually justified.
If you disagree, post your argument. (-1, Overrated) isn't your personal censorship tool for views you don't like.
OK, let's look at a concrete example. Suppose I have a model where I need to know some value that is identified by a location in space. I want to establish that value by taking the input co-ordinates and applying various transforms on them to get a new position. I then use a "master function" of some sort to calculate an output value. I may then also want to apply further variations to that, before returning the final value to the caller.
In the decorator pattern, I model this using an interface that takes the co-ordinates as parameters and returns a value. I then provide three classes implementing that interface, one of which does co-ordinate transforms, one of which represents a "master function", and one of which represents the further variations on the value. I also add a second part to the first and last cases, allowing me to chain them on to any other object implementing the main calculation interface, so I can use the decorator pattern. The individual calculation effects are now derived from one of the three specific types, and any data necessary to perform the calculation can be introduced on a case-by-case basis. The result is a simple class hierarchy representing the various transformations to be applied on a one transformation, one class basis, and with any extra data required to define a particular transformation wrapped up with the transformation algorithm in its class.
I can now build a chain of the co-ordinate transforms and variations, ending with a master function to do the main calculation. The only place that knows or cares how to combine the effects is the place that sets up the chain in the first place. There is no connection at all between the three different types of calculation (other than implementing that main interface) and they can be freely interchanged. New calculation classes can be added without any impact on existing code, and just slotted into the chain creation process.
The nearest procedural equivalent without jumping through hoops is to have a list of functions, and to provide both some function to set up the list (which is directly equivalent to setting up the chain in the decorator case), and another master evaluation function to iterate through the functions, calling them in the right order. Life gets more complicated when you then have to provide arbitrarily varying parameters to the different functions, of course. A suitable mechanism for this is not trivial.
OK, that's my problem. It's a real example, the major part of a key subsystem in our current application. The above is the OO model I used to model it, using the decorator pattern. I claim that this use of decorator is a good example, and has proved its worth in a real program. I invite you to suggest a plain procedural and/or relational/table-based solution that is as elegant and adaptable in the face of arbitrary change. I also invite you to point out any weaknesses in the decorator model that make it susceptible to changes in requirements.
If you disagree, post your argument. (-1, Overrated) isn't your personal censorship tool for views you don't like.
My experience with scientific programming has been that while it is quite possible to code in a procedural language (I've done F77 and C), it will eventually start to give out.
That is, there's no question that the inner core algorithms are nicely written in FORTRAN or C or assembler if you please, and these are probably best written in those languages.
It's all the other overlying code that starts to get really ponderous in a procedural language. Things like parsers and managing I/O.
If your underlying code is useful, then you'll inevitably want one more feature to make it easier to use in a slightly different way. This happens constantly. In the end, managing that complexity is more convenient using an OO language.
My own inclination (having wallowed in C++ syntax for a few years) would be to follow an approach like having efficient numerical algorithms in FORTRAN or C and a higher level code in Python, using things like SWIG to connect them together.
Don't dismiss OO programming because of the history of over hype. It really does offer something. It can be misused. But if you take as much care with it as you do with your procedural programming you'll appreciate the dividends it returns.
"Provided by the management for your protection."