Does OOP make sense for small scripts?

Question:

I mostly write small scripts in python, about 50 – 250 lines of code. I usually don’t use any objects, just straightforward procedural programming.

I know OOP basics and I have used object in other programming languages before, but for small scripts I don’t see how objects would improve them. But maybe that is just my limited experience with OOP.

Am I missing something by not trying harder to use objects, or does OOP just not make a lot of sense for small scripts?

Asked By: Mad Scientist

||

Answers:

In your case I’d say that OOP would be helpful only if it makes the scripts more readable and understandable. If not, you probably don’t need to bother.

Answered By: Jesse Jashinsky

Object-Oriented Programming, while useful for representing systems as real-world objects (and hopefully making large software system easier to understand) is not the silver bullet to every solution (despite what some people teach).

If your system does not benefit from what OOP provides (things such as data abstraction, encapsulation, modularity, polymorphism, and inheritance), then it would not make sense to incur all the overhead of doing OOP. However, if you find that as your system grows these things become a bigger concern to you, then you may want to consider moving to an OOP solution.

Edit: As an update, you may want to head over to Wikipedia to read the articles on various criticisms of OOP. Remember that OOP is a tool, and just like you wouldn’t use a hammer for everything, OOP should not be used for everything. Consider the best tool for the job.

Answered By: JasCav

OOP is a tool to manage complexity in code, 50-250 lines of code are rarely complicated. Most scripts I have written are primarily procedural. So yes, for small scripts just go with procedural programming.

Note that for significantly complicated scripts OOP may be more relevant, but there is still not hard and fast rule that says use OOP for them. It is a matter of personal preference then.

Answered By: omermuhammed

Use the right tool for the right job. For small scripts that don’t require complex data structures and algorithms, there is likely no use for object oriented concepts.

Answered By: Mike Atlas

If you plan to use the script independently, then no. However if you plan to import it and reuse some of it, then yes. In the second case, it’s best to write some classes providing the functionality that’s required and then have a conditional run (if __name__=='__main__':) with code to execute the “script” version of the script.

Answered By: aviraldg

OOP is just another paradigm. A lot of problems can be solved using both procedural or OOP.

I use OOP when I see clear need of inheritance in the code i am writing, its easier to manage common behaviour and common attributes.

It sometimes makes it easy to understand, and manage. Even if the code is small.

Answered By: Rishav Rastogi

My experience is that any purely procedural script longer than a few dozen lines becomes difficult to maintain. For one thing, if I’m setting or modifying a variable in one place and using it in another place, and those two places can’t fit on a single screen, trouble will follow.

The answer, of course, is to tighten the scope and make the different parts of your application more encapsulated. OOP is one way to do that, and can be a useful way to model your environment. I like OOP, as I find I can mentally jump from thinking about how the inside of a particular object will work, to thinking about how the objects will work together, and I stay saner.

However, OOP is certainly not the only way to make your code better encapsulated; another approach would be a set of small, well-named functions with carefully defined inputs and outputs, and a master script that calls those functions as appropriate.

Answered By: Jacob Mattison

I use whatever paradigm best suits the issue at hand — be it procedural, OOP, functional, … program size is not a criterion, though (by a little margin) a larger program may be more likely to take advantage of OOP’s strengths — multiple instances of a class, subclassing and overriding, special method overloads, OOP design patterns, etc. Any of these opportunities can perfectly well occur in a small script, there’s just a somewhat higher probability that it will occur in a larger one.

In addition, I detest the global statement, so if the natural procedural approach would require it, I will almost invariably switch to OOP instead — even if the only advantage is the ability to use a qualified name instead of the barename which would require global.

There’s definitely no need to “try harder” in general — just ask yourself “is there an opportunity here to use (a) multiple instances (etc etc)” and it will soon become second nature, i.e., you’ll spot the opportunities without needing to consciously remind yourself every time to look for them, and your programming will improve as a result.

Answered By: Alex Martelli

First of all – what do you mean by objects? In Python functions are objects and you’re most likely using them. 🙂

If by objects you mean classes and instances thereof, then I would say something obvious: no, there is no reason to saying that using them is making your code better by itself. In small scripts there is not going to be any leverage coming from sophisticated OO design.

Answered By: zifot

Another benefit of OOP is to communicate intent (whether to other developers, managers, or yourself some point in the future). If the script is small enough where it can be fully communicated in a couple of sentences then OOP is probably not necessary, in my opinion.

Answered By: Sherwin James

“Script” means “sequential” and “procedural”. It’s a definition.

All of the objects your script deals with are — well — objects. All programming involves objects. The objects already exist in the context in which you’re writing your script.

Some languages allow you to clearly identify the objects. Some languages don’t clearly identify the objects. The objects are always there. It’s a question of whether the language makes it clear or obscure.

Since the objects are always there, I find it helps to use a language that allows clear identification of the objects, their attributes, methods and relationships. Even for short “scripts”, I find that explicit objects and an OO language helps.

The point is this.

There’s no useful distinction between “procedural”, “script” and “OO”.

It’s merely a shift in emphasis. The objects are always there. The world is inherently object-oriented. The real question is “Do you use a language that makes the objects explicit?”

Answered By: S.Lott

Using OOP for few hundred lines of code rarely makes sense. But if your script is useful, it will probably grow rather quickly because new features will be added. If this is the case, it is better to start coding OOP way it will pay in the long run.

Answered By: danatel

OOP is about what you get if you add polymorphism on top of modular programming.
The latter of both promotes low coupling, encapsulation, separation of responsibility and some other concepts, that usually produce code, that is short, expressive, maintainable, flexible, extensible, reusable and robust.

This is not so much a question about size, but about length of the software’s life cycle. If you write any code, as short as it may be, as long as it is complex enough that you don’t want to rewrite it, when your requirements change, it is important that it meets the aforementioned criteria.

OOP makes modular programming easier in that it has established solutions for implementing the concepts promoted by modular programming, and that polymorphism allows really low coupling through dependency injection.

I personally find it simpler to use OOP to achieve modularity (and reusability in particular), but I guess, that is a matter of habit.

To put it in one sentence. OOP will not help you in solving a given problem better, than procedural programming, but instead yields a solution, that is easier to apply to other problems.

Answered By: back2dos

as someone who does a lot of scripts, if you get the idea that your code may at some point go beyond 250 line start to go oop. I use a lot of vba and vbscript and I would agree that anything under 100 lines is usually pretty straightforward and taking the time to plan a good oop design is just a waste.

That being said I have one script that came to about 500 line + and looking back on it, because i didn’t do it oop it quickly turned into an unholy mess of spaghetti. so now anything over 200 lines I make sure i have a good oop plan ahead of time

Answered By: Anthony

It really depends on what the script is an what it’s doing and how you think about the world.

Personally after a script has made it past 20-30 lines of code I can usually find a way that OOP makes more sense to me (especially in Python).

For instance, say I’m writing a script that parses a log file. Well, conceptually I can imagine this “log parser” machine… I can throw all these sheets of paper into it and it will sort them, chop parts out of some pages and paste them onto another and eventually hand me a nice report.

So then I start thinking, well, what does this parser do? Well, first off he’s (yes, the parser is a he. I don’t know how many of my programs are women, but this one is definitely a guy) going to read the pages, so I’ll need a method called page reader. Then he’s going to find all of the data referring to the new Frobnitz process we’re using. Then he’s going to move all the references about the Frobnitz process to appear next to the Easter Bunny graph. Ooh, so now I need a findeasterbunny method. After he’s done that, then he’s going to take the rest of the logs, remove every 3rd word, and reverse the order of the text. So I’ll need a thirdwordremover and a textreversal method, too. So an empty shell class would look like so:

class LogParser(Object):
    def __init__(self):
         #do self stuff here
    def pageReader(self):
         #do the reading stuff here, probably call some of the other functions
    def findFrobnitz(self):
         pass
    def findEasterBunny(self):
         pass
    def thirdWordRemover(self):
         pass
    def textReversal(self):
         pass

That’s a really contrived example, and honestly probably not a situation I’d use OOP for… but it really just depends on what’s easiest for me to comprehend at that particular moment in time.

Answered By: Wayne Werner

One of the unfortunate habits developed with oop is Objectophrenia – the delusion of seeing objects in every piece of code we write.

The reason why that happens is due our delusion of believing in the existence of a unified objects theorem.

Every piece of code you write, you begin to see it as a template for objects and how they fit into our personal scheme of things. Even though it might be a small task at hand, we get tempted by the question – is this something I could place into my class repository which I could also use for the future? Do I see a pattern here with code I have previously written and with code which my object clairvoyance tells me that I will one day write? Can I structure my present task into one of these patterns.

It is an annoying habit. Frequently, it is better not to have it. But when you find that every bit of code you write somehow falls into patterns and you refactor/realign those patterns until it covers most of your needs, you tend to get a feeling of satisfaction and accomplishment.

Problems begins to appear when a programmer gets delusional (compulsive obsessive object oriented disorder) and does not realise that there are exceptions to patterns and trying to over-manipulate patterns to cover more cases is wrong. It’s like my childhood obsession with trying to cover a piece of bread completely with butter or jam spread every morning I had breakfast. That sometimes, it is just better to leave the object oriented perception behind and just perform the task at hand quick and dirty.

The accepted industrial adage of 80-20 might be a good measure. Using this adage in a different manner than it is normally perceived, we could say 80% of the time have an object oriented perception. 20% of the time – code it quick and dirty.

Be immersed by objects but eventually you have to resist its consuming you.

You probably have not done enough programming yet because if you have, you would see all the patterns that you had done and you will also begin to believe in patterns that you have yet to apply. When you begin to see such objectophrenia visions, it’s time to be careful not to be consumed by them.

Answered By: Blessed Geek

Am I missing something by not trying harder to use objects, or does OOP just not make a lot of sense for small scripts?

Objects buy you encapsulation and reuse (through inheritance). Neither is likely to be terribly useful when writing small scripts. When you have written a collection of similar scripts or you find yourself repeatedly changing your scripts, then maybe you should consider where objects might help.

Answered By: Norman Ramsey
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.