Beefy Boxes and Bandwidth Generously Provided by pair Networks
go ahead... be a heretic
 
PerlMonks  

Re: Good practice for OO module defaults

by 1nickt (Abbot)
on Apr 08, 2019 at 15:30 UTC ( #1232299=note: print w/replies, xml ) Need Help??


in reply to Good practice for OO module defaults

Hi John Davies,

A few points in random order:

  • It's recommended to always make an Moo attribute lazy unless there's a good reason for it not to be.
  • If your attribute is lazy you can declare a builder sub for it.
  • The builder sub can be anywhere, including a module that is basically just a config file (but lives in lib/).
  • The value of the default property of an attribute can also be a coderef or sub.
  • Most applications grow to need a config system at some point; I place changeable config data in config files as it's easiest to maintain. If you are concerned about directory structures you can make you config directory relative to the library directory.

Hope this helps!


The way forward always starts with a minimal test.
  • Comment on Re: Good practice for OO module defaults

Replies are listed 'Best First'.
Re^2: Good practice for OO module defaults
by tobyink (Canon) on Apr 09, 2019 at 15:50 UTC

    "It's recommended to always make an Moo attribute lazy unless there's a good reason for it not to be."

    Recommended by whom? Plenty of attributes simply don't have any sensible default value. For many attributes, having them unset is itself meaningful. (For example, if you object has an output_file attribute, leaving it unset might indicate that you don't want it to produce any output.) And if the default is a simple value (like 0, 1, undef, or the empty string) then making it eager (i.e. not lazy) may have performance benefits.

      "... unless there's a good reason for them not to be."

      As for the recommendation, I can't find the original source but am sure I have read it in some doc somewhere. In my own experience it's usually the case that many if not most attributes depend on others or other things, and rather than try to remember all that I am lazy and use lazy and a builder. Of course that is not so in all cases, including e.g. your example of an attribute that has a static value.


      The way forward always starts with a minimal test.

        Sure, if an attribute's default value is going to be based on other attributes, then make it a lazy default. For most people, that's a minority of attributes though.

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others meditating upon the Monastery: (5)
As of 2020-08-12 10:10 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    Which rocket would you take to Mars?










    Results (65 votes). Check out past polls.

    Notices?