Beefy Boxes and Bandwidth Generously Provided by pair Networks
"be consistent"
 
PerlMonks  

Re: Is it ok to mix functional and oo programming in one package?

by bennymack (Pilgrim)
on Oct 19, 2007 at 16:28 UTC ( [id://646024]=note: print w/replies, xml ) Need Help??


in reply to Is it ok to mix functional and oo programming in one package?

I've recently adopted a coding style that results in code that can be executed both purely procedurally or in an object oriented fashion. I find that as long as I consistently stick to the style, my code is much more flexible for both internal and external use.

In a nutshell, I alwas add the line my( $self, %args ) = @_; *unless* it's an new *or* import. Then I substitute $self with $class.

The resulting subroutines end up looking like this:

sub do_something { my( $self, %args ) = @_; my( $scalar ) = $args{scalar} || eval { $self->{scalar} } || $self->SCALAR; my( @list ) = ( eval { @{ $args{list} } or 1 } ) ? @{ $args{list} : $self->LIST; }

Then calling code can choose to pass in parameters it wishes to override, or define a subclass that overrides the defaults (such as SCALAR and LIST.)

This approach has worked well for me so far. It supports both OO and procedural. It doesn't break inheritance, in fact it uses inheritance to reduce the number of arguments necessary if changing the defaults makes sense.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://646024]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others romping around the Monastery: (1)
As of 2024-04-25 03:30 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found