Does procedural programming have any advantages over OOP? - oop

[Edit:] Earlier I asked this as a perhaps poorly-framed question about when to use OOP versus when to use procedural programming - some responses implied I was asking for help understanding OOP. On the contrary, I have used OOP a lot but want to know when to use a procedural approach. Judging by the responses, I take it that there is a fairly strong consensus that OOP is usually a better all-round approach but that a procedural language should be used if the OOP architecture will not provide any reuse benefits in the long term.
However my experience as a Java programmer has been otherwise. I saw a massive Java program that I architected rewritten by a Perl guru in 1/10 of the code that I had written and seemingly just as robust as my model of OOP perfection. My architecture saw a significant amount of reuse and yet a more concise procedural approach had produced a superior solution.
So, at the risk of repeating myself, I'm wondering in what situations should I choose a procedural over an object-oriented approach. How would you identify in advance a situation in which an OOP architecture is likely to be overkill and a procedural approach more concise and efficient.
Can anyone suggest examples of what those scenarios would look like?
What is a good way to identify in advance a project that would be better served by a procedural programming approach?

I like Glass' rules of 3 when it comes to Reuse (which seems to be what you're interested in).
1) It is 3 times as difficult to
build reusable components as single
use components 2) A reusable
component should be tried out in three
different applications before it will
be sufficiently general to accept into
a reuse library
From this I think you can extrapolate these corollaries
a) If you don't have the budget
for 3 times the time it would take you
to build a single use component, maybe
you should hold off on reuse. (Assuming Difficulty = Time)
b) If
you don't have 3 places where you'd
use the component you're building,
maybe you should hold off on building
the reusable component.
I still think OOP is useful for building the single use component, because you can always refactor it into something that is really reusable later on. (You can also refactor from PP to OOP but I think OOP comes with enough benefits regarding organization and encapsulation to start there)

Reusability (or lack of it) is not bound to any specific programming paradigm. Use object oriented, procedural, functional or any other programming as needed. Organization and reusability come from what you do, not from the tool.

Those who religiously support OOP don't have any facts to justify their support, as we see here in these comments as well. They are trained (or brain washed) in universities to use and praise OOP and OOP only and that is why they support it so blindly. Have they done any real work in PP at all? Other then protecting code from careless programmers in a team environment, OOP doesn't offer much. Personally working both in PP and OOP for years, I find that PP is simple, straight forward and more efficient, and I agree with the following wise men and women:
(Reference: http://en.wikipedia.org/wiki/Object-oriented_programming):
A number of well-known researchers and programmers have criticized OOP. Here is an incomplete list:
Luca Cardelli wrote a paper titled “Bad Engineering Properties of Object-Oriented Languages”.
Richard Stallman wrote in 1995, “Adding OOP to Emacs is not clearly an improvement; I used OOP when working on the Lisp Machine window systems, and I disagree with the usual view that it is a superior way to program.”
A study by Potok et al. has shown no significant difference in productivity between OOP and procedural approaches.
Christopher J. Date stated that critical comparison of OOP to other technologies, relational in particular, is difficult because of lack of an agreed-upon and rigorous definition of OOP. A theoretical foundation on OOP is proposed which uses OOP as a kind of customizable type system to support RDBMS.
Alexander Stepanov suggested that OOP provides a mathematically-limited viewpoint and called it “almost as much of a hoax as Artificial Intelligence” (possibly referring to the Artificial Intelligence projects and marketing of the 1980s that are sometimes viewed as overzealous in retrospect).
Paul Graham has suggested that the purpose of OOP is to act as a “herding mechanism” which keeps mediocre programmers in mediocre organizations from “doing too much damage”. This is at the expense of slowing down productive programmers who know how to use more powerful and more compact techniques.
Joe Armstrong, the principal inventor of Erlang, is quoted as saying “The problem with object-oriented languages is they’ve got all this implicit environment that they carry around with them. You wanted a banana but what you got was a gorilla holding the banana and the entire jungle.”
Richard Mansfield, author and former editor of COMPUTE! magazine, states that “like countless other intellectual fads over the years (“relevance”, communism, “modernism”, and so on—history is littered with them), OOP will be with us until eventually reality asserts itself. But considering how OOP currently pervades both universities and workplaces, OOP may well prove to be a durable delusion. Entire generations of indoctrinated programmers continue to march out of the academy, committed to OOP and nothing but OOP for the rest of their lives.” and also is quoted as saying “OOP is to writing a program, what going through airport security is to flying”.

You gave the answer yourself - big projects simply need OOP to prevent getting too messy.
From my point of view, the biggest advantage of OOP is code organization. This includes the principles of DRY and encapsulation.

I would suggest using the most concise, standards-based approach that you can find for any given problem. Your colleague who used Perl demonstrated that a good developer who knows a particular tool well can achieve great results regardless of the methodology. Rather than compare your Java-versus-Perl projects as a good example of the procedural-versus-OOP debate, I would like to see a face-off between Perl and a similarly concise language such as Ruby, which happens to also have the benefits of object orientation. Now that's something I'd like to see. My guess is Ruby would come out on top but I'm not interested in provoking a language flame-war here - my point is only that you choose the appropriate tool for the job - whatever approach can accomplish the task in the most efficient and robust way possible. Java may be robust because of its object orientation but as you and your colleague and many others who are converting to dynamic languages such as Ruby and Python are finding these days, there are much more efficient solutions out there, whether procedural or OOP.

I think DRY principle (Don't Repeat Yourself) combined with a little Agile is a good approach. Build your program incrementally starting with the simplest thing that works then add features one by one and re-factor your code as necessary as you go along.
If you find yourself writing the same few lines of code again and again - maybe with different data - it's time to think about abstractions that can help separate the stuff that changes from the stuff that stays the same.
Create thorough unit tests for each iteration so that you can re-factor with confidence.
It's a mistake to spend too much time trying to anticipate which parts of your code need to be reusable. It will soon become apparent once the system starts to grow in size.
For larger projects with multiple concurrent development teams you need to have some kind of architectural plan to guide the development, but if you are working on your own or in small cooperative team then the architecture will emerge naturally if you stick to the DRY principle.
Another advantage of this approach is that whatever you do is based on real world experience. My favourite analogy - you have to play with the bricks before you can imagine how the building might be constructed.

I think you should use procedural style when you have a very well specified problem, the specification won't change and you want a very fast running program for it. In this case you may trade the maintainability for performance.
Usually this is the case when you write a game engine or a scientific simulation program. If your program calculate something more than million times per second it should be optimized to the edge.
You can use very efficient algorithms but it won't be fast enough until you optimize the cache usage. It can be a big performance boost your data is cached. This means the CPU don't need fetch bytes from the RAM, it know them. To achieve this you should try to store your data close to each other, your executable and data size should be minimal, and try using as less pointers as you can (use static global fixed sized arrays where you can afford).
If you use pointers you are continuously jumping in the memory and your CPU need to reload the cache every time. OOP code is full of pointers: every object is stored by its memory address. You call new everywhere which spread your objects all over the memory making the cache optimization almost impossible (unless you have an allocator or a garbage collector that keeps things close to each other). You call callbacks and virtual functions. The compiler usually can't inline the virtual functions and a virtual function call is relatively slow (jump to the VMT, get the address of the virtual function, call it [this involves pushing the parameters and local variables on the stack, executing the function then popping everything]). This matters a lot when you have a loop running from 0 to 1000000 25 times in every second. By using procedural style there aren't virtual function and the optimizar can inline everything in those hot loops.

If the project is so small that it would be contained within one class and is not going to be used for very long, I would consider using functions. Alternatively if the language you are using does not support OO (e.g. c).

"The problem with object-oriented languages is they’ve got all this implicit environment that they carry around with them. You wanted a banana but what you got was a gorilla holding the banana and the entire jungle.” —Joe Armstrong
Do you want the jungle?

I think the suitability of OOP depends more on the subject area you're working in than the size of the project. There are some subject areas (CAD, simulation modeling, etc.) where OOP maps naturally to the concepts involved. However, there are a lot of other domains where the mapping ends up being clumsy and incongruous. Many people using OOP for everything seem to spend a lot of time trying to pound square pegs into round holes.
OOP has it's place, but so do procedural programming, functional programming, etc. Look at the problem you're trying to solve, then choose a programming paradigm that allows you to write the simplest possible program to solve it.

Procedural programs can be simpler for a certain type of program. Typically, these are the short script-like programs.

Consider this scenario:
Your code is not OO. You have data structures and many functions throughout your progam that operate on the data structures. Each function takes a data structure as a parameter and does different things depending on a "data_type" field in the data structure.
IF all is working and not going to be changed, who cares if it's OO or not? It's working. It's done. If you can get to that point faster writing procedurally, then maybe that's the way to go.
But are you sure it's not going to be changed? Let's say you're likely to add new types of data structures. Each time you add a new data structure type that you want those functions to operate on, you have to make sure you find and modify every one of those functions to add a new "else if" case to check for and add the behavior you want to affect the new type of data structure. The pain of this increases as the program gets larger and more complicated. The more likely this is, the better off you would be going with the OO approach.
And - are you sure that it's working with no bugs? More involved switching logic creates more complexity in testing each unit of code. With polymorphic method calls, the language handles the switching logic for you and each method can be simpler and more straightforward to test.

The two concepts are not mutually exclusive, it is very likely that you will use PP in conjunction with OOP, I can't see how to segregate them.

I believe Grady Booch said once that you really start to benefit a lot from OOP at 10000+ lines of code.
However, I'd always go the OO-way. Even for 200 lines. It's a superior approach in a long term, and the overhead is just an overrated excuse. All the big things start small.

One of the goals of OOP was to make reusability easier however it is not the only purpose. The key to learning to use objects effectively is Design Patterns.
We are all used to the idea of algorithms which tell us how to combine different procedures and data structures to perform common tasks. Conversely look at Design Patterns by the Gang of Four for ideas on how to combine objects to perform common tasks.
Before I learned about Design Patterns I was pretty much in the dark about how to use objects effectively other than as a super type structure.
Remember that implementing Interfaces is just as important if not more important than inheritance. Back in the day C++ was leading example of object oriented programming and using interfaces are obscured compared to inheritance (virtual functions, etc). The C++ Legacy meant a lot more emphasis was placed on reusing behavior in the various tutorials and broad overviews. Since then Java, C#, and other languages have moved interface up to more a focus.
What interfaces are great for is precisely defining how two object interact with each. It is not about reusing behavior. As it turns out much of our software is about how the different parts interact. So using interface gives a lot more productivity gain than trying to make reusable components.
Remember that like many other programming ideas Objects are a tool. You will have to use your best judgment as to how well they work for your project. For my CAD/CAM software for metal cutting machines there are important math functions that are not placed in objects because there is no reason for them be in objects. Instead they are exposed from library and used by the object that need them. Then there is are some math function that were made object oriented as their structure naturally lead to this setup. (Taking a list of points and transforming it in on of several different types of cutting paths). Again use your best judgment.

Part of your answer depends on what language you're using. I know that in Python, it's pretty simple to move procedural code into a class, or a more formal object.
One of my heuristics is a based on how the "state" of the situation is. If the procedure pollutes the namespace, or could possibly affect the global state (in a bad, or unpredictable way), then encapsulating that function in an object or class is probably wise.

My two cents...
Advantages of procedural programming
Simple designing (fast proof of concept, battle with dramatically
dynamic requirements)
Simple inter-project communications
Natural when temporal order matters
Less overhead at runtime
The more Procedural code become good the closer it's to Functional. And advantages of FP are well known.

I always begin designing in a top-down fashion and in the top parts it's much easier to think in OOP terms. But when comes the time to code some little specific parts you are much more productive with just procedure programming.
OOP is cool in designing and in shaping the project, so that the divide-et-impera paradigm can be applied. But you cannot apply it in every aspect of your code, as it were a religion :)

If you "think OO" when you're programming, then I'm not sure it makes sense to ask "when should I revert to procedural programming?" This is equivalent to asking java programmers what they can't do as well because java requires classes. (Ditto .NET languages).
If you have to make an effort to get past thinking procedurally, then I'd advise asking about how you can overcome that (if you care to); otherwise stay with procedural. If it's that much effort to get into OOP-mode, your OOP code probably won't work very well anyway (until you get further along the learning curve.)

IMHO, the long term benefits of OOP outweigh the time saved in the short term.
Like AZ said, using OOP in a procedural fashion (which I do quite a bit), is a good way to go (for smaller projects). The bigger the project, the more OOP you should employ.

You can write bad software in both concepts. Still, complex software are much easier to write, understand and maintain in OO languages than in procedural. I wrote highly complex ERP applications in procedural language (Oracle PL/SQL) and then switched to OOP (C#). It was and still is a breath of fresh air.

To this point, the arguments of using OO for DRY and encapsulation is just adding unnecessary complexity in terms of how implicit it is and just sheer of how many layers that a class can inherit a lot of properties and methods into it.
not to mention that it's really hard to design a good OO cause you'd end up adding unrelated/unnecessary things that are going to be inherited throughout the whole layers of classes that inherits them. which is really bad if one parent class gets messy, the whole codebase is messy. and gets refactored.
also the fact that those inherited properties are not specifically fit into the use case to the class that inherits it which requires to be overridden. and to the ones that don't need them at all just have them for no good reason.
for something that does not need to be shared, sure there's abstract properties. but you'd end up having to implement them in all the instances that tries to inherits them.
this inheritance is just too magicky and gets dangerous.
but I'd give OO credit on how it's good at enforcing of what should be available. but then again it's too much power that is really easy to be wrongly used.
In my opinion, final class should be the default. and you need to deliberately choose if you want to allow it to inheritance.

Most studies have found that OO code is more concise than procedural code. If you look at projects that re-wrote existing C code in C++ (not something I necessarily advise, BTW) , you normally see reductions in code size of between 50 and 75 percent.
So the answer is - always use OO!

Related

OO or procedural

I have an Access db I use for my checkbook (with a good amount of fairly simple VBA behind it) and I'd like to rewrite it as a stand-alone program with a SQL backend. I'm thinking of using either C++, Java, or Python. I had assumed, before I started, that I would write it OO because I thought that I would think "in OO terms" (due to a OO Logic class and a C++ class I took), but I'm finding that I can only visualize it as procedural (but maybe because I'm mentally stuck in thinking of how the db works in Access). How do I decide? Am I making sense or does it seem like I'm not understanding the concepts?
Thanks for your help.
I'd suggest OO - it's not harder than procedural programming, actually easier to maintain with the right tool. Delphi would be my choice - great DB programming support, visual designer, strongly-typed, plenty of components available. There are many great applications that are written in Delphi. Often underestimated, there are many reasons it's got a loyal following.
Now I'll duck as the Delphi-haters load up with tomatoes.
Well, OO may well be overkill, but it is excellent practice. Any code monkey can write procedural code. Its the path of least resistance in every case, which is why most people use it for one off apps that don't do much. However, if you're writing to get experience in working with OO, than it is best to think of it that way. You could start by designing an object that manages financial transaction, then you will also need a way to interact with the DB. Perhaps you could write a DB layer where you abstract away the database calls from the transaction object using the Entity framework where you could learn LINQ (or whatever the JAVA equivalent is). This is all assuming that you are doing this for fun and practice.
oo seems to be overkill for a simple checkbook app. Try something on a larger scale like something to manage all your financial accounts. This way designing an account class would make sense
Well it depends on your motivation. If you want a checkbook application as quickly as possible, just churn out the procedural code. No-one other than you will know the difference. If you want to use this application to better yourself as aprogrammer. Take the time to learn how to write in in OO.
I'd go with Python: no compiling and uses dynamic typing (you can use strict typing too if you want). Plus, it has a huge following in the open source community which means great support, tools, and documentation for free.
As for OO vs. Procedural -- all these languages you've mentioned could be written in a procedural style -- that is, one big class/method that does everything -- but you'll soon find that you'll want to follow DRY principles (Don't Repeat Yourself) and start with some private methods that do one particular thing well. From then, you'll want to group similar things into separate classes, and then from there you'll want to abstract those classes... see where I'm going here?
In my opinion you should concentrate less on the OO versus procedural thing. If you have the possibility to go procedural in the beginning, then go procedural. It's the easiest thing you can do to get you started. The OO thing, on the other hand, may just as well qualify as YAGNI (You Ain't Gonna Need It).
What you should do though, is to write tests, unit tests and then integration tests. And you should strive to write tests first. This way, even if you begin with a procedural application you may later on refactor it into a full-fledged OO application. But, only if you need objects. These tests will be you're safety net when moving around code in your application.
Trying to think your applications into object from the beginning may lead you to an point where you're stuck with your class hierarchies and architecture.
I'm not a genius, so I may be wrong, but in my experience, starting with simple functions and then thinking about grouping them into objects or modules is better than starting by saying: OK, I'll have this object that interacts with this object, which is implementing pattern X, so this way I'll decouple interface Y from implementation Z. Later on, you may observe that your domain model is weak. Take an evolutionary design path and start with small building blocks.
If you are looking for a quick app that you can extend, check out Dynamic Data.

How to teach object oriented programming to procedural programmers? [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
I have been asked to begin teaching C# and OO concepts to a group of procedural programmers. I've searched for ideas on where to begin, but am looking for general consensus on topics to lead with in addition to topics to initially avoid.
Edit
I intend to present information in 30 minute installments weekly until it no longer makes sense to meet. These presentations are targeted at coworkers at a variety of skill levels from novice to expert.
The best thing you can do is: Have a ton of Q&A.
Wikipedia's procedural programming (PP) article really hits where you should start:
Whereas procedural programming uses
procedures to operate on data
structures, object-oriented
programming bundles the two together
so an "object" operates on its "own"
data structure.
Once this is understood, I think a lot will fall into place.
In general
OOP is one of those things that can take time to "get," and each person takes their own path to get there. When writing in C#, it's not like the code screams, "I am using OO principles!" in every line. It's more of a subtle thing, like a foreach loop, or string concatenation.
Design center
Always use something (repeatedly) before making it.
First, use an object, and demonstrate the basic differences from PP. Like:
static void Main(string[] args)
{
List<int> myList = new List<int>();
myList.Add(1);
myList.Add(7);
myList.Add(5);
myList.Sort();
for (int i = 0; i < myList.Count; i++)
{
Console.WriteLine(myList[i]);
}
}
Using objects (and other OO things) first -- before being forced to create their own -- leads people down the path of, "Ok, I'm making something like what I just used," rather than "WTF am I typing?"
Inheritance (it's a trap!)
I would NOT spend a lot of time on inheritance. I think it is a common pitfall for lessons to make a big deal about this (usually making a cliché animal hierarchy, as others pointed out). I think it's critical to know about inheritance, to understand how to use the .NET Framework, but its nuances aren't that big of a deal.
When I'm using .NET, I'm more likely to "run into inheritance" when I'm using the .NET Framework (i.e. "Does this control have a Content property?" or "I'll just call its ToString() method.") rather than when I'm creating my own class. Very (very (very)) rarely do I feel the need to make something mimicking the taxonomy structure of the animal kingdom.
Interfaces
Coding to an interface is a key mid-level concept. It's used everywhere, and OOP makes it easier. Examples of this are limitless. Building off the example I have above, one could demonstrate the IComparer<int> interface:
public int Compare(int x, int y)
{
return y.CompareTo(x);
}
Then, use it to change the sort order of the list, via myList.Sort(this). (After talking about this, of course.)
Best practices
Since there are some experienced developers in the group, one strategy in the mid-level classes would be to show how various best practices work in C#. Like, information hiding, the observer pattern, etc.
Have a ton of Q&A
Again, everyone learns slightly differently. I think the best thing you can do is have a ton of Q&A and encourage others in the group to have a discussion. People generally learn more when they're involved, and you have a good situation where that should be easier.
The leap from procedural to object oriented (even within a language - for four months I programmed procedural C++, and classes were uncomfortable for a while after) can be eased if you emphasize the more basic concepts that people don't emphasize.
For instance, when I first learned OOP, none of the books emphasized that each object has its own set of data members. I was trying to write classes for input validation and the like, not understanding that classes were to operate on data members, not input.
Get started with data structures right away. They make the OOP paradigm seem useful. People teach you how to make a "House" class, but since most beginning programmers want to do something useful right away, that seems like a useless detour.
Avoid polymorphism right away. Inheritance is alright, but teach when it is appropriate (instead of just adding to your base class).
Operator overloading is not essential when you are first learning, and the special ctors (default, dtor, copy ctor, and assignment operator all have their tricky aspects, and you might want to avoid that until they are grounded in basic class design).
Have them build a Stack or a Linked List. Don't do anything where traversal is tricky, like a binary tree.
Do it in stages.
High level concepts : Describe what an object is and relate it to real life.
Medium level concepts: Now that they got what object is, try compare and contrast. Show them why global variable is bad compared to an encapsulated value in a class. What advantage they might get from encapsulating. Start introducing the tennets of OOP (encapsulation, inheritance)
Low Level concepts: Go in further into polymorphism and abstraction. Show them how they can gain even better design through polymorphism and abstraction.
Advance concepts: SOLID, Interface programming, OO design patterns.
Perhaps you should consider a problem that is work related and start with a procedural implementation of it and then work through (session by session) how to make an OOP implementation of it. I find professionals often grasp concepts better if it is directly related to real examples from their own work place. The junk examples most textbooks use are often horrible for understanding because they leave the student wondering, why on earth would I ever want to do that. Give them a real life reason why they would want to do that and it makes more sense.
I would avoid the "a bicycle is a kind of veichle" approach and try to apply OO to an environment that is fairly specific and that they are already used to. Try to find a domain of problems that they all recognize.
Excercise the basics in that domain, but try to move towards some "wow!" or "aha!" experience relatively early; I had an experience like that while reading about "Replace Conditional with Polymorphism" in Fowlers Refactoring, that or similar books could be a good source of ideas. If I recall correctly, Michael Feathers Working effectively with legacy code contains a chapter about how to transform a procedural program into OO.
Teach Refactoring
Teach the basics, the bare minimum of OO principles, then teach Refactoring hands-on.
Traditional Way: Abstractions > Jargon Cloud > Trivial Implementation > Practical Use
(Can you spot the disconnect here? One of these transitions is harder than the others.)
In my experience most traditional education does not do a good job in getting programmers to actually grok OO principles. Instead they learn a bit of the syntax, some jargon they have a vague understanding of, and a couple canonical design examples that serve as templates for a lot of what they do. This is light years from the sort of thorough understanding of OO design and engineering one would desire competent students to obtain. The result tends to be that code gets broken down into large chunks in what might best be described as object-libraries, and the code is nominally attached to objects and classes but is very, very far from optimal. It's exceedingly common, for example, to see several hundred line methods, which is not very OO at all.
Provide Contrast To Sharpen The Focus on the Value of OO
Teach students by giving them the tools up front to improve the OO design of existing code, through refactoring. Take a big swath of procedural code, use extract method a bunch of times using meaningful method names, determine groups of methods that share a commonality and port them off to their own class. Replace switch/cases with polymorphism. Etc. The advantages of this are many. It gives students experience in reading and working with existing code, a key skill. It gives a more thorough understanding of the details and advantages of OO design. It's difficult to appreciate the merits of a particular OO design pattern in vacuo, but comparing it to a more procedural style or a clumsier OO design puts those merits in sharp contrast.
Build Knowledge Through Mental Models and Expressive Terminology
The language and terminology of refactoring help students in understanding OO design, how to judge the quality of OO designs and implementations through the idea of code smells. It also provides students a framework with which to discuss OO concepts with their peers. Without the models and terminology of, say, an automobile transmission, mechanics would have a difficult time communicating with each other and understanding automobiles. The same applies to OO design and software engineering. Refactoring provides abundant terminology and mental models (design patterns, code smells and corresponding favored specific refactorings, etc.) for the components and techniques of software engineering.
Build an Ethic of Craftsmanship
By teaching students that design is not set in stone you bolster students' confidence in their ability to experiment, learn, and discover. By getting their hands dirty they'll feel more empowered in tackling software engineering problems. This confidence and practical skill will allow them to truly own the design of their work (because they will always have the skills and experience to change that design, if they desire). This ownership will hopefully help foster a sense of responsibility, pride, and craftsmanship.
First, pick a language like C# or Java and have plenty of samples to demonstrate. Always show them the big picture or the big idea before getting into the finer details of OO concepts like abstraction or encapsulation. Be prepared to answer a lot of why questions with sufficient real world examples.
I'm kinda surprised there's any pure procedural programmers left ;-)
But, as someone who started coding back in the early 80s on procedural languages such as COBOL, C and FORTRAN, I remember the thing I had most difficulty with was instantiation. The concept of an object itself wasn't that hard as basically they are 'structures with attached methods' (looked at from a procedural perspective) but handling how and when I instantiated an object - and in those days without garbage collection - destroyed them caused me some trouble.
I think this arises because in some sense a procedural programmer can generally point to any variable in his code any say that's where that item of data is directly stored, whereas as soon as you instantiated an object and assign values to that then it's much less directly tangible (using pointers and memory allocation in C is of course similar, which may be a useful starting point also if your students have C experience). In essence I suppose it means that your procedural -> OOPS programmer has to learn to handle another level of abstraction in their code, and getting comfortable with this mental step is more difficult than it appears. By extension I'd therefore make sure that your students are completely comfortable with allocating and handling objects before looking at such potentially confusing concepts as static methods.
I'd recommend taking a look at Head First Design Patterns which has really nice and easy to understand examples of object oriented design which should really help. I wouldn't emphasize the 'patterns' aspect too much at this point though.
I'm a vb.net intermediate programmer, and I'm learning OOP. One of the things I find is the lecturing about the concepts over and over is unnerving. I think what would be perfect documentation would be a gradual transition from procedural programming to full blown OOP rather than trying to force them to understand the concepts then have them write exclusively OOP code using all the concepts. That way they can tinker with little projects like "hello world" without the intimidation of design.
For example (this is for VB.NET beginners not advanced procedural programmers).
I think the first chapters should always be about the general concepts, with just a few examples, but you should not force them to code strictly OOP right away, get them used to the language, so that it's natural for them. When I first started, I had to go back and read the manual over and over to remember HOW to write the code, but I had to wade through pages and pages of lecturing about concepts. Painful!
I just need to remember how to create a ReadOnly Property, or something. What would be real handy would be a section of the book that is a language reference so you can easily look in there to find out HOW to write the code.
Then you briefly explaining how forms, and all the objects are already objects, that have methods, and show how they behave, and example code.
Then show them how to create a class, and have them create a class that has properties, and methods, and the new construct. Then have them basically switch from them using procedural code in the form or modules, to writing methods for classes.
Then you just introduce more advance codes as you would any programming language.
Show them how inheritance works, etc. Just keep expanding, and let them use thier creativity to discover what can be done.
After they get used to writing and using classes, then show how thier classes could improve, introducing the concepts one by one in the code, modifying the existing projects and making them better. One good idea is to take an example project in procedural code, and transform it into a better application in OOP showing them all the limitations of OOP.
Now after that is the advanced part where you get into some really advanced OOP concepts, so that folks who are familar with OOP already get some value out of the book.
Define an object first, not using some silly animal, shape, vehicle example, but with something they already know. The C stdio library and the FILE structure. It's used as an opaque data structure with defined functions. Map that from a procedural use to an OO usage and go from there to encapsulation, polymorphism, etc.
If they are good procedural programmers and know what a structure and a pointer to a function are, the hardest part of the job is already done!
I think a low level lecture about how Object Oriented Programming can be implemented in procedural languages, or even assembler, could be cool. Then they will appreciate the amount of work that the compiler does for them; and maybe they will find coding patterns that they already knew and have used previously.
Then, you can talk about best practices in good Object Oriented design and introduce a bit of UML.
And a very important thing to keep in mind always is that they're not freshmen, don't spend much time with basic things because they'll get bored.
Show Design Patterns in Examples
There where some plenty good answers, alright. I also think, that you should use good languages, good, skillful examples, but I have an additional suggestion:
I have learned what OOP means, by studying Design Patterns. Of course, I have of course learned an OO-language before, but until I was working on Design Patterns, I did not understand the power of it all.
I also learned much from OO-Gurus like Robert C. Martin and his really great papers (to be found on his companies site).
Edit: I also advocate the use of UML (class diagrams) for teaching OO/Design-Pattern.
The thing that made it click for me was introducing Refactoring and Unit Testing. Most of my professional programming career has been in OO Languages, but I spent most of it writing procedural code. You call a function on an instance of class X, and it called a different method on an instance of class Y. I didn't see what the big deal about interfaces was, and thought that inheritance was simply a concept of convenience, and classes were by and large a way of helping us sort and categorize the massive code. If one was masochistic enough, they could have easily go through some of my old projects and inline everything until you get to one massive class. I'm still acutely embarrassed at how bad my code was, how naive my architecture was.
It half-clicked when we went through Martin Fowler's Refactoring book, and then fully clicked when started going through and writing Unit and Fitnesse tests for our code, forcing us to refactor. Start pushing refactoring, dependency injection, and separation of the code into distinct MVC models. Either it will sink in, or their heads will explode.
If someone truly doesn't get it, maybe they aren't cut out for working on OO, but I don't think anyone from our team got completely lost, so hopefully you'll have the same luck.
I'm an OO developer professionally, but have had had procedural developers on my development team (they were developing Matlab code, so it worked). One of the concepts that I like in OO programming is how objects can relate to your domain (http://en.wikipedia.org/wiki/Domain-driven_design - Eric Evans wrote a book on this, but it is not a beginner's book by any stretch).
With that said, I would start with showing OO concepts at a high level. Try to have them design a car for example. Most people would say a car has a body, engine, wheels, etc. Explain how those can relate to real world objects.
Once they seem to grasp that high level concept, then I would start in on the actual code part of it and concepts like inheritance vs aggregation, polymorphism, etc.
I learned about OOP during my post-secondary education. They did a fairly good job of explaining the concepts, but completely failed in explaining why and when. They way they taught OOP was that absolutely everything had to be an object and procedural programming was evil for some reason. The examples they were giving us seemed overkill to me, partly because objects didn't seem like the right solution to every problem, and partly because it seemed like a lot of unnecessary overhead. It made me despise OOP.
In the years since then, I've grown to like OOP in situations where it makes sense to me. The best example I can think of this is the most recent web app I wrote. Initially it ran off a single database of its own, but during development I decided to have it hook into another database to import information about new users so that I could have the application set them up automatically (enter employee ID, retrieves name and department). Each database had a collection of functions that retrieved data, and they depended on a database connection. Also, I wanted an obvious distinction which database a function belonged to. To me, it made sense to create an object for each database. The constructors did the preliminary work of setting up the connections.
Within each object, things are pretty much procedural. For example, each class has a function called getEmployeeName() which returns a string. At this point I don't see a need to create an Employee object and retrieve the name as a property. An object might make more sense if I needed to retrieve several pieces of data about an employee, but for the small amount of stuff I needed it didn't seem worth it.
Cost. Explain how when properly used the features of the language should allow software to be written and maintained for a lower cost. (e.g. Java's Foo.getBar() instead of the foo->bar so often seen in C/C++ code).Otherwise why are we doing it?
I found the book Concepts, Techniques, and Models of Computer Programming to be very helpful in understanding and giving me a vocabulary to discuss the differences in language paradigms. The book doesn't really cover Java or C# as 00-languages, but rather the concepts of different paradigms. If i was teaching OO i would start by showing the differences in the paradigms, then slowly the differences in the 00-languages, the practical stuff they can pickup by themselves doing coursework/projects.
When I moved from procedural to object oriented, the first thing I did was get familiarized with static scope.
Java is a good language to start doing OO in because it attempts to stay true to all the different OO paradigms.
A procedural programmer will look for things like program entry and exit points and once they can conceptualize that static scope on a throwaway class is the most familiar thing to them, the knowledge will blossom out from there.
I remember the lightbulb moment quite vividly. Help them understand the key terms abstract, instance, static, methods and you're probably going to give them the tools to learn better moving forward.

Practical uses of OOP

I recently had a debate with a colleague who is not a fan of OOP. What took my attention was what he said:
"What's the point of doing my coding in objects? If it's reuse then I can just create a library and call whatever functions I need for whatever task is at hand. Do I need these concepts of polymorphism, inheritance, interfaces, patterns or whatever?"
We are in a small company developing small projects for e-commerce sites and real estate.
How can I take advantage of OOP in an "everyday, real-world" setup? Or was OOP really meant to solve complex problems and not intended for "everyday" development?
My personally view: context
When you program in OOP you have a greater awareness of the context. It helps you to organize the code in such a way that it is easier to understand because the real world is also object oriented.
The good things about OOP come from tying a set of data to a set of behaviors.
So, if you need to do many related operations on a related set of data, you can write many functions that operate on a struct, or you can use an object.
Objects give you some code reuse help in the form of inheritance.
IME, it is easier to work with an object with a known set of attributes and methods that it is to keep a set of complex structs and the functions that operate on them.
Some people will go on about inheritance and polymorphism. These are valuable, but the real value in OOP (in my opinion) comes from the nice way it encapsulates and associates data with behaviors.
Should you use OOP on your projects? That depends on how well your language supports OOP. That depends on the types of problems you need to solve.
But, if you are doing small websites, you are still talking about enough complexity that I would use OOP design given proper support in the development language.
More than getting something to just work - your friend's point, a well designed OO design is easier to understand, to follow, to expand, to extend and to implement. It is so much easier for example to delegate work that categorically are similar or to hold data that should stay together (yes even a C struct is an object).
Well, I'm sure a lot of people will give a lot more academically correctly answers, but here's my take on a few of the most valuable advantages:
OOP allows for better encapsulation
OOP allows the programmer to think in more logical terms, making software projects easier to design and understand (if well designed)
OOP is a time saver. For example, look at the things you can do with a C++ string object, vectors, etc. All that functionality (and much more) comes for "free." Now, those are really features of the class libraries and not OOP itself, but almost all OOP implementations come with nice class libraries. Can you implement all that stuff in C (or most of it)? Sure. But why write it yourself?
Look at the use of Design Patterns and you'll see the utility of OOP. It's not just about encapsulation and reuse, but extensibility and maintainability. It's the interfaces that make things powerful.
A few examples:
Implementing a stream (decorator pattern) without objects is difficult
Adding a new operation to an existing system such as a new encryption type (strategy pattern) can be difficult without objects.
Look at the way PostgresQL is
implemented versus the way your
database book says a database should
be implemented and you'll see a big
difference. The book will suggest
node objects for each operator.
Postgres uses myriad tables and
macros to try to emulate these nodes.
It is much less pretty and much
harder to extend because of that.
The list goes on.
The power of most programming languages is in the abstractions that they make available. Object Oriented programming provides a very powerful system of abstractions in the way it allows you to manage relationships between related ideas or actions.
Consider the task of calculating areas for an arbitrary and expanding collection of shapes. Any programmer can quickly write functions for the area of a circle, square, triangle, ect. and store them in a library. The difficulty comes when trying to write a program that identifies and calculates the area of an arbitrary shape. Each time you add a new kind of shape, say a pentagon, you would need to update and extend something like an IF or CASE structure to allow your program to identify the new shape and call the correct area routine from your "library of functions". After a while, the maintenance costs associated with this approach begin to pile up.
With object-oriented programming, a lot of this comes free-- just define a Shape class that contains an area method. Then it doesn't really matter what specific shape you're dealing with at run time, just make each geometrical figure an object that inherits from Shape and call the area method. The Object Oriented paradigm handles the details of whether at this moment in time, with this user input, do we need to calculate the area of a circle, triangle, square, pentagon or the ellipse option that was just added half a minute ago.
What if you decided to change the interface behind the way the area function was called? With Object Oriented programming you would just update the Shape class and the changes automagically propagate to all entities that inherit from that class. With a non Object Oriented system you would be facing the task of slogging through your "library of functions" and updating each individual interface.
In summary, Object Oriented programming provides a powerful form of abstraction that can save you time and effort by eliminating repetition in your code and streamlining extensions and maintenance.
Around 1994 I was trying to make sense of OOP and C++ at the same time, and found myself frustrated, even though I could understand in principle what the value of OOP was. I was so used to being able to mess with the state of any part of the application from other languages (mostly Basic, Assembly, and Pascal-family languages) that it seemed like I was giving up productivity in favor of some academic abstraction. Unfortunately, my first few encounters with OO frameworks like MFC made it easier to hack, but didn't necessarily provide much in the way of enlightenment.
It was only through a combination of persistence, exposure to alternate (non-C++) ways of dealing with objects, and careful analysis of OO code that both 1) worked and 2) read more coherently and intuitively than the equivalent procedural code that I started to really get it. And 15 years later, I'm regularly surprised at new (to me) discoveries of clever, yet impressively simple OO solutions that I can't imagine doing as neatly in a procedural approach.
I've been going through the same set of struggles trying to make sense of the functional programming paradigm over the last couple of years. To paraphrase Paul Graham, when you're looking down the power continuum, you see everything that's missing. When you're looking up the power continuum, you don't see the power, you just see weirdness.
I think, in order to commit to doing something a different way, you have to 1) see someone obviously being more productive with more powerful constructs and 2) suspend disbelief when you find yourself hitting a wall. It probably helps to have a mentor who is at least a tiny bit further along in their understanding of the new paradigm, too.
Barring the gumption required to suspend disbelief, if you want someone to quickly grok the value of an OO model, I think you could do a lot worse than to ask someone to spend a week with the Pragmatic Programmers book on Rails. It unfortunately does leave out a lot of the details of how the magic works, but it's a pretty good introduction to the power of a system of OO abstractions. If, after working through that book, your colleague still doesn't see the value of OO for some reason, he/she may be a hopeless case. But if they're willing to spend a little time working with an approach that has a strongly opinionated OO design that works, and gets them from 0-60 far faster than doing the same thing in a procedural language, there may just be hope. I think that's true even if your work doesn't involve web development.
I'm not so sure that bringing up the "real world" would be as much a selling point as a working framework for writing good apps, because it turns out that, especially in statically typed languages like C# and Java, modeling the real world often requires tortuous abstractions. You can see a concrete example of the difficulty of modeling the real world by looking at thousands of people struggling to model something as ostensibly simple as the geometric abstraction of "shape" (shape, ellipse, circle).
All programming paradigms have the same goal: hiding unneeded complexity.
Some problems are easily solved with an imperative paradigm, like your friend uses. Other problems are easily solved with an object-oriented paradigm. There are many other paradigms. The main ones (logic programming, functional programming, and imperative programming) are all equivalent to each other; object-oriented programming is usually thought as an extension to imperative programming.
Object-oriented programming is best used when the programmer is modeling items that are similar, but not the same. An imperative paradigm would put the different kinds of models into one function. An object-oriented paradigm separates the different kinds of models into different methods on related objects.
Your colleague seems to be stuck in one paradigm. Good luck.
To me, the power of OOP doesn't show itself until you start talking about inheritance and polymorphism.
If one's argument for OOP rests the concept of encapsulation and abstraction, well that isn't a very convincing argument for me. I can write a huge library and only document the interfaces to it that I want the user to be aware of, or I can rely on language-level constructs like packages in Ada to make fields private and only expose what it is that I want to expose.
However, the real advantage comes when I've written code in a generic hierarchy so that it can be reused later such that the same exact code interfaces are used for different functionality to achieve the same result.
Why is this handy? Because I can stand on the shoulders of giants to accomplish my current task. The idea is that I can boil the parts of a problem down to the most basic parts, the objects that compose the objects that compose... the objects that compose the project. By using a class that defines behavior very well in the general case, I can use that same proven code to build a more specific version of the same thing, and then a more specific version of the same thing, and then yet an even more specific version of the same thing. The key is that each of these entities has commonality that has already been coded and tested, and there is no need to reimpliment it again later. If I don't use inheritance for this, I end up reimplementing the common functionality or explicitly linking my new code against the old code, which provides a scenario for me to introduce control flow bugs.
Polymorphism is very handy in instances where I need to achieve a certain functionality from an object, but the same functionality is also needed from similar, but unique types. For instance, in Qt, there is the idea of inserting items onto a model so that the data can be displayed and you can easily maintain metadata for that object. Without polymorphism, I would need to bother myself with much more detail than I currently do (I.E. i would need to implement the same code interfaces that conduct the same business logic as the item that was originally intended to go on the model). Because the base class of my data-bound object interacts natively with the model, I can instead insert metadata onto this model with no trouble. I get what I need out of the object with no concern over what the model needs, and the model gets what it needs with no concern over what I have added to the class.
Ask your friend to visualize any object in his very Room, House or City... and if he can tell a single such object which a system in itself and is capable of doing some meaningful work. Things like a button isnt doing something alone - it takes lots of objects to make a phone call. Similarly a car engine is made of the crank shaft, pistons, spark plugs. OOPS concepts have evolved from our perception in natural processes or things in our lives. The "Inside COM" book tells the purpose of COM by taking analogy from a childhood game of identifying animals by asking questions.
Design trumps technology and methodology. Good designs tend to incorporate universal principals of complexity management such as law of demeter which is at the heart of what OO language features strive to codify.
Good design is not dependant on use of OO specific language features although it is typically in ones best interests to use them.
Not only does it make
programming easier / more maintainable in the current situation for other people (and yourself)
It is already allowing easier database CRUD (Create, Update, Delete) operations.
You can find more info about it looking up:
- Java : Hibernate
- Dot Net : Entity Framework
See even how LINQ (Visual Studio) can make your programming life MUCH easier.
Also, you can start using design patterns for solving real life problems (design patterns are all about OO)
Perhaps it is even fun to demonstrate with a little demo:
Let's say you need to store employees, accounts, members, books in a text file in a similar way.
.PS. I tried writing it in a PSEUDO way :)
the OO way
Code you call:
io.file.save(objectsCollection.ourFunctionForSaving())
class objectsCollection
function ourFunctionForSaving() As String
String _Objects
for each _Object in objectsCollection
Objects &= _Object & "-"
end for
return _Objects
end method
NON-OO Way
I don't think i'll write down non-oo code. But think of it :)
NOW LET'S SAY
In the OO way. The above class is the parent class of all methods for saving the books, employees, members, accounts, ...
What happens if we want to change the way of saving to a textfile? For example, to make it compactible with a current standard (.CVS).
And let's say we would like to add a load function, how much code do you need to write?
In the OO- way you only need the add a New Sub method which can split all the data into parameters (This happens once).
Let your collegue think about that :)
In domains where state and behavior are poorly aligned, Object-Orientation reduces the overall dependency density (i.e. complexity) within these domains, which makes the resulting systems less brittle.
This is because the essence of Object-Orientation is based on the fact that, organizationally, it doesn't dustinguish between state and behavior at all, treating both uniformly as "features". Objects are just sets of features clumpled to minimize overall dependency.
In other domains, Object-Orientation is not the best approach. There are different language paradigms for different problems. Experienced developers know this, and are willing to use whatever language is closest to the domain.

What should be OO and what shouldn't?

I've read a lot of people saying that some things shouldn't be written in an object orientated style - as a person learning the OO style coming from a C background, what do they mean by this?
What shouldn't be OO, why do some things fit this design better, and how do we know when it's best to do what?
The real world is full of objects.
It's helpful to make the software world match the real world.
"What about 'system utilities'? They just deal with abstractions like sockets and processes and file systems." They sound like things to me. They have attributes and behaviors, they have associations.
If you're looking for proof that OO is better, there isn't any. Nothing is better because better is a gloriously vague term. Anyone who's clever can write any program in any style. You could adopt functional, procedural, object-oriented, or anything you feel like.
I use OO because I have a very small brain and must learn to live within its limits. OO is a crutch to help me struggle through programming. If I was smarter, richer and better-looking, I wouldn't need the help, and I could write non-OO programs. Sadly, I'm not smart. Without class definitions to isolate responsibility and structure an architecture, I'd still be writing single-file "hello world" variants.
A simple rule of thumb is to encapsulate complex data and repeatedly used code, and to ignore what isn't. This lets you put complicated data structures together with their manipulative methods for greater portability and flexibility. Such as a list of database objects with intelligent sorting by property type.
OO code also obfuscates what you don't need to know. Such as, I don't need to know what my sort algorithm is until it slows me down, or if I'm already programming for a high performance environment.
Another great thing about OO code is its polymorphism, the way you can use subsequent types to change actions without the program knowing how or caring about it. An example is an archive format with multiple file-list types: the list may have an array of structures (records or structs) within it that changes between the types of list, but inherit from a base class and the complexity of knowing which underlying structure to use goes away. It would be quite difficult to manage that without object orientation, and quite frankly it's tough enough to manage as it is with object orientation.
OO and MVC do not solve your problems if you don't know how to solve them already, they merely give you more powerful ways to shoot yourself in the foot—only this time you might not know why. So remember that if it's anything, OO isn't the "magic bullet" ... but remember that it can be the magic bullet given the right situation and the right programmer.
Object Oriented design is all about managing complexity as your system grows. Therefore OO design can be overkill for smaller less complex systems, or for systems that you know will never grow.
Of course the problem is that we rarely know with certainty that a system is not going to grow.
I agree with most of the above (or below?) that OO exists to simplify complex problems and software design.
However, there are many times where it is extremely overdone. I can't tell you the number of times where I wish there was a Visual Studio Unrefactor button just to make sense of the code and put all base classes in one file for readability.
I can't think of anything other than stored procedures. Get yourself a copy of Reflector and use it to look at the .NET framework dll's as a good learning lesson. Alternately there are a ton of books on C++ and OO on the market since thats been around a while.
If you're writing mobile applications (at least I can speak for .NET mobile), then you should try to be as non-OO as possible. As much as mobile has advanced, you don't want to waste system memory because you've tied up processing with abstraction layers, large datasets in memory, or other entities that will slow things down. You'll want to write things as straightforward as possible.
Just a tip: you should tag this question as "subjective" as everyone seems to have a different opinion on things like this.

When is OOP better suited for? [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
Since I started studying object-oriented programming, I frequently read articles/blogs saying functions are better, or not all problems should be modeled as objects. From your personal programming adventures, when do you think a problem is better solved by OOP?
There is no hard and fast rule. A problem is better solved with OOP when you are better at solving problems and thinking in an OO mentality. Object Orientation is just another tool which has come along through trying to make computing a better tool for solving problems.
However, it can allow for better code reuse, and can also lead to neater code. But quite often these highly praised qualities are, in-relity, of little real value. Applying OO techniques to an existing functional application could really cause a lot of problems. The skill lies in learning many different techniques and applying the most appropriate to the problem at hand.
OO is often quoted as a Nirvana-like solution to the software development, however there are many times when it is not appropriate to be applied to the issue at hand. It can, quite often, lead to over-engineering of a problem to reach the perfect solution, when often it is really not necessary.
In essence, OOP is not really Object Oriented Programming, but mapping Object Oriented Thinking to a programming language capable of supporting OO Techniques. OO techniques can be supported by languages which are not inherently OO, and there are techniques you can use within functional languages to take advantage of the benefits.
As an example, I have been developing OO software for about 20 years now, so I tend to think in OO terms when solving problems, irrespective of the language I am writing in. Currently I am implementing polymorphism using Perl 5.6, which does not natively support it. I have chosen to do this as it will make maintenance and extension of the code a simple configuration task, rather than a development issue.
Not sure if this is clear. There are people who are hard in the OO court, and there are people who are hard in the Functional court. And then there are people who have tried both and try to take the best from each. Neither is perfect, but both have some very good traits that you can utilise no matter what the language.
If you are trying to learn OOP, don't just concentrate on OOP, but try to utilise Object Oriented Analysis and general OO principles to the whole spectrum of the problem solution.
I'm an old timer, but have also programmed OOP for a long time. I am personally against using OOP just to use it. I prefer objects to have specific reasons for existing, that they model something concrete, and that they make sense.
The problem that I have with a lot of the newer developers is that they have no concept of the resources that they are consuming with the code that they create. When dealing with a large amount of data and accessing databases the "perfect" object model may be the worst thing you can do for performance and resources.
My bottom line is if it makes sense as an object then program it as an object, as long as you consider the performance/resource impact of the implementation of your object model.
I think it fits best when you are modeling something cohesive with state and associated actions on those states. I guess that's kind of vague, but I'm not sure there is a perfect answer here.
The thing about OOP is that it lets you encapsulate and abstract data and information away, which is a real boon in building a large system. You can do the same with other paradigms, but it seems OOP is especially helpful in this category.
It also kind of depends on the language you are using. If it is a language with rich OOP support, you should probably use that to your advantage. If it doesn't, then you may need to find other mechanisms to help break up the problem into smaller, easily testable pieces.
I am sold to OOP.
Anytime you can define a concept for a problem, it can probably be wrapped in an object.
The problem with OOP is that some people overused it and made their code even more difficult to understand. If you are careful about what you put in objects and what you put in services (static classes) you will benefit from using objects.
Just don't put something that doesn't belong to an object in the object because you need your object to do something new that you didn't think of initially, refactor and find the best way to add that functionality.
There are 5 criteria whether you should favor Object Oriented over Object Based,Functional or Procedural code. Remember all of these styles are available in all languages, they're styles. All of these are written in a style of "Should I favor OO in this situation?"
The system is very complex and has over approximately 9k LOC (Just an arbitrary level). -- As systems get more complex, the benefits gained by encapsulating complexity go up quite a bit. With OO, as opposed to the other techniques, you tend to encapsulate more and more of the complexity, which is very valuable at this level. Object Based or procedural should be favored before this. (This is not advocating a particular language mind you. OO C fits these features more than OO C++ in my mind, a language with a notorious reputation for leaky abstractions and an ability to eat shops with even 1 mediocre/obstinate programmer for lunch).
Your code is not operations on data (i.e. Database based or math/analysis based). Database based code is often more easily represented via procedural style. Analysis based code is often easier represented in a functional style.
Your model is a simulation of something (OO excels at simulations).
You're doing something for which the object based subtype dispatch of OO is valuable (aka, you need to send a message to all objects of a certain type and various subtypes and get an appropriate, but different, reaction out of all of them).
Your app is not multi-threaded, especially in a non-worker task method type of codebase. OO is quite problematic in programs which are multithreaded and require different threads to do different tasks. If your program is structured with one or two main threads and many worker threads doing the same thing, the muddled control flow of OO programs is easier to handle, as all of the worker threads will be isolated in what they touch and can be considered as a monolithic section of code. Consider any other paradigm actually. Functional excels at multithreading (lack of side effects is a huge boon), and object based programming can give you boons with some of the encapsulation of OO, however with more traceable procedural code in critical sections of your codebase. Procedural of course excels in this arena as well.
Some places where OO isn't so good are where you're dealing with "Sets" of data like in SQL. OO tends to make set based operations more difficult because it isn't really designed to optimally take the intersection of two sets or the superset of two sets.
Also, there are times when a functional approach would make more sense such as this example taken from MSDN:
Consider, for example, writing a program to convert an XML document into a different form of data. While it would certainly be possible to write a C# program that parsed through the XML document and applied a variety of if statements to determine what actions to take at different points in the document, an arguably superior approach is to write the transformation as an eXtensible Stylesheet Language Transformation (XSLT) program. Not surprisingly, XSLT has a large streak of functionalism inside of it
I find it helps to think of a given problem in terms of 'things'.
If the problem can be thought of as having one or more 'things', where each 'thing' has a number of attributes or pieces of information that refer to its state, and a number of operations that can be performed on it - then OOP is probably the way to go!
The key to learning Object Oriented Programming is learning about Design Pattern. By learning about design patterns you can see better when classes are needed and when they are not. Like anything else used in programming the use of classes and other features of OOP languages depends on your design and requirements. Like algorithms Design patterns are a higher level concept.
A Design Pattern plays similar role to that of algorithms for traditional programming languages. A design pattern tells you how create and combine object to perform some useful task. Like the best algorithms the best design patterns are general enough to be application to a variety of common problems.
In my opinion it is more a question about you as a person. Certain people think better in functional terms and others prefer classes and objects. I would say that OOP is better suited when it matches your internal (subjective) mental model of the world.
Object oriented code and procedural code have different extensibility points. Object oriented solutions make it easier to add new classes without modifying existing functions (see the Open-Closed Principle), while procedural code allows you to add functions without modifying existing data structures. Quite often different parts of a system require different approaches depending upon the type of change that is anticipated.
OO allows for logic related to an object to be placed within a single place (the class, or object) so that it can be decoupled and easier to debug and maintain.
What I have observed, is that every app is a combination of OO and procedural code, where the procedural code is the glue that binds all your objects together (at the very least, the code in your main function). The more you can turn your procedural code into OO, the easier it will be to maintain yor code.
Why OOP is used for programming:
Its flexibility – OOP is really flexible in terms of use implementations.
It can reduce your source codes by more than 99.9% – it may sound like I’m over exaggerating, but it is true.
It’s much easier in implementing security – We all know that security is one of the vital requirements when it comes to web development. Using OOP can ease the security implementations in your web projects.
It makes the coding more organized – We all know that a Clean Program is a Clean Coding. Using OOP instead of procedural makes things more organized and systematized (obviously).
It helps your team to work with each other easily – I know some of you had/have experienced team projects and some of you guys know that it’s important to have the same method, implementations, algorithm etc etc etc
It depends by the problem: the OOP paradigm is useful in designing distribuited systems or framework with a lot of entity living during the actions of the user (example: web application).
But if you have a math problem you will prefer a functional language (LISP); for a performance-critical systems you will use ADA or C, etc etc.
The language OOP is useful because too it use probabily the garbage collector (automatic use of memory) in the run of program: you you program in C a lot of time you must debug and correct manually a problem of memory.
OOP is useful when you have things. A socket, a button, a file. If you end a class in er it is almost always a function that is pretending to be a class. TestRunner more than likely should be a function that runs tests(and probably named run tests).
Personally, I think OOP is practically a necessity for any large application. I can't imagine having a program over 100k lines of code without using OOP, it would be a maintenance and design nightmare.
I tell you when OOP is bad.
When the architect writes really complicated, non-documented OOP code. Leaves half way through the project. And many of his common code pieces he used across various project has missing code. Thank god for .NET Reflector.
And the organization was not running Visual Source Safe or Subversion.
And I'm sorry. 2 pages of code to login is rather ridiculous even if it is cutely OOPed....