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?

2 answers

  • answered 2020-01-14 01:40 Steve

    In general, no, it's not usually a good practice. I'm curious, though: What language are you using? Most common programming languages will allow you to refer to a member variable without requiring "this." ... and I don't know of any that allow using a hyphen in a variable or function name.

  • answered 2020-01-14 02:02 khuynh

    If it helps readability, I would consider it good practice. In your example, the readability isn't affected that much so it could really go either way. But in general, optimizing for readability first is good practice.

    I think this answer helps sum it up:

    Code is read much more often than it is written, so you should take pity on the poor soul who will have to read the code six months from now (it may be you) and strive for the clearest, easiest to understand code. In my opinion, the first form, with local variables, is much more understandable. I see three actions on three lines, rather than three actions on one line.

    https://softwareengineering.stackexchange.com/questions/339384/should-we-eliminate-local-variables-if-we-can