is several small functions preferred rather than a few long ones in GUI

3 次查看(过去 30 天)
I know this question has been asked before in different variations, but as a novice I need a bit help with best practice. I have a GUI (see code below) where I use a pushbutton to select a folder containing a lot of *.asc files. All these files are imported through a for loop as a text array inside one large cell array, for instance a 1x10 cell where each cell contain a subarray (30x13 cell). I hope this makes sense? from these cell I extract different variables and do various calculations. Now my question is: Will it be better practice to split large function (here pushbutton1) into minor functions such as one function for folder selection and one function for importing and another function for extracting parameters and yet another function for calculations etc...?
function pushbutton1_Callback(hObject, eventdata, handles)
%%Import every rawdata (*.asc) files from selected folder
Folder='C:\Users\test\GUI1.3\'; %start location for the folder selection
dirname = uigetdir(fullfile(Folder, ''), 'Select a directory');
if ~ischar(dirname);
return;
end %user canceled
dinfo = dir( fullfile( dirname, '*.asc') );
files=fullfile( {dirname},{dinfo.name});
numfiles = length(dinfo);
names = cell(1, numfiles);
Alldata = cell(1, numfiles);
for k = 1:numfiles
% Initialize variables.
filename = files{1,k};
delimiter = '\t';
% Format string for each line of text (column1-13: text (%s)):
formatSpec = '%s%s%s%s%s%s%s%s%s%s%s%s%s%[^\n\r]';
% Open the text file.
fileID = fopen(filename,'r');
% Read columns of data according to format string.
dataArray = textscan(fileID, formatSpec, 'Delimiter', delimiter, 'ReturnOnError', false);
% Close the text file.
fclose(fileID);
% Create output variable and insert in the "Alldata" cell array
Alldata{k}=[dataArray{1:end-1}];
names{k}=getfield(dinfo(k), 'name');
end

采纳的回答

TADA
TADA 2018-11-8
编辑:TADA 2018-11-8
Splitting large functions is always better practice. A function should have a specific logical role.
That being said, when you have a huge loop it is better to put the whole loop in a function rather than the contents of the loop because function invocation has an overhead.
Then again your mere 10×30 cells will amount to a few milliseconds that no user would notice.
  5 个评论
TADA
TADA 2018-11-8
If you have a lot of code and a lot of iterations, I would run a test and see how much the added functions affect your runtime

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Programming 的更多信息

标签

产品


版本

R2015b

Community Treasure Hunt

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

Start Hunting!

Translated by