3
$\begingroup$

In general, if one wants to define local variables and local constants, which of the following is the best programming practice in terms of performance and code "safety"? (Assume Block is not appropriate.)

  1. With inside Module

  2. Module inside With

  3. Define constants along with variables using just Module

Bonus Question

Is the answer the same if Block is appropriate in place of Module?

$\endgroup$
4
  • 3
    $\begingroup$ I'd say With outermost and Module as inner as possible, even if that means using nested Withs. (Reason: immutable beats mutable.) And avoid Block unless you know why you must use it. But I'll listen to whatever the CS guys have to say. $\endgroup$
    – Alan
    Commented May 25, 2021 at 19:37
  • $\begingroup$ @Alan When you say “Immutable beats mutable”, you mean performance-wise. Correct? $\endgroup$ Commented May 26, 2021 at 0:56
  • 2
    $\begingroup$ Related, also you can 'chain' locals with With, e.g. With[{a = 2}, {b=a^2}, {c=b^2}, c] $\endgroup$
    – I.M.
    Commented May 26, 2021 at 6:29
  • 1
    $\begingroup$ @JustSomeOldMan I think 'immutable beats mutable' is from the point of view of debuggability and reasoning about your program, guaranteeing that immutable variables won't change, confining bug prone mutability to fewer lines of code. The performance differences are small. $\endgroup$
    – flinty
    Commented May 26, 2021 at 13:06

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.