What are the benefits of switching from Rule and /. to OptionsPattern[] and OptionValue in a large application?

Viewed 1373

Old habits die hard, and I realise that I have been using opts___Rule pattern-matching and constructs like thisoption /. {opts} /. Options[myfunction] in the very large package that I'm currently developing. Sal Manango's "Mathematica Cookbook" reminds me that the post-version-6 way of doing this is opts:OptionsPattern[] and OptionValue[thisoption]. The package requires version 8 anyway, but I had just never changed the way I wrote this kind of code over the years.

Is it worth refactoring all that from my pre-version-6 way of doing things? Are there performance or other benefits?

Regards

Verbeia

EDIT: Summary

A lot of good points were made in response to this question, so thank you (and plus one, of course) all. To summarise, yes, I should refactor to use OptionsPattern and OptionValue. (NB: OptionsPattern not OptionPattern as I had it before!) There are a number of reasons why:

  1. It's a touch faster (@Sasha)
  2. It better handles functions where the arguments must be in HoldForm (@Leonid)
  3. OptionsPattern automatically checks that you are passing a valid option to that function (FilterRules would still be needed if you are passing to a different function (@Leonid)
  4. It handles RuleDelayed (:>) much better (@rcollyer)
  5. It handles nested lists of rules without using Flatten (@Andrew)
  6. It is a bit easier to assign multiple local variables using OptionValue /@ list instead of having multiple calls to someoptions /. {opts} /. Options[thisfunction] (came up in comments between @rcollyer and me)

EDIT: 25 July I initially thought that the one time using the /. syntax might still make sense is if you are deliberately extracting a default option from another function, not the one actually being called. It turns out that this is handled by using the form of OptionsPattern[] with a list of heads inside it, for example: OptionsPattern[{myLineGraph, DateListPlot, myDateTicks, GraphNotesGrid}] (see the "More information" section in the documentation). I only worked this out recently.

4 Answers
Related