[sf-perl] Advice on how to expose a class-wide preference

Shlomi Fish shlomif at iglu.org.il
Tue Mar 18 01:50:12 PDT 2008


Hi Anirvan!

On Tuesday 18 March 2008, Anirvan Chatterjee wrote:
> I'm looking for advice on how to expose a user-settable preference
> that affects the behavior of all objects in a given class. I'm working
> on a module representing data stringifiable in multiple ways, e.g.:
>
> 	$data->normalized
> 	$data->full
> 	$data->compact
>
> I'd like to set up string operator overloading, but it's not obvious
> what the default stringification style should be; different users will
> have different needs. I'd like to allow users to choose how objects
> will stringify by default in their code. I can imagine doing this in
> two different ways:
>
> 1) Have a class-wide preference indicating the default style:
>
> 	Class->default_string_style('normalized');
>
> 2) Let users set their preference via a magic variable:
>
> 	local $Class::default_string_style = 'normalized';
>
> The first option seems cleaner, and easier to subclass (were that an
> issue); it also allows for better error handling when the user calls
> the class method. Unfortunately, setting a class-wide flag also blows
> away any prior settings. Two pieces of code using the module will
> necessarily overwrite each other's preferences.
>
> Using a variable seems uglier, but allows users to safely intermix
> different preference values in different contexts.
>
> Any suggestions on which of these is generally better to use? Are
> there other strategies I'm ignoring? Thanks for any advice.

Another option I can think of is to make use of closures to define a certain 
scope:

<<<<<<<<<<<<<<<<<<<

$data->as_normalized(sub {
	# Here $data will stringify as normalized:
	print "$date";
});
# And here $data will revert back to its previous setting.

>>>>>>>>>>>>>>>>>>>

And naturally inside the closure you can safely set the setting to any other 
value, because it will be reverted at the end.

Regards,

	Shlomi Fish

---------------------------------------------------------------------
Shlomi Fish      shlomif at iglu.org.il
Homepage:        http://www.shlomifish.org/

I'm not an actor - I just play one on T.V.


More information about the SanFrancisco-pm mailing list