Local functions vs. private functions

13 次查看(过去 30 天)
I am writing my first real piece of code which I hope to publish some day soon on Git and also it's qualification/methodology in a journal. However I wrote the code to employ functions which I have defined locally at the end of the script file. I am aware that you can also seperately write individual script files for each individual function and call these as long as they are within the same directory/folder. By including the numerous functions at the bottom of my main script file the code is rather long, and I am wondering, for the sake of other people's understanding of the code and for clarity, what the advantages/disadvantages to defining the functions either way are (locally at the end of a file, vs privatley)?

采纳的回答

Stephen23
Stephen23 2020-2-5
In my experience:
  1. files in a private folder are easier to maintain with version control. as each file encapsulates one functionality and can be tracked using standard version managment tools. In contrast putting everything into one file means the entire file gets a new version, even if you actually only change one local function.
  2. you can easily define a test script/function for the functions in a private directory (of course you should be collecting test cases for your functions, edge cases, failed test cases, etc.).
  3. local functions are useful when distributing code, it prevents functions from going missing and doesn't scare users who are not used to lots of folders and files hanging around.
  4. nested functions are very very useful... and can only be defined in the same file!
  1 个评论
Dan Hallatt
Dan Hallatt 2020-2-5
编辑:Dan Hallatt 2020-2-5
Thanks for the well thought out and wide range of considerations covered by each of the points in your response. It looks like there's some tradeoffs to either which I need to weigh and decide. Your first point in particular is something I thought of, which would certainly get annoying when someone tries to specify that they changed a small part of the code.
From my own opinion, I think your second point is extremly important, given how related a lot of my functions are within the main code. I've been testing my code and having to run through parts of it which gets redundant. Keeping the functions private would make this process much easier to test them.

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Startup and Shutdown 的更多信息

产品


版本

R2019b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by