Given the following two snippets:
Snippet 1:
public void foo(Data data, AbstractNode node)
{
int originalId = data.getCurrentId;
node.execute(data);
//If node changed currentId reset it to the original.
data.setCurrentId(originalId);
}
Snippet 2:
public void foo(Data data, AbstractNode node)
{
int originalId = data.getCurrentId;
node.execute(data);
resetCurrentIdIfChangedByNode(data, originalId);
}
private void resetCurrentIdIfChangedByNode(Data data, int originalId)
{
data.setCurrentId(originalId);
}
In both cases it is not be known whether node.execute() changes the currentId or not.
Does the one-line method in Snippet 2 make the code more readable? Or is it preferable to use comments as in Snippet 1?
EDIT: I understand that node has side effects. This is why I'm resorting to creating a method that explains (or tries to explain) that the data.currentId might be changed by node. Depending on which subclass of AbstractNode is being used, it might be changed or not.
EDIT 2: The reason there is no if statement around the reset in Snippet 2 is that it would be pointless, since the result would be the same whether we check or not.
private void resetCurrentIdIfChangedByNode(Data data, int originalId)
{
data.setCurrentId(originalId);
}
same result as
private void resetCurrentIdIfChangedByNode(Data data, int originalId)
{
if(data.getCurrentId() != originalId)
{
data.setCurrentId(originalId);
}
}