How to make function available for several classes

4 次查看(过去 30 天)
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..)?

采纳的回答

Image Analyst
Image Analyst 2015-12-23
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 个评论
Ilya
Ilya 2015-12-24
编辑:Ilya 2015-12-24
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.

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Data Type Identification 的更多信息

标签

产品

Community Treasure Hunt

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

Start Hunting!

Translated by