开发者

Why I can't see a real point for using OOP? [duplicate]

This question already has answers here: Closed 12 years ago.

Possible Duplicate:

Classes. Whats the point?

I've read tons of tutorials, wrote many classes, used them, but I still can't figure out some OOP points.

I mean, I think I got the theory. It's a paradigm, a different way to think and solve a problem. I know all commom points: code reuse, encapsulation, better error handling, easier maintenance, inheritance, design by contract, better documentation, aggregation, composition, some design patterns...

That said, let's go to the real deal. Let's say I have the following:

  • a database, and a class to access and query it.
  • I have a table named person and another table named address
  • Simple business rule: one person can have one or more address (home, work, delivery...), a simple one to many relationship
  • I have a highlevel class for commom operations (CRUD). Each table has a class that is a extension from this one.
  • Of course, each class (person and address) have their own methods: eg, getAddressByLocation or getPersonsByAge.
  • Also there are a dozen views and a couple forms

All this is awesome and sure useful but... I can't stop thinking in the simplest case: listing some people. Yes because every row on the output table is made upon one class instance. I can't stop thinking on how much memory and cpu is used on not used resources.

Listing 50 people means creating 50 instances, full of resources like crud, filtering processing uploads, validating rules and so on when what I need is to run a query and just output results with a simple loop.

This confuses me a lot. And not just confuse, as I already saw some apps where runtime increases exponentialy with database when business rules are a little more complex.

I think, is the case to create new classes or plain scripts to just handle the outputs and reports? If yes, so this mean double effort, making use of OOP pointless, once I would need to create many different classes for same database entity. Coding turns harder, maintenance turns no cool.

Am I missing something? Or this is a drawback of OOP approach?

Should we sacrifice a straight to t开发者_如何学运维he point, thin, faster code in order to get faster development and maintenance?

EDIT

As expected, some points I put before were misleading for some guys...

First, I'm seasoned to really really big projects (I worked at IBM vendoring for Sprint/Nextel USA and Directv North America, so I'm used to see some terabytes being processed daily).

When I said 50 people being retrieved from database, I don't mean strictly 50 people, I just want to gave the idea of many records. I know 50 records is nothing to today's servers. 50 million are. Imagine this last number if appropriate.


Here's the crux of the issue. As has been said before, there are tradeoffs to each and every paradigm. OOP has a lot of benefits, but it also has some negatives as you point out. The key is weighing them.

OOP is founded on the principal that developers are expensive and hardware is cheap. It uses this principal to lead towards highly maintainable (easy to fix in the long run) and highly adaptable code (easy to change in the long run). And if you buy the 60/60 Rule (which says that 60% of development time is in maintenance and 60% of that time is due to enhancements), then maintainability is the ultimate goal for professional programming.

If you get your head around how OOP works (I'm talking to the point of where you are thinking in a OOP paradigm) everything becomes really easy. I think you're still getting confused because you don't fully understand OOP. But then again, it's not the holy-grail of programming either, so if you're more comfortable using another paradigm, by all means use it. Choices exist because we are not all identical. Use what you're best at and what fits what you are trying to do best. If the only tool you have is a hammer, every problem looks like a nail...

Oh, and contrary to popular opinion, OOP is not about never coding anything twice. That's the DRY (Don't Repeat Yourself) principal. While it's often used with OOP, it's not directly attached to. In fact, I'd suggest while developing that you don't follow DRY as a rule. Shoot for it as a goal, but let it be a guideline more than a rule. As Fred Brooks said, plan to throw one away; you will, anyhow. (From The Mythical Man-Month ). If you strictly never repeat yourself, you're going to wind up re-doing a lot of work when it comes time to throw something away that you didn't get right the first time around. Only when it's built and running good should you start slimming it down and really making the code DRY. (personal opinion at least)...


It's as you said, a paradigm. It has strengths and weaknesses like any other paradigm. Where I think you're mistaken is the notion of what is materially significant. What makes 50 instances a big number? Perhaps to you keeping track of 50 discreet things is difficult (likely so for all humans), but that doesn't mean it's difficult for a computer. That 50 isn't big just because it seems big to you. It is certainly big compared to your example of a simple script to retrieve the data and collate the results, but the tradeoffs should be obvious, you listed most of them when you pointed out the strengths of OOP. The more interesting point to consider is when those strengths outweigh the weaknesses. Much more goes into that judgment call than what you've identified here, including the size of the codebase, the number of developers involved, their relative skill to each other, how long the code will remain in production, and much more.


To provide you a simple example about what seems to be your main concern :

$list = DB::query($query);

foreach ($list as $person)
{
  // $person->name
  // $person->address
  // .. and so on 
}

First of all, if you come to a point were you have an instance of a class per person, when you want a list of them, then it's bad programming from the very beginning and you should review your own knowledge of OOP (trying not to be rude, sorry if I am).


I'm afraid that what you are missing is the real experience of working long time with a big project. That means you have 100% theoretical concepts, but they are theoretical. When I first learned programming function (in C), I wondered why we need this. But then when I started coding something bigger than before I realized why we need them. Same happens when I first learned OOP. Why we need this? But now I can't think much without it. So my summery is, try to contribute in some real big project. At least in software development, only theory is not sufficient.

And if you are already experienced with enough big projects, then please ignore this answer.


Your are confusing frameworks with the paradigm.

A framework is the structure in which you code to make something easier to maintain. In this case, you are using a framework centered around objects that know how to go out and get their own data.

This is a simplistic approach, and as you've found, can lead to exponential growth in number of queries.

A better way is to create a factory class that returns arrays of Persons with all their addresses. This factory object consolidates your request and runs as few queries as possible before creating objects by passing a row from the database (or a DTO) to each new instance of a Person.

Remember, not all objects are a direct analogue to the real world. People are not made in factories, but you don't really have people there, do you?

Factory + Representative Object + (optionally) a Data Transfer Object is a ROBUST and tried-and-true framework component in most large-scale applications that are Object Oriented.

But not all. There are other ways to skin this cat.

OO isn't the problem here. Your rules are. Your framework that you are working in is. (Self-imposed or 3rd Party, it doesn't matter)

Remember. OOP is about never coding anything twice. Frameworks are about selectively deciding what to code twice in the interest of making the code easy to update, upgrade, and otherwise maintain.


If you look at DDD, you have an independent domain layer that contains the domain entities; each of them containing properties and domain logic. Another layer is infrastructure, which contains the repositories (where your CRUD operations are implemented towards a specific resource and technology).

Retrieving a list of domain entities is done by the repository, and what you get is 50 instances of the domain entities, together with the needed domain logic. You need this information, to be sure that your client doesn't abuse it.

Do you think that getting 50 items with complex domain logic will kill your system?


You're stuck because of the "OOP = paradigm" meme. In reality and regarding PHP, it is just a notational style. When you have a hybrid language you should use the best approach for each application part. And the difference between procedures and objects is just the API look and feel.

Yes, there's grouping and inheritance, and you can abstract away and generalize utility code better with object structures. But for actual behaviour and functionality you shouldn't restrict yourself to either methodology. Not every nail is object-oriented, and not every screw is procedural. It's all about beautifying the API.

Also, forget about the microperformance differences.


Creating 50 instances is nothing... Don't worry about performance until you have an actual problem. Most scripts that take a long time to load is either because they do complex queries or have to fetch remote resources.

As to the effort and maintainability issue -- I think you'll quickly find out that the initial effort to properly structure your program will be worthwhile. For instance, if you then change the name of a column in the database for the persons' tables, you will only need to change one class, not several queries spread out through the application.


If you're writing a short simple piece of code, there's very little overhead when you want to modify it later: even if you have to rewrite it from scratch, it doesn't really matter. As the system grows, you have to design code in a more careful way: document interfaces, provide abstractions, encapsulate complexity, and provide mechanisms to test isolated parts of the system. OO provides one set of design ideas to let you build these into your code.

The difficulty is knowing the difference between simple code that's going to become larger and more complex (in which case, you probably want to start with OO design), and when you've got simple code that's never going to change (in which case you want to do the simplest thing possible and not pay the overhead of going full OO). It's genuinely difficult to pick between these two, although I tend towards assuming code will grow, since the over-engineered small piece of code is only moderately bad compared to the under-engineered code that's grown beyond its initial design.


OOP is an approach to a problem through the application of various concepts. These concepts can be used together in a strict OO fashion or can be mixed and matched with other concepts from other paradigms. Most modern programming languages are no longer purely 1 paradigm or another. They usually incorporate other paradigms and/or concepts from those paradigms. For example "lazy evaluation", a concept from functional programming can be used in concert with OO concepts to create a list of objects that are lazily evaluated. Or you could simply have a lazy list that constructs the objects as needed.

FYI your common points, many of them are shared in other paradigms.


Don't forget testing!

Having solid object that you work with allows you to do dependency injection and provide tests and debug at every level of the application independently. This is a huge boon to developers who like to make their code airtight.

This is especially true if you are using languages like .Net with a structure like MVP, because by separating out objects, you really nail down the layers and code reusability skyrockets.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜