Local functions vs. private functions

조회 수: 4 (최근 30일)
Dan Hallatt
Dan Hallatt 2020년 2월 5일
편집: Dan Hallatt 2020년 2월 5일
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에서 Argument Definitions에 대해 자세히 알아보기

제품


릴리스

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by