필터 지우기
필터 지우기

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