- #1
- 2,076
- 140
There really is no specific guideline for this. Personally, I like to write my code as compact as I can, but is there really a problem with this? Having those small complicated statements can make code hard to read, but is that not up to the developer's/reader's level of skill?
For example, the following is a piece of code written in java (A language I'm sure most programmers are familiar with, so I'll use it for this example). It is written inside a Seat class where there is a private field called 'booked' of type boolean. It should be fairly clear what this code segment accomplishes:
Below is a piece of code which accomplishes exactly the same thing. Although you will notice the syntax is significantly different:
Many will claim the second piece of code is hard to read, and they would prefer the first version.
Is there really a disadvantage to writing code like in the second code block? I think it might be coder's apathy if anything.
More importantly, are there actual advantages to writing code so compactly? Does it influence the run-time in any fashion? Does it have other benefits?
When is code readability actually a factor? If you are working with software professionals, I'm sure they would be able to read both versions anyway.
What are your opinions?
For example, the following is a piece of code written in java (A language I'm sure most programmers are familiar with, so I'll use it for this example). It is written inside a Seat class where there is a private field called 'booked' of type boolean. It should be fairly clear what this code segment accomplishes:
Code:
/**
* If this seat is available, books it and returns true.
* If the seat is not available, returns false.
*
* @return boolean: True if the seat was successfully booked, false otherwise.
*/
public boolean book(){
if(!booked){
booked = true;
return true;
}
return false;
}
Below is a piece of code which accomplishes exactly the same thing. Although you will notice the syntax is significantly different:
Code:
/**
* If this seat is available, books it and returns true.
* If the seat is not available, returns false.
*
* @return boolean: True if the seat was successfully booked, false otherwise.
*/
public boolean book(){
return !booked ? booked = !booked : false;
}
Many will claim the second piece of code is hard to read, and they would prefer the first version.
Is there really a disadvantage to writing code like in the second code block? I think it might be coder's apathy if anything.
More importantly, are there actual advantages to writing code so compactly? Does it influence the run-time in any fashion? Does it have other benefits?
When is code readability actually a factor? If you are working with software professionals, I'm sure they would be able to read both versions anyway.
What are your opinions?