Beefy Boxes and Bandwidth Generously Provided by pair Networks
laziness, impatience, and hubris
 
PerlMonks  

Re^4: 'state' variables and unit testing (intentional)

by tye (Cardinal)
on Feb 02, 2014 at 02:27 UTC ( #1073018=note: print w/ replies, xml ) Need Help??


in reply to Re^3: 'state' variables and unit testing
in thread 'state' variables and unit testing

It is very often useful to prevent people from accidentally violating encapsulation. It is usually a mistake to try to prevent people from intentionally violating encapsulation.

Caching to a global variable is very often extremely handy when writing unit tests. Nobody accidentally modifies a global variables in another package. Nobody on my team even does that intentionally in Production code.

And I've seen lots of really stupid things done to try to work around such attempts to prevent intentional violations of encapsulation. They are usually much worse than the behavior that was trying to be prevented.

- tye        


Comment on Re^4: 'state' variables and unit testing (intentional)
Re^5: 'state' variables and unit testing (intentional)
by Jenda (Abbot) on Feb 02, 2014 at 12:10 UTC

    Unlike the solution using state the my in an enclosing block allows you to include controlled access to the cache.

    { my $_cache; sub withLongComputation { $_cache //= ...; ... } sub clearCache { undef $_cache; } }

    Jenda
    Enoch was right!
    Enjoy the last years of Rome.

      An an alternative:

      { use Scope::Guard; my $_cache; sub withLongComputation { $_cache //= ...; ...; } sub localClearCache { my $old = $_cache; undef $_cache; return guard { $_cache = $old }; } } ...; withLongComputation(); withLongComputation(); { my $guard = localClearCache(); # here, $_cache has been cleared withLongComputation(); } # Because $guard has fallen out of scope, # $_cache has been restored to its old value withLongComputation();
      use Moops; class Cow :rw { has name => (default => 'Ermintrude') }; say Cow->new->name

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others contemplating the Monastery: (7)
As of 2014-10-23 02:44 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    For retirement, I am banking on:










    Results (123 votes), past polls