首页 > 解决方案 > OOP中的Matlab私有/嵌套函数

问题描述

我有一个函数,它有几个子函数,一切都是句柄类的一部分。这可以通过以下来说明(私有函数没有循环依赖,有些东西依赖于对象):

function out = f1(obj, in)
   out = f2(obj, f3(in * obj.Thickness));
end

function out = f2(obj, in)
   out = f3(in / obj.NumLayers);
end

function out = f3(in)
   out = in;
end

与文件夹f1.m内的@MyClass文件。

我决定将所有这些文件放在类中,并@MyClass在制作最终包的过程中删除该文件夹(我现在就是那个时候)。

此时,类结构为

classdef MyClass < handle
properties
   prop1
end
methods
   function obj = MyClass(varargin) ...
   function out = f1(obj, in)
end
methods (Access = private)
   function out = f2(obj, in)
end
methods (Access = private, Static)
   functions out = f3(obj, in)
end
end

一切都在MyClass.m, f2 和 f3 是私有的,但显然可以看到类内的其他函数。我发现这有点问题,因为某些函数的名称略有相似(因为它们做的事情相似,尽管不是相同的东西)并且可能会误导维护代码的任何人——包括我以后。

嵌套函数是我简要考虑过的另一个选项,但是对于我的用例,我真的不喜欢“共享参数”位(这是那些嵌套函数的重点),因为对我来说这听起来很容易引入错误。

我在这里错过了任何更好的解决方案,还是应该坚持当前的私有功能?

标签: matlaboop

解决方案


一种解决方案如下:

classdef name

   properties
      ...
   end

   methods

      function out = f1(obj, in)
         out = f2(obj, f3(in * obj.Thickness));
      end

   end
end

function out = f2(obj, in)
   out = f3(in / obj.NumLayers);
end

function out = f3(in)
   out = in;
end

这使它们成为类私有的,但不是成员方法。我不确定这些私有函数是否可以访问该类的私有成员。

另一种方法是创建私有成员函数

classdef name

   properties
      ...
   end

   methods

      function out = f1(obj, in)
         out = f2(obj, f3(in * obj.Thickness));
      end

   end

   methods (Access=private, Hidden=true)

      function out = f2(obj, in)
         out = f3(in / obj.NumLayers);
      end

      function out = f3(in)
         out = in;
      end

   end
end

推荐阅读