Re: About java program.
On 6/17/2013 9:46 AM, lipska the kat wrote:
On 17/06/13 13:49, Arved Sandstrom wrote:
On 06/16/2013 12:28 PM, Robert Klemme wrote:
On 16.06.2013 15:21, lipska the kat wrote:
On 16/06/13 00:12, Robert Klemme wrote:
On 15.06.2013 22:38, rajbhaumik@gmail.com wrote:
import acm.program.*;
public class askYesNoQuestion extends ConsoleProgram {
public void run(){
String str=readLine("Would you like instructions");
println(askYesNoquestion(str));
}
7. private boolean askYesNoquestion (String str){
if(str.equals("yes"))return true;
if(str.equals("no")) return false;
}
}
the false is that , the program cannot be executed, because no 7
said, this method must return a type of boolean.
One possible solution (not compiled or tested)
private boolean askYesNoquestion (String str){
boolean response = false;
if(str.equals("yes")){
response = true;
}
return response;
}
[snip]
To the original point, I agree to an extent. But the actual idiom that
lipska used is not bad in general, if you're used to single return. It's
sort of like *always* providing braces for conditionals, even for one
liners, defensive coding in part, but also adhering to personal coding
style.
... and what is your opinion of defensive coding?
Anyone who has ever written software to interact with a user via a
device interface knows (or should know) that defensive coding is de-riguer.
If you don't want the device to crash every time someone does something
unexpected you need to anticipate no only the unexpected but the
unanticipated. There is *no* room for error.
This discipline is hard to learn and once learned even harder to
un-learn. This is why I don't like things like
return str.equals("yes");
Why?
Your code and this code has the exact same potential for problems!?!?
It's lazy coding and harder to understand than my example
Not is is not. It has less elements to understand.
If I was doing a proper job and not just providing a simple example I
would have had a pre-condition on the method *and* exception handling
Exception handling is rarely a good thing to try ay such low level -
and especially not a NPE.
*and* braces around every conditional, even one liners,
You already had.
Arne