lundi 13 janvier 2020

Is a good practice to create a local variable and assign a field's value

Suppose we have a class with a field x. It is a value type, not an entity (let's say int or string). We create an instance method and use the field, not changing its value.

Is it a good practice to create a new local variable and assign the x's value to it? Consider the following example in pseudocode:

private instance-method(n) {
  const float x = this.x
  float y = x * x + math.sin(x)
  y += this.monte-carlo(this.space, x, n)
  this.result.y = y
}

I could use this.x * this.x + math.sin(this.x) instead, but I think it's less readable as there are too many this words. On the other hand, it is an extra line of code, which doesn't bring about much. And as regards forcing x to stay const, in most languages we can force it anyway in other ways.

What are pros and cons of such an approach? Is it a good practice? Does it make the code more readable or less readable?

Aucun commentaire:

Enregistrer un commentaire