Abbreviating long object chain (java)

109 Views Asked by At

First of all I would like to share that I've started working with java and object oriented programming very recently so forgive me if this is a stupid question but I cannot find a clear answer elsewhere.

I'm working on a template for a Comsol model and would like to abbreviate a part of the code to make it more readable. Although the following piece of code runs with the Comsol compiler:

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");

I would like to do abbreviate model.geom("geom1").shape("circle") into something like MGS.

I need such a command a significant amount of times since I would also like to use it for abbreviating model.material("mat1").propertyGroup("def") and model.sol("sol1").feature("s1").feature("fc1") and model.result("pg2").feature("iso1") and presummably more in the future.

I am more familiar with Python which would allow me to do something very simple like:

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

I can't find any similar expression in java.

Thanks

1

There are 1 best solutions below

2
On BEST ANSWER

Just use local variables to store intermediate values that are accessed repeatedly. This won't only make the code more readable but also improve efficiency in case the operations called to get the intermediate values can be expensive.

Something along the lines of:

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");

Please note this is only an orientative example and not intended to work by just copy&pasting. The Geom, Component, Feature and Circle classes might not correspond with real class names or actual return types of your methods, I do not know anything about the specifics of the API your code is using.