is several small functions preferred rather than a few long ones in GUI
1 vue (au cours des 30 derniers jours)
Afficher commentaires plus anciens
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
0 commentaires
Réponse acceptée
TADA
le 8 Nov 2018
Modifié(e) : TADA
le 8 Nov 2018
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 commentaires
TADA
le 8 Nov 2018
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
Plus de réponses (0)
Voir également
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!