[Coding Style] Why T something = this.something?

Started by shivshank, November 22, 2015, 00:13:37

Previous topic - Next topic

shivshank

I really don't know how to phrase this question. It might be:

Why create local references to object fields?

I'm reading LibGDX's source for inspiration. In graphics.g2d.SpriteBatch, they have code like this everywhere:
Mesh mesh = this.mesh;
mesh.setVertices(vertices, 0, idx);
mesh.getIndicesBuffer().position(0);
mesh.getIndicesBuffer().limit(count);


Does that first line do anything or is it just a form of self documentation? If it's self documentation, I'd say it's pretty snazzy for reading the source without any tools.

Cornix

This can have several advantages, none of which come into play right away. These advantages can be:
1) If member variables have nonsensical or abbreviated names the various methods can still use more readable names.
2) If member variables are renamed the implementations of methods are not effected and whoever initially wrote that method will still understand whats going on.
3) No chance of errors accidentally introduced by adding a parameter with a name equal to a member variable.
4) If you, at some point in the future, decide to no longer use "this.mesh" in the code but instead some other instance you only have to make a change at one single point in the code instead of repeating the same change everywhere.

There are more benefits, but I think you can think about them yourself. In general, when working on a team project with many members you want to write code that is clear and easy to understand. Communication is key, especially if you are too lazy to properly document.

shivshank

Okay, thank you. That makes a lot of sense. Reading it on the Github website, I also find it's great because it restates the type, so I don't need to search around for a minute.