缩写长对象链(java)

时间:2018-01-16 14:19:28

标签: java oop abbreviation comsol

首先,我想分享一下我最近开始使用java和面向对象编程,如果这是一个愚蠢的问题,请原谅我,但我无法在其他地方找到明确的答案。

我正在研究Comsol模型的模板,并希望缩写代码的一部分以使其更具可读性。虽然以下代码段与Comsol编译器一起运行:

Model model = ModelUtil.create("Model");    // Returns a model
model.geom().create("geom1");               // add a component
model.geom("geom1").create("circle")        // add a shape

//I would like to rewrite the following block of code:
model.geom("geom1").shape("circle").name("c1", "Circle");
model.geom("geom1").shape("circle").feature("c1").label("OuterDiameter");
model.geom("geom1").shape("circle").feature("c1").set("type", "curve");
model.geom("geom1").shape("circle").feature("c1").set("r", "0.5");

我想将model.geom("geom1").shape("circle")缩写为MGS

我需要这样一个命令很多次,因为我还想用它来缩写model.material("mat1").propertyGroup("def")model.sol("sol1").feature("s1").feature("fc1")以及model.result("pg2").feature("iso1"),并且预计将来会更多。

我更熟悉Python,它可以让我做一些非常简单的事情:

MGS = model.geom("geom1").shape("circle")
MGS.name("c1", "Circle")
MGSF = MGS.feature("c1")
MGSF.label("OuterDiameter")
MGSF.set("type", "curve")

我在java中找不到任何类似的表达式。

由于

1 个答案:

答案 0 :(得分:2)

只需使用局部变量来存储重复访问的中间值。这不仅可以使代码更具可读性,而且还可以提高效率,以防止调用获取中间值的操作非常昂贵。

有些事情:

Model model = ModelUtil.create("Model");    // Returns a model
Geom g = model.geom();
g.create("geom1");               // add a component
Component c = model.geom("geom1");
c.create("circle")                          

Circle ci = c.shape("circle");
ci.name("c1", "Circle");
Feature f = ci.feature("c1");
f.label("OuterDiameter");
f.set("type", "curve");
f.set("r", "0.5");

请注意,这只是一个定位示例,并不打算只通过复制和粘贴工作。 GeomComponentFeatureCircle类可能与您的方法的实际类名或实际返回类型不对应,我对此的具体细节一无所知。您的代码正在使用的API。