35

I am writing a program in Python, which basically manipulates strings, and I was wondering whether I should do it using OOP principles or not. The client did tell me he doesn't care about the code, he just want the thing done.

I know that object-oriented code is not by definition cleaner, and conversely non-OO code is not by definition crappy. The question I'm asking might be more or less opinion-based but there might be some rules that I'm not aware of.

Some more info about what's to be done:

  • parse a .csv file and process the data based on a config file (the columns may be different - like in the number of columns or the data they hold)
  • use the above processed data to create a new custom formatted data (or multiple files based on some of the above values)
  • use the last formatted data to create an XML file.
  • split the XML file in multiple XMLs based on their content
  • the application should be CLI-based
  • there are of course other things like: logging some events, parse CLI arguments, and so on.

Now, this isn't at all a big / hard application, and it's also almost finished but during the whole development process I was keep asking myself if this should be done using OOP or not.

So, my question would be: how do you guys, know/decide when to use OOP in an application?

closed as too broad by gnat, Daenyth, Thomas Junk, ChrisF Jul 26 '16 at 20:50

Please edit the question to limit it to a specific problem with enough detail to identify an adequate answer. Avoid asking multiple distinct questions at once. See the How to Ask page for help clarifying this question. If this question can be reworded to fit the rules in the help center, please edit the question.

  • 12
    Re, "The client ... doesn't care about the code, he just want the thing done." OK, then do the thing. But how complex is this thing? How well do you really understand the requirements? How likely is it that the client will sometime later ask you to change the thing? Sometimes a quick and dirty hack is all you need, but the more time and energy you're going to invest into it, the more likely that some structured approach to solving the problem (e.g., OO design) will benefit you. – Solomon Slow Jul 26 '16 at 17:27
  • 5
    Don't use "EDIT" or other similar monikers in your posts. Every Stack Exchange post has a detailed edit history that anyone can review. Information like "I didn't ask what OOP was" is more appropriate in a comment anyway, not your question. – Robert Harvey Jul 26 '16 at 17:39
  • @RobertHarvey ok, got it. I'll do this next time. – Grajdeanu Alex. Jul 28 '16 at 8:30
59

Python is a multi-paradigm language which means you can choose the paradigm most appropriate for the task. Some languages like Java are single-paradigm OO which means you will get headaches if you try to use any other paradigm. Posters saying "always use OO" are probably coming from a background in such a language. But fortunately you have a choice!

I note your program is a CLI app which reads some input (csv and config files) and produces some output (xml files), but is not interactive and hence does not have a stateful GUI or API. Such a program is naturally expressed as a function from input to output, which delegate to other functions for subtasks.

OO on the other hand is about encapsulating mutable state and is therefore more appropriate for interactive applications, GUI's, and API's exposing mutable state. It is no coincidence that OO was developed in parallel with the first GUI's.

OO has another advantage in that polymorphism allows you a more loosely coupled architecture, where different implementations of the same interface can be easily substituted. Combined with dependency injection this can allow configuration-based loading of dependencies and other cool stuff. This is mostly appropriate for very large applications though. For a program the size of what you describe, it would be far to much overhead with no apparent benefit.

Apart from the functions actually reading and writing the files, the bulk of your logic can be written as side-effect free functions which takes some input and return some other output. This is eminently easy to test, much simpler than testing OO units where you need to mock dependencies and whatnot.

Bottom line: I suggest a bunch of functions split into modules for organization, but no objects.

  • 8
    Finally a well-balanced answer that does not just sing the praise of OOP :-) – cmaster Jul 26 '16 at 17:02
  • 1
    That's the kind of answer I expected. Could expand a bit your answer ? It looks awesome so far. – Grajdeanu Alex. Jul 26 '16 at 17:12
  • 3
    @Dex'ter: Than you. What kind of additional information do you seek? – JacquesB Jul 26 '16 at 17:18
  • 3
    I'd add to this that Functional Programming could be a paradigm to read up on. – Andrew Piliser Jul 26 '16 at 17:39
  • 1
    @Bergi: Yeah that is the benefit of a multi-paradigm language. You can use OO libraries without having to write your own program in a OO-style. – JacquesB Jul 26 '16 at 20:24
15

Consider a button on a GUI. It has state (it's size, colour, position, label etc). Things can happen to it (it's clicked, needs redrawing etc). In such situations, modelling it as an object makes sense. As an object, it can contain it's state, a set of actions that can be performed on it (methods) and it can notify other parts of the application that things have happened to it by firing events.

OOP is a superb tool for handling GUIs, and other situations where parts of the system have volatile state.

Other situations, such as the one you describe, where data is read from a source, processed and written out to a destination are handled well by a different approach: declarative (or function) programming. Declarative code for data processing tends to both be easier to read and shorter than OOP solutions.

Just as a hammer and saw are both powerful tools when used correctly, so too are object-orientated and declarative programming techniques. You probably could hammer a nail into a piece of wood with the handle of a saw. Likewise, you can break a piece of wood in half with a hammer. Likewise, you can create a GUI with just functions and process data with objects. When the tools are used correctly though, the results are cleaner and simpler.

The general rule of thumb I use is that if I have lots of state, or need user interaction, I use objects; otherwise I use (pure and higher order, where possible) functions.

6

Object-Oriented Programming adds four new tools to your arsenal:

  1. Encapsulation
  2. Abstraction
  3. Inheritance
  4. Polymorphism

You would use OOP in your application when it has grown large enough and complex enough to benefit from these tools.

  • 18
    Abstraction and polymorphism are tools provided by many "orientations" of programming. OOP actually offers a weaker form of encapsulation than other approaches because inheritance encourages leaky abstraction designs. The only thing OOP really adds to the toolkit is inheritance, which is widely seen as a bad thing. – David Arno Jul 26 '16 at 16:53
  • 4
    @DavidArno: You're basically saying "Never use OOP." – Robert Harvey Jul 26 '16 at 17:16
  • 6
    This is off the back of a trying day at work looking at other peoples code,a straight forward procedural implementation of a program is often better than an implementation with a bad understanding of OO design. OO architecture can be very powerful but should be used like a spice in cooking, with expert knowledge and just the right amount. Misusing OO design is about as common as asking for ketchup in a bad restaurant. – Phill Jul 26 '16 at 18:17
  • 6
    None of the four tools (Encapsulation, Abstraction, Inheritance, Polymorphism) is specific to OOP. Maybe you should explain how OOP is different from other paradigms wrt to these dimensions. – Giorgio Jul 26 '16 at 18:34
  • 4
    @gardenhead your odd sense of superiority is doing nothing for your position. Perhaps you should spin up a question titled 'Why are the most employable languages often OO?' Better yet, Ctrl+F and type 'GUI'. – Gusdor Jul 26 '16 at 19:15
1

This question seems a little confused to me. If you are writing it in Python, you are pretty surely going to use objects. When you open a file, it returns an object. When you yield result, it returns an iterator Object. Each function you create is an object. Questioning the value of OO in Python applications seems odd to say the least.

Based on the comments here, yes, Python supports functional paradigms but it's primarily object based. The language itself and built-in libs are oriented around objects. Yes it supports lambda (as does Java and any other number of langauges typically described as OO) but it's intentionally simplistic compared to a true functional language.

Perhaps these distinctions around OO design and functional design are becoming obsolete. If I create take a polymorphic function on an OO designed Object* and pass a pointer to that function on an object as a parameter to functionally styled function*, is that OO or is it functional? I think it's both and also a really effective approach to solving problems.

I think the real question is 'when you should start designing your own classes versus just creating a module with functions?' I think the right answer for that is: when it helps simplify the solution. I'd give the same basic answer for any object oriented language.

*redundancy is intentional: I don't want to be accused here of assuming objects are OO or that functions are functional.

  • 5
    yeah, objects are not equal to OOP. there's a differenct between having an object and structuring your architecture around objects and their interactions. kind of like how if you make a function that doesn't mean you're doing functional programming. – sara Jul 26 '16 at 20:17
  • you could quite easily consider a Python/JavaScript object a Record, which is quite functional. Functional languages have objects. The key is in the second word: orientated. OOP languages are completely orientated around using objects, whereas some other languages just seem them as another part of your toolbox. – Dan Pantry Jul 26 '16 at 21:04
0

One of the biggest thing about object oriented programming is that instead of reasoning about program flow you start reasoning about state.

A lot of times I see the object, I see the methods but what I also see is that the driving thought behind the code is flow instead of state.

And once you reason about state it's easy to build good OOP code because as soon as your code becomes too complex you notice that you can't reason about your state anymore and know you need to refactor.

Consider your example: You want to parse a csv file. Where does it come from: a file on disk. You load it and put it into memory and parse it. Now your client comes: hey I also want to parse files from the web. So you are happy because you made a nice interface for loading your file and only have to make the code that fetches it from the web and the rest of your program stays exactly the same.

And the nice thing is: you can test for that.

  • 3
    Your example with reading a file from disk versus reading a file from web can also be implemented with different functions. You don't need OO for that. – JacquesB Jul 26 '16 at 18:06
0

In layman's terms:

  • You can use OOP or non-OOP in any kind of projects you want.
  • OOP is not the panacea but it helps to manage complexity.
  • It goes beyond modularity, it's about compartmentalization. Think of the different compartments a ship has for retaining buoyancy if the hull is damaged.
  • OOP is a way of managing dependencies so bugs can be easier to track down since there's only a defined set of ways the different components of a program can communicate which other.
  • In a program there are many things working: variables, constants, methods, files, parameters, functions, modules, etc. They can interact with each other in ways that can be sometimes impredictable. OOP is a set of principles that reduce the number of ways things can interact which each other. You are not forced to use OOP to do that, but it helps.

That said, there are other factors to take into account:

  • Are your programmers proficient in OOP/OOD?
  • Are your programmers proficient in an OOP language?
  • Do you think the software will grow complex over time?
  • Do you plan to scale or reuse code in the future?
  • Do you think your "design" can become an asset? i.e. Will you be able to leverage it for growing or as a foundation for future projects?

Don't get me wrong: You can achieve all that without using OOP but with OOP it will be easier.

But...

If your team is not proficient in OOP/OOD and have no expertise in that area, go with the resources you have.

-2

So, my question would be: how do you guys, know/decide when to use OOP in an application?

Always use it. Once you're used to using it, you'll use it for everything. It is a great way to ensure good abstraction between capabilities and their use, which is a significant benefit to maintenance. We use it, for example, for

  • small data structure objects because these are so are often polymorphic, for example and intermediate data structure after parsing something often has multiple small entities, which have common behavior and yet are also specialized. These are a great use case for a common base class or interface, with specialized implementations & behaviors, i.e. a class hierarchy (polymorphism).

  • logging, as an example, because it makes it easy to substitute a different logger

  • large pieces of program structure, because you conjure up multiple concurrent ones, and maybe take advantage of multi cpu processors. For example, a web server can trivially use multiple concurrent request handlers, due to objects.

It makes refactoring and reuse easier, as I mentioned, encourages good abstraction, all of which ease maintenance. OOP should be embraced and used all the time. Good OOP programming avoids static methods and/or static data, and uses objects for everything.

  • 6
    I didn't downvote (even though I was close to it), but I think this is the reason for the downvotes you got: "Always use this, because it's great" is seldomly a good advice. There are always exceptions. No tool comes without downsides, and OOP is no exception. Tell people that it is good, tell people what it is good for, tell people why it is good, tell people to avoid alternatives if they can, but never tell people not to think about alternatives. – cmaster Jul 26 '16 at 16:59
  • @cmaster, I'm ok if people downvote, it's their choice, and I've done it, too. On the subject matter, I still think this is the right answer for the person asking the question; IMHO, the OP needs to jump all the way in and use OOP, instead of trying to decide when to use OOP and occasionally choosing to make a class but otherwise writing procedural code. – Erik Eidt Jul 26 '16 at 17:11
  • 2
    @cmaster I can appreciate Erik's advice. As often as the "it depends" kind of answer may be the politically correct way to go, let's face it people, OO has pretty much become the baseline for programming environments that support it. So let's not kid ourselves, you can hardly go wrong with OO. The described script is, although linear, complex enough for objects to bring you some benefits. – Martin Maat Jul 26 '16 at 17:53
  • 2
    @ErikEidt "the OP needs to jump all the way in and use OOP" You could paraphrase that as "The OP needs to stop thinking about the best way to solve the customer's problem and just follow the One True Path To Enlightenment." Sadly, I've had to deal with a lot of so-called computing professionals who do follow that software design methodology. Obligatory Dilbert cartoon: dilbert.com/strip/1996-02-27 – alephzero Jul 26 '16 at 19:05
  • 1
    as easy as it is to wave this away as "yet another mindless OOP zealot", I think there's something to be said for actually going 100 % into something to really internalize and absorb it. not so you can use it every day for the rest of your life, but so you actually LEARN the strengths and weaknesses and not just read about them. I'd recommend just about anyone to spend a few months going hardcore OOP and a few months hardcore FP (á la haskell) and a few months procedural C and so on. just get in there and get down and dirty with it. – sara Jul 26 '16 at 19:19
-2

Object-Oriented Programming provides tools to create framework. These tools are Encapsulation , Abstraction , Inheritance and Polymorphism. These ideas will help you divide your program into two sections .

How to - This is the frame work part of your code , where you create some kind of abstraction , decide how your blocks work in general and how it interact with other blocks.

What to - This part is where the blocks do the actual work itself. Here the class are derived from the base classes create in the "How to section" .

One can greatly benefit from OOPS

  1. if you can reuse an existing framework and only have to do implement specific details in the "what to do" section.
  2. The functionality that is being implemented for the current project is a generic/commonly used one and other project/future projects can derive benefit from framework that is created while development of current project.
  3. Breaking down huge projects into commonly know patterns to solve a big problem.
  4. Use OOPS for even small project to get into habit of using it and be ready when 1 - 3 types of problem comes along
  • So you are basically saying you should always use OOP, regardless of the actual task you want to solve? – JacquesB Jul 27 '16 at 15:53
  • No :) , there are many program padigrams out there and some lend themselves to solving a particular problem better than others . OOPS is by no means the best solution for all ,But OOPS is pretty popular one . it will take time and practice to build good class and structures in OOPS , so if you want to use OOPS efficiently better start with smaller projects. Once you master it , its entirely upto you. I see OOPS concepts as a tool to build framework mostly. – Rahul Menon Jul 27 '16 at 16:09

Not the answer you're looking for? Browse other questions tagged or ask your own question.