How to make function available for several classes

5 ビュー (過去 30 日間)
Ilya
Ilya 2015 年 12 月 23 日
編集済み: Ilya 2015 年 12 月 24 日
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 Center および File ExchangeData Type Identification についてさらに検索

タグ

製品

Community Treasure Hunt

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

Start Hunting!

Translated by