Refactoring in MATLAB
Asked Answered
R

1

5

I got the fruitless task to incorporate some programs my predecessor wrote. One horrible mess of unorganized code.

So far I know only about the automatic identation (C-i). So I wonder if you can suggest some tool.

some key problems I'm having:

  • Assignment to the same structure is sparkled through the whole file
  • This is one big file of code - I would like to split it
  • Quite a lot of code produces results that are never used

Update On the nice looking part I found that the Matlab mode of Emacs can break overlong lines quite reasonable.

Riess answered 23/7, 2012 at 15:33 Comment(1)
You don't sound like you need a refactoring tool. You sound you you need an analysis tool ("is this code dead?"); with that, you could do much of the work yourself. (Granted an analysis tool integrated into a refactoring tool would be even nicer). Matlab doesn't have a huge audience (compared to Java or C#); my guess is you're unlikely to find such tools unless the Mathworks is supplying it.Oyler
I
8

Incremental refactoring is the way forward.

  • Pick an m-file that seems reasonably self contained and work out what it's supposed to do.
  • Create a test for the m-file. This can be as simple as loading in some data from a file, calling the function with that data as an argument, and checking that the result matches the original output (obviously, before you make any changes, the test should pass!)
  • Start making changes to the file. Every so often, run the test to make sure that it still passes. If it doesn't pass, then you've broken something - undo your last set of changes (you are using version control, right?) and try again.
  • Repeat until complete, always starting from the least dependent functions to the most dependent.

Unfortunately there is no magic bullet. You can rely on the Matlab linter, which will tell you when a variable is never assigned to or used, or when a function is never called, but beyond that you need to tidy the code up a piece at a time, testing it as you go.

Intercommunicate answered 23/7, 2012 at 15:40 Comment(3)
watch out when the author uses stuff like global variables, or a bunch of scripts instead of functionsPutup
Another advice: use unit tests and some kind of version management: Subversion or GIT for example.Kim
Well some of it I already knew. Just had hoped a tool would help me in the task.Riess

© 2022 - 2024 — McMap. All rights reserved.