Beefy Boxes and Bandwidth Generously Provided by pair Networks
Think about Loose Coupling
 
PerlMonks  

comment on

( [id://3333]=superdoc: print w/replies, xml ) Need Help??

Keep in mind that for non-trivial code an optional dependency can cause spaghetti-like code with conditionals peppered throughout the code base:

if(exists $INC{'Example/Module.pm'}) {...}

...or...

if (__PACKAGE__->can('example')) {...}

...or any of a number of other strategies for detecting if the optional module got loaded. This is a situation where it's usually better to encapsulate the optional dependency so that the calling code doesn't have to care whether it was available or not:

package SomeThing; use Exporter; BEGIN { if (eval "require MyOptional; 1;") { MyOptional->import('foo'); } else { *foo = sub { # fallback code here. }; } } use parent 'Exporter'; our @EXPORT = qw(foo); 1; package main; use SomeThing; foo();

Now everywhere you wanted foo() you can just call it and not worry about whether or not it got loaded at startup by an external dependency, or by a fallback sub that you created yourself. This is just one of many ways to do it. An encapsulating OO class might work better, or dependency injection into a consuming object could be better; it depends a lot on your use case. But the goal is to reduce the pervasiveness of conditional logic in your code to only the one place.


Dave


In reply to Re: Using perl module if env is enabled by davido
in thread Using perl module if env is enabled by ovedpo15

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post; it's "PerlMonks-approved HTML":



  • Are you posting in the right place? Check out Where do I post X? to know for sure.
  • Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
    <code> <a> <b> <big> <blockquote> <br /> <dd> <dl> <dt> <em> <font> <h1> <h2> <h3> <h4> <h5> <h6> <hr /> <i> <li> <nbsp> <ol> <p> <small> <strike> <strong> <sub> <sup> <table> <td> <th> <tr> <tt> <u> <ul>
  • Snippets of code should be wrapped in <code> tags not <pre> tags. In fact, <pre> tags should generally be avoided. If they must be used, extreme care should be taken to ensure that their contents do not have long lines (<70 chars), in order to prevent horizontal scrolling (and possible janitor intervention).
  • Want more info? How to link or How to display code and escape characters are good places to start.
Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others contemplating the Monastery: (6)
As of 2024-03-28 11:26 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found