Readability Expectations
Variables && When to Create Them
A general rule: If you are going to use a value more than once in a certain scope of code its reasonable to create a reference variable.
Rationale:
- It makes your code easier to maintain, understand and update if you use a variable instead of a random value
- Having the literal 12 all over your code is not good practice. Its better to make a variable eggPackageSize=12. Then its clear where the 12 is coming from. Its also much easier to update your code if eggPackageSize changes from 12 to 18, you only have to change the variable.
- Even if you are using a value retrieved by a ‘getter’ method… if you know the value will be the same, it is more efficient to create a variable than to have your program create multiple function calls.
- (Note that accessing a field or attribute of an object does not require a function call so you gain no speed/processing by creating a variable. )
Note: If you see code from my introductory courses you may see extra (unnecessary) variables! These are added deliberately to help new programmers to understand what is happening.
Style preference:
If you have a complex line/section of code, for example a long string of method calls, it may increase readability to break this up and use an ‘extra’ variable.
//Java example
// Before
String[] test = input.nextLine().toLowercase().split("\t");
// After
String line = input.nextLine().toLowercase();
String[] test = line.split("\t");
Be aware: These are my opinions. Other instructors will have their own policies!
Check out more of my readability expectations by language: