Question

I have procedural Perl code (ca 500 lines long) which I would like to rewrite to object oriented equivalent (in procedural way it slowly becomes a mess). I can post code here (with few simple comments) if anyone is interested.

What are the best practices for rewriting procedural to OOP equivalent?

Was it helpful?

Solution

In your procedural Perl code I imagine your functions rely on a lot of global state: accessing global variables or receiving dozens of arguments at a time. OOP lets you encapsulate state within objects, and methods (functions defined on the object) have access to all the state contained in the object.

If you have a lot of functions operating on the same global variables, make a class that contains those variables, and move those functions into that class. Your data will then be protected from the global scope, and you'll no longer need to declare that you're using global variables, nor will you need to have functions signatures with tons of parameters.

OOP is really just a cleaner way to pass around program state and thus results in nicer code that's easier to reason about (than procedural code with tons of global side effects). Methods don't require you to define a giant list of parameters because the instance of the object (which includes all its state) it's working on is passed as an argument to the method under the hood.

class Person { ... }
p = Person(...)
print p.to_string()

In the above, p is really an argument to to_string(), it's just that in typical OOP syntax it's being passed in on the left side of the function call.

Something similar would be like this in C:

struct Person { ... };
char* to_string(struct Person);
struct Person p = { ... };
printf(to_string(p));

OTHER TIPS

OOP is mainly concerned with keeping local state (instead of global) and with modularizing functionality by grouping related behavior into objects. Given the broad generality of the question, I would advise to think about your objects (what is the main data / what are the main domain objects) first and to break your procedural functions down into methods of those objects.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top