Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Refactoring in MATLAB

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.

like image 716
bdecaf Avatar asked Jul 23 '12 15:07

bdecaf


People also ask

What is refactoring a function?

Refactoring is the process of restructuring code, while not changing its original functionality. The goal of refactoring is to improve internal code by making many small changes without altering the code's external behavior.

What is a refactoring tool?

Code refactoring is a controller technique or process of restructuring your code without changing its external behavior for easier maintenance, better readability, understanding, and extended support. The main purpose of refactoring is to fight technical debt.

When should we do refactoring?

The best time to consider refactoring is before adding any updates or new features to existing code. Going back and cleaning up the current code before adding in new programming will not only improve the quality of the product itself, it will make it easier for future developers to build on the original code.


1 Answers

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.

like image 95
Chris Taylor Avatar answered Oct 02 '22 07:10

Chris Taylor