MATLAB Answers

How to make function available for several classes

18 views (last 30 days)
Ilya
Ilya on 23 Dec 2015
Edited: Ilya on 24 Dec 2015
My problem is that I'm using one-liner functions like
isint = @(x) all(imag(x)==0 & mod(x, 1)==0);
to check the type of function inputs (this is similar to some answer of Bruno Luong somewhere on matlabcentral). Initially there was only one 'start' function to check this.
Now I'd like to use them in set methods of multiple classes, in which I'd like to check the validity of an input before assigning it to a property. But then it seems that it's needed to define these "checker functions" in each class or to abandon their use alltogether and write the underlying expressions directly into setters. Is there any elegant way to avoid these two unpleasant alternatives? May be somehow make the "checker functions" available to several classes (writing a separate function file for each checker is unpleasant as well..)?

  0 Comments

Sign in to comment.

Accepted Answer

Image Analyst
Image Analyst on 23 Dec 2015
You can define a static class that all your other classes then call to validate inputs to them. For example I have a static class for Excel ActiveX utilities. It starts out like this:
classdef Excel_utils
methods(Static)
% --------------------------------------------------------------------
% GetNumberOfExcelSheets: returns the number of worksheets in the active workbook.
% Sample call
% numberOfSheets = Excel_utils.GetNumberOfExcelSheets(Excel);
function numberOfSheets = GetNumberOfExcelSheets(excelObject)
try
worksheets = excelObject.sheets;
numberOfSheets = worksheets.Count;
catch ME
errorMessage = sprintf('Error in function %s() at line %d.\n\nError Message:\n%s', ...
ME.stack(1).name, ME.stack(1).line, ME.message);
fprintf(1, '%s\n', errorMessage);
WarnUser(errorMessage);
end
return; % from GetNumberOfExcelSheets()
end % of GetNumberOfExcelSheets()
and then after that it has a bunch more functions in it. Then whenever I want to call that method, I just do
numberOfSheets = Excel_utils.GetNumberOfExcelSheets(Excel);
I don't need to instantiate an object in advance to use the method since it's static. You could have a static class called ValidateInputs() and then have all the various methods listed inside that. Would that work for you?

  1 Comment

Ilya
Ilya on 24 Dec 2015
Yes, that's what I want! Then I'll just create a class Utils with static-only methods, in which I'll place all these small functions, also other functions that can't be assigned to any particular group like ValidateInput.

Sign in to comment.

More Answers (0)

Categories

Tags

Products

Community Treasure Hunt

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

Start Hunting!