Trying to improve this code's readability

Feb 18, 2019 at 1:48pm
Hi! So I have a code like this:

1
2
3
4
5
6
7
8
class Farm
{
public:
	Farm();
	~Farm();

	Object farmObj;
};


Where Object is a custom data type that holds various other custom data types. All this is good and all until I discovered my calling procedure looks something like this:

1
2
3
4
Farm farm;
farm.farmObj.shader.Bind();
farm.farmObj.transform.position = Vector3D(0.0f, 1.0f, 0.0f);
farm.farmObj.Draw();


So basically, I don't like how I'm having to say farm.farmObj to access all these other elements. Any efficient way I can immediately access the object type through the identifier's name like so: farm.shader.Bind()?

Thanks!
Last edited on Feb 18, 2019 at 1:50pm
Feb 18, 2019 at 1:57pm
you can hide farmobj. (by the way calling some class "object" is terribly unhelpful, on par with int "variable").

you could, for example, inherit object instead of has-a, which lets you say farm.Draw() directly. Is that worth doing, or do you need a has-a for some reason?
Feb 18, 2019 at 2:18pm
I usually do this:
1
2
3
4
5
Farm farm;
Object &obj(Farm.farmObj);
obj.shader.Bind();
obj.transform.position = Vector3D(0.0f, 1.0f, 0.0f);
obj.Draw();

In this case there is zero overhead to creating the reference. The compiler doesn't even need to create a pointer to implement the reference - it is a synonym for Farm.farmObj and the compiler knows where it's located relative to the top of stack.

Another possibility is to create some inline functions and/or references:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Farm
{
public:
	Farm();
	~Farm();

	Object farmObj;
	void Bind() {farmObj.Bind(); }
	Position &position(farmObj.transform.position);
	void Draw() {farmObj.Draw(); }
};
...
Farm farm;
farm.Bind();
farm.position = Vector3D(0.0f, 1.0f, 0.0f);
farm.Draw();
};
Feb 19, 2019 at 5:33am
Thanks for the feedback guys! Jonnin's reply had me thinking for a bit and I ended up inheriting from class Object instead. However, I'm not entirely sure whether I'm happy with it because I'm not a big fan of inheritance, but in this case inheritance seems to be fitting. dhayden's lValue reference and inline functions works out nicely as well so I think in the future I will consider all those options when I run into a problem like this one. Thanks! ^^
Topic archived. No new replies allowed.