How would I prevent access to classes that shouldn't be publicly available in my toolkit?

5 vues (au cours des 30 derniers jours)
I have a toolkit where I would like to provide some public functions and classes to the user (a public API). There are also many functions and classes that the user doesn't need access to. For the functions, I can create a folder named private and then put the public functions and classes one level above. This makes it where the public functions and classes can still call these private functions without exposing them to the user (i.e., the user can't call them from the command window or outside the folder). However, classes can't go inside private folders. How would I go about preventing access like I did with the private functions for my classes?

Réponses (2)

Matt J
Matt J le 6 Avr 2022
Modifié(e) : Matt J le 6 Avr 2022
You cannot truly hide the class, but you can have its constructor raise an error when someone tries to invoke it from outside your toolkit folder by doing something like below. Obviously also, you can make specific class methods private to the class using method attributes.
classdef myclass
function obj=myclass
if ~strcmp(pthCaller,pthPrivate)
error 'Class is private'

Steven Lord
Steven Lord le 7 Avr 2022
The way I'd probably do this is to make the class constructor for the "private" classes have Access='protected' (so only accessible in the class and its subclasses) and give the private classes a Static method that can call the protected constructor. Make that Static method only allow Access to a fixed set of classes or functions.
See the attached two classes.
% This works
y = class1690285_public(5); % invokes the Static method in class1690285_private
% which invokes the constructor of class1690285_private
ans = 25
% These don't work
z = class1690285_private(7);
catch ME
fprintf("The error was: %s\n", ME.message)
The error was: Cannot access method 'class1690285_private' in class 'class1690285_private'.
z = class1690285_private.makeOne(7);
catch ME
fprintf("The error was: %s\n", ME.message)
The error was: Cannot access method 'makeOne' in class 'class1690285_private'.


En savoir plus sur Argument Definitions dans Help Center et File Exchange




Community Treasure Hunt

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

Start Hunting!

Translated by