martedì, aprile 03, 2007

Programmare OOP in Matlab

In Matlab esistono degli strumenti del linguaggio appositamente realizzati per consentire la programmazione OOP, essi sono descritti nel capitolo "Classes and Objects" e sono lo standard utilizzato anche all'interno della toolbox standard di Matlab per l'UI e per molto altro.
Tale tecnica di programmazione presenta alcuni indubbi vantaggi ma anche degli svantaggi enormi, a partire dalla struttura e costruzione delle classi all'interno del file-system, l'impossibilità di utilizzo della dot-notation e molti altri.
Una tecnica alternativa per fare OOP in Matlab sfrutta lo storing del workspace locale condiviso nel caso in cui vengano utilizzate delle funzioni innestate. La seguente dichiarazione della classe "counter", completamente commentata, mostra come può essere facilmente utilizzata questa tecnica:

function c = counter(start)
% COUNTER Generates a new counter object created with internal functions.
%
% The technique used here allows to create objects with all private
% attributes and public methods exported in a structure. All local
% variables defined here can be used as object attributes. Sub-functions
% can be used as private methods and setter/getter methods can be written
% to give the acces to attributes.. using the complete information
% hiding paradigm. The main funciton is the constructor. The object status
% is stored in a local workspace that have the same lifetime of the
% generated object.

% Save the initial value:
startVal = start;

% ===========
% Now there are two object attributes: start and startVal.
% ===========

% Returning the counter: this is the public methods set exported.
c = struct('next',@Next,'prev',@Prev,'reset',@Reset);

% ===========
% The public methods body.
% ===========
% The next integer function:
function n = Next
% Set:
n = start;
% Increment:
start = start + 1;
end
% The prev integer function:
function n = Prev
% Set:
n = start;
% Decrement:
start = start - 1;
end
% The reset function:
function Reset
% Reset:
start = startVal;
end
% ===========
% Private methods are simple functions and can be defined here.
% ===========
end

% ===========
% Support functions that are not methods (no access to attributes) are
% defined here.
% ===========

Per creare un oggetto di classe "counter" è sufficiente eseguire la funzione:
c1 = counter(1);
c2 = counter(-2);
Per eseguire un metodo è sufficiente utilizzare la dot-notation:
c1.next()
ans = 1
c1.next()
ans = 2
c1.reset()
c1.next()
ans = 1
Have fun! ;)

1 commento:

nataluca ha detto...

Forte! Anche se Matlab non è nato come linguaggio OO, non c'è che ammirare lo sforzo che sta facendo la Mathworks per supportare la semantica OO senza incasinare/stravolgere troppo il linguaggio.
Al solito: se ci si porte il fardello della retro-compatibilità le cose vanno fatte gradualmente e senza rompere eccessivamente con il passato... Matlab è questo... evoluzione... senza fretta ;-)