How to make function available for several classes
6 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Ilya
el 23 de Dic. de 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 comentarios
Respuesta aceptada
Image Analyst
el 23 de Dic. de 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 comentario
Más respuestas (0)
Ver también
Categorías
Más información sobre Software Development Tools en Help Center y File Exchange.
Productos
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!