Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Best Practice: nested getters? or delegates?

Tags:

java

android

No doubt this is a n00b question, but I would appreciate guidance or a link.

I am writing an Android game app, which includes plenty of interaction between the Activity and other classes. In doing so, I'm not sure which is better practice for example for calling a "updatePlayer" method.

Choice A is chained getters, so I might have in myActivity:

mGame.getPlayerList().getCurrentPlayer().updateScore(score);

Choice B is delegation (hopefully I am using the term correctly):

mGame.updateCurrentPlayerScore(score);

then in Game:

playerList.updateCurrentPlayerScore(score);

then in PlayerList:

currentPlayer.updateScore(score);

I can see the advantage of Choice B because I am then free to change the structure and behavior of playerList and Game, but it sure adds a lot of one-line methods.

Am I thinking corrrectly? Is there a Choice C or D?

like image 579
Opus1217 Avatar asked Nov 01 '22 07:11

Opus1217


1 Answers

Personally I've always thought coding styles as a matter of opinion. If your coding just for yourself you do what works and is simplest for you. For example in java you name variables in camel case (intVar) but in python you use underscores (int_var). It wouldn't matter if you used underscores in java and camel case in python in an independent environment.

However...

In a place where people must read and understand your code, I'd try to follow conventional coding styles as much as possible just for extra clarity.

For your scenario, what ever floats you boat. Traditionally the getters and setters is the accepted coding style for java.

Extending your classes might also help on not showing your implementation of higher level classes.

like image 71
JGerulskis Avatar answered Nov 12 '22 16:11

JGerulskis