What are some tips to write a more readable code?

For example in C, tab is your friend. You can also declare variables in a way such that you can read the code easily later on.

In Mathematica, if you are writing a complicated code, things can get messy very quick and becomes very hard to read later on. What are some tips for code readability without trading away the performance?


Several rules of thumb:

  • Always use lower-case letters to start the name of a variable or defined function: myList and myFunction (not MyList or MyFunction) so as to never conflict with Matheamtica's internal names.
  • Group similar program elements on a single line for readability:

Plot3D[Sin[x y], {x, 0, 1}, {y, 0,1}]

instead of

Plot3D[Sin[x y], {x, 0, 1}, {y, 0,1}]

  • Likewise, align lists, options, and such so that any errors can be easily seen
  • Use blank lines to separate large groups of code of similar functionality.
  • Use the usage option for important functions, as in f::usage = "explanation of function f"
  • Comment as necessary (* my comment *)
  • There are innumerable other suggestions that are specific to Mathematica language (such as Table instead of Do) that are best discovered by extensive programming.
  • Use cell style such as Chapter to separate code in easily recognizable fashion.
  • Use the pulldown menu Format... TextColor or Format... BackgroundColor to color variables or functions for ease of finding and reading.
|improve this answer|||||
  • $\begingroup$ Thank you, this is about what I am asking. $\endgroup$ – gurluk Nov 14 '15 at 0:59

In any programming language the readability of code is greatly improved when the programmer takes the time and puts in the effort to use meaningful identifiers. Mathematica is no exception in this regard.

I quote a piece of own code as an example. It moves a file into the OS X trash.

moveToTrash[fullPathName_String] :=
  Module[{trash, fileName},
    trash = FileNameJoin[{HomeDirectory[], ".Trash"}];
    fileName = FileNameTake[fullPathName];
    While[FileExistsQ[FileNameJoin[{trash, fileName}]],fileName = "#" <> fileName];
    RenameFile[fullPathName, FileNameJoin[{trash, fileName}]]]

I think this code is as readable as any code written with care given to choosing identifier names in any other language.

|improve this answer|||||

In a language like C, you'll write sequential procedures like:

a=some stuff;

b=more stuff;

result=munge a and b together;

return result;

In Mathematica, it's much handier to write one-line functions and compose them rather than one-line steps and concatenate them:

a[stuff_]:=a formula

b[stuff_]:=another formula

munge[stuff_]:=a[stuff] together with b[stuff]

By making a, b, and munge functions, you localize their behavior and make them easier to understand and test in isolation.

|improve this answer|||||

Not the answer you're looking for? Browse other questions tagged or ask your own question.