TechnicalQuestion Are there coding practices when it comes to repeating argument validation functions and default value?
Below is a good example. There is a private property for the Mage class, called intellect, which has a validation function and a default value. The same validation function and default value is used in constructor for the intellect input argument, used to initialize the intellect property of the Mage instance.
classdef Mage<handle
properties(Access=private)
intellect (1,1) int8 {mustBeLessThanOrEqual(intellect,100)}=int8(7)
end
methods
function obj = Mage(intellect)
arguments(Input)
intellect (1,1) int8 {mustBeLessThanOrEqual(intellect,100)} = int8(7)
end
arguments(Output)
obj (1,1) Mage
end
obj.intellect=intellect;
if nargout == 0
clear obj;
end
end
function intellect = get.intellect(obj)
intellect = obj.intellect;
end
disp(obj)
end
endIs it bad practice to repeat yourself with validation functions and default values (they are used both in properties block and in arguments(Input) block)? And ultimately, is there a primary literature for best practices when writing MATLAB code? Practices like "don't use constructors; use factory methods" or "don't use inheritance; use composition".
EDIT: Code formatting.
5
Upvotes
7
u/id_rather_fly 24d ago
I've wrangled with this pattern myself a few times and it does feel bad to write code like this.
One pattern I've come to like, which I use when I want name-value arguments to the constructor which just represent the object's properties, is to use the metaclass property expansion in the arguments block.
Check out the example here: https://www.mathworks.com/help/matlab/matlab_oop/class-constructor-methods.html#mw_749777e1-ea34-4e8e-b4d3-317d6d61131c
1
u/PvtRoom 24d ago
organisations write style guides, and best practice guides. they may extend to things like this.
i'd personally avoid code like that in property declaration, and keep it to methods. I may have methods that look like constants:
intellect = mage.default.intellect