WrRaThY
WrRaThY

Reputation: 1998

Java performance - good practices (using references)

This is the basic structure of code on a project I am contributing to:

protected ModelAndView showForm(ActionContext ctx) throws Exception {
    Command cmd = ctx.getCommand();
    SubCommand subCmd = cmd.getSubCommand();
    doSmth(cmd, subCmd);
    doSmthElse(ctx);
    doSmthElse2(ctx);
}

and every doSmthElse(ctx) begins with

Command cmd = ctx.getCommand();
SubCommand subCmd = cmd.getSubCommand();

for me it is NOT clear why it looks like this and it should be changed towards the way it looks in doSmth. Please correct me if i'm wrong, but i think it also works slower as it is now.

Upvotes: 0

Views: 89

Answers (2)

assylias
assylias

Reputation: 328618

If getCommand is as simple as return command; then there won't be any performance difference.

From a design perspective, if doSmthElse only needs the sub command to do its work, then you could indeed pass what it needs and only what it needs rather than a "generic" context object that contains unnecessary information - it will allow easier testing too. If that is the case, it would make sense to call doSmthElse(subCmd).

But that will mean that if you need more information at a later stage you will need to change the method signature.

In other words, as often, it depends...

Upvotes: 1

Tassos Bassoukos
Tassos Bassoukos

Reputation: 16142

I would say that the major point is not performance per se, but it's a conceptual/clarity thing. If the commands and subcommands always go together, then it makes more sense to replace doSmth(cmd, subCmd) with doSmth(ctx).

Regarding performance, if the object is prebuilt (that is, it doesn't get rebuilt on a getter call), it does not matter how many references to it there are.

Upvotes: 0

Related Questions