iCodeLikeImDrunk
iCodeLikeImDrunk

Reputation: 17866

How do I solve this sonar rule?

Dodgy - Write to static field from instance method

This is the line it is referring to:

record.setEarliestTradeDate(earliestTradeDate = value.earliestTradeDate);

Some more code:

Record record = getRecord(value.id);
private static Date earliestTradeDate = null;
public void setEarliestTradeDate(Date newValue) { earliestTradeDate = newValue; }

It is definitely not causing any sort of errors, but I would like to clear up the projects of any red-marked lines of code.

Upvotes: 1

Views: 4929

Answers (1)

oers
oers

Reputation: 18714

This is a hint that it is possible to change the static

static Date earliestTradeDate

in an instance method (i.e. not static)

public void setEarliestTradeDate

This is (or could be problematic) because all instances of your object can change the state of that variable.
You can fix this by making the method static as well, so that the static variable will ony be changed in a static context. It seems to me, that this is the right approach here, because earliest Date is a fixed point somewhere in your code.

public static void setEarliestTradeDate

Or make this Date an instance variable:

private Date earliestTradeDate

This also could be a case for the singleton pattern.

Upvotes: 1

Related Questions