"OOP" 和 "functional" 方法调用语法之间的差异

Difference between "OOP" and "functional" method invocation syntax

关于this page的解释 inputParser class,

我们看到示例中的每个 inputParser 方法调用都是

形式
methodname(object, arguments)

而不是

object.methodname(arguments)

例如

addRequired(p,'filename',@ischar)

而不是

p.addRequired('filename',@ischar)

其中 p 是一个实例 if inputParser.

我会说这使得不清楚 addRequired 的来源,而不必通过 which 或调用代码中的实例化行来搜索它。 addRequired 在任何上下文中都可用会破坏封装,这似乎与您首先引入 OOP 所希望的完全相反。

我怀疑以这种特殊方式牺牲可读性和编写文档是有充分理由的。

所以我的问题是,MATLAB 中的 "functional" 和 "OOP" 语法之间是否有任何实用 区别?

恐怕这些语法甚至不完全等价,从下面的例子可以看出:

>> f = fit( (1:3).', (2:2:6).' ,'poly1')
f = 
     Linear model Poly1:
     f(x) = p1*x + p2
     Coefficients (with 95% confidence bounds):
       p1 =           2  (2, 2)
       p2 =  -6.784e-16  (-4.709e-14, 4.574e-14)
>> methods(f)
Methods for class cfit:

argnames       cfit           coeffvalues    dependnames    feval          formula        integrate      numargs        plot           probnames      setoptions     
category       coeffnames     confint        differentiate  fitoptions     indepnames     islinear       numcoeffs      predint        probvalues     type           

>> f.coeffvalues
Error using cfit/subsref (line 18)
The name 'coeffvalues' is not a coefficient or a problem parameter.  You can only use dot notation to access the coefficients and problem parameters of a cfit or sfit, e.g.,
'f.p1'.

For the current fit, you can access these properties: p1, p2

You can get coefficient names and values either by name, e.g., p1 = f.p1, or by using the coeffnames or coeffvalues functions, e.g., names = coeffnames(f).

To use methods, use functional notation instead, e.g., plot(f). 

>> coeffvalues(f)
ans =
    2.0000   -0.0000

最重要的是:

To use methods, use functional notation instead, e.g., plot(f).

现在假设我们是虐待狂并且想自己编写一个行为类似的函数,进一步调查我们发现 cfit.coeffvalues 只是一个 getter 用于私有 属性。现在,如果您仔细查看上面的错误,您会注意到 它甚至没有出现在 cfit.coeffvalues 中,而是出现在 cfit.subsref![=17 中=]

总之,

由此我们可以了解到,根据经验,函数符号直接进入相关方法,而 OOP 符号首先经过可能被重写的 subsref class 的方法。我想如果您想确保跳过任何自定义 subsref,请使用函数符号。