views:

1016

answers:

17

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?

+1  A: 

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.

Jesse J
+21  A: 

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.

JasCav
+2  A: 

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.

omermuhammed
+3  A: 

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.

Mike Atlas
+5  A: 

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.

Aviral Dasgupta
I have often found myself wishing I had made a simple script more object oriented, because I later wanted to borrow some parts of it to handle a similar problem.
Michael Mathews
Good point, although you can do the same with a function.
Xiong Chiamiov
@Xiong : I really don't know, but for some reason I find myself more comfortable with exposed classes, than exposed functions. Maybe it's because with functions, you end up exposing *all* your module level variables...
Aviral Dasgupta
@Michael: You can always refactor as needed; that usually works out better than peering in the crystal ball to see how you'll reuse it.
Roger Pate
+1  A: 

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.

Rishav Rastogi
+4  A: 

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.

JacobM
+25  A: 

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.

Alex Martelli
Alex, I've been writing a simple Chip8 emulator, and I found myself wondering if using global was the right way to go. I'm using them for things like Memory, Stack, General Registers, Input Registers and the Timer. I actually think global was the right way to go here. OO would have complicated it, and given there is really only one level of scope at play, the side effects of having a global aren't going to be negative. What do you think?
Dominic Bou-Samra
@Dominic, I disagree -- what complication?! Having Memory, Stack, etc, as instance attributes, naturally afford very simple and compact ways to (e.g.) save and restore state in the middle of a simulation run (just `pickle`!), "take a snapshot" (`copy.deepcopy`) so you can later compare to see exactly what a certain sequence of instructions has done (or "undo" them by restoring the snapshot), and so forth -- huge lots of extra, useful functionality at just about no extra effort whatsoever!
Alex Martelli
Hmm I never thought about using copy and having an undo/save game feature. Looks like my case for using global just disappeared :D
Dominic Bou-Samra
A: 

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.

zifot
+1  A: 

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.

Sherwin James
A: 

"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?"

S.Lott
hmm; I didn't know "script" means "sequential" and "procedural" by definition (even if no useful distinction between procedural, script and OO can be made);it seems your answer talks about a philophical view(a Weltanschauung): objects are everywhere. Philosophically can be correct, but how does it applies to programming, where "objects" are something of someway defined, so that you can't call, say, a "processor register" _object_ the same way you call `a` in `string a` an _object_?There are levels and levels of abstraction that disappear if you say everything is an object.imo
ShinTakezou
@ShinTakezou: A processor register is an object. Not often formalized with a class definition, but it is an object: unique identity, state, etc. How is it not a first-class object? What properties do programming languages impose that the underlying register does not already have?
S.Lott
@ShinTakezou: Objects **are** the levels and levels of abstraction. Objects layer on objects, there are Composite objects, Facade objects, and many other design patterns that increase the abstraction. There are also low-level objects that aren't very abstract. And there are really bad objects that have poorly-designed purely procedural API's.
S.Lott
"script" means written (specifically, "inscribed"). Writing is sequential. Procedures are sequential. It's all one. Script, sequence, procedure.
S.Lott
No irony in"I didn't know 'script' means [...]";about objects...yes,so now I am objetizing with my object on the object (ops I mean:I am writing with my digits on the keyboard).I've said: in (OO)programming objects are defined,having "properties" other "stuffs"(to not confound 2different meanings)have not and so can't be called objects(in the OO way);if you choose the general meaning of "object",everything's a object(a cpu reg too),but you are moving to a level where there's no distinction between me and the computer,since we're both objects,and u'r misunderstanding (purposely?) the OP's Q
ShinTakezou
Sigh. You're right. The world is impossible to understand. All **software** is objects, even if the language does not formalize them. It's hard to make this clearer except by repeating (for the 4th time) that some languages formalize the objects, and some don't. The **software** objects exist whether or not the language formalizes it. All **software** is object-oriented. Some is shabby and hard to use (i.e., shell scripts). Some have object definitions are first-class parts of the language (i.e., Python) Some are hybrids (i.e., C++).
S.Lott
+1  A: 

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.

danatel
+1  A: 

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.

back2dos
A: 
Anthony
A: 

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.

Wayne Werner
+5  A: 

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.

Blessed Geek
My objectophrenia has unfortunately extended into my day-to-day, non-programming life :(
Justin L.
+1 for this funny and slightly scary essay on...objectophrenia ;-)
Greg S
+3  A: 

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.

Norman Ramsey