About java program.

R

rajbhaumik

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.
 
A

Arne Vajhøj

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.

Let meask you a question: what value will the method return if
the input string is "xxx"?

Arne
 
R

Robert Klemme

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.

And, do you have a particular question or are you just informing us of
your compiler error?

Kind regards

robert
 
R

Roedy Green

private boolean askYesNoquestion (String str){
if(str.equals("yes"))return true;
if(str.equals("no")) return false;

what should it return if I typed "maybe"?
 
R

Robert Klemme

One possible solution (not compiled or tested)

private boolean askYesNoquestion (String str){
boolean response = false;
if(str.equals("yes")){
response = true;
}
return response;
}

Why are you making it so complicated? Just do

private static boolean isStringYes(String str) {
return str.equals("yes");
}

Or, for NPE safety:

private static boolean isStringYes(String str) {
return "yes".equals(str);
}

Btw, I also changed the name because the method did not ask a question
at all.

Cheers

robert
 
A

Arne Vajhøj

This is the age old argument about the use and abuse of the return
statement. I can't see us coming to a MAC so there's little point
arguing about it here really.

But OK, it's another solution.

How can it be misuse of return to have a non-void method
with a single return statement as the last statement returning
what should be returned?

Arne
 
A

Arved Sandstrom

Why are you making it so complicated? Just do

private static boolean isStringYes(String str) {
return str.equals("yes");
}

Or, for NPE safety:

private static boolean isStringYes(String str) {
return "yes".equals(str);
}

Btw, I also changed the name because the method did not ask a question
at all.

Cheers

robert
To some extent I agree with you, Robert.

A little side note about the NPE-safe form of doing "equals": this can
sometimes bite because of the very liberal method signature. Just last
week I was doing some CXF+JAXB work with SOAP, and for a few hours I was
perplexed as to why a a path was not being taken. Anyone who has worked
with generated code for SOAP knows how verbose and encapsulated and
boilerplate it is; lots of commenting and good white space needed, and
copy & paste is to be avoided (albeit tempting).

Anyway, come to find out that I was doing a String equals (had to be
equals, not equalsIgnoreCase), and the argument was not a String but
through a typo an MXString. equals() of course happily accepted that and
always returned false.

That's not to say it wasn't my mistake, it was. But I've found that
equals() is a relatively fertile source of program defects.

With your method it's not a concern, you're controlling the type of the
parameter. But in wider expanses of code then it's important to nail
down that the 2 objects being compared are of the expected types. Code
reviews, maybe even an instanceof if correctness at this point is
essential (more so than we usually desire but often don't achieve :))

For String in particular, I wouldn't actually mind if there was an
equals(String). In some cases I'll use String#compareTo(String) to
achieve that.

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.

AHS
 
A

Arved Sandstrom

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, (e-mail address removed) 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?

Not far different from yours, apparently.
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");

It's lazy coding and harder to understand than my example and yes, I
realize that it's only a one liner but the next stage in the
'development' of this style is

if(something){
return something;
}
else if(something else){
return something else;
}
else{
return some other value
}

It is much easier to understand and debug
the following

type var;

if(something){
var = something;
}
else if(something else){
var = something else;
}
else{
var = some other value
}

return var;

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
*and* braces around every conditional, even one liners,
*and* a fallback position if the operation was mission critical. So yes,
it's my personal style learned from painful experience.

Thank you for understanding

lipska
Generally speaking all of this boils down to one thing: errors happen
when the same developer - you, me, anyone - has white-box knowledge of,
and maybe responsibility for, both called *and* calling code. This
extends even to method lexical scope where a developer may write some
stuff that makes assumptions about his or her own code in the same
method 50 lines previous.

I daresay that this state of affairs is the norm. Sure, a whole bunch of
developers work on NASA or defense or avionics or Big Healthcare type
projects where you've got a great deal of imposed rigor. But very likely
most developers own a whole bunch of code, and I'm sure that a large
number of us write entire apps. For example, as a software consultant I
often do analyze, design and code entire applications.

So, given this, it's necessary to be somewhat schizophrenic - when
working on method X in class A, and it's called by method Y in class B
and method Z in class C, and you are writing *all* of them, you need to
wear 3 hats. And by extension N hats as you implement the entire app,
and even more because you're also doing design and analysis.

God forbid that the developer also does the functional and integration
and system testing, but this is not rare. But let's ignore that aspect
of real life. :)

If there actually is a good sized team the same considerations apply.
The nature of the beast these days is that often developers have
visibility into calling code that they don't have responsibility for,
because they do git or svn or hg, and they inevitably see way more than
they ought to.

I've rarely seen it done, because it adds substantial cost, but a better
approach would be to have each developer assigned (a) method(s) in a
class just write the class, and also be given time to write necessary
scaffolding in the form of tests that exercises their code. They never
see the complete codebase. The advantage of this is that they write to a
written design spec and not to knowledge of other code, and that they
have also necessarily written useful tests.

Robert's method, the NPE-safe one that also types the method parameter,
is not objectionable to me precisely because the equals is encapsulated
in a method that constrains the type. Trivial methods of this sort are
quite handy as private methods and make the code more robust, since
equals() by itself is too Wild West.

AHS
 
J

Joerg Meier

return str.equals("yes");
It's lazy coding and harder to understand than my example and yes, I
realize that it's only a one liner but the next stage in the
'development' of this style is

Personally, I found your example considerably harder to read than the one
liner, as well as harder to read than what would have been my solution:

private boolean askYesNoquestion (String str){
if(str.equals("yes"))
return true;

return false;
}

Of course, YMMV. Obviously, I find code written the way I would write it
easier to read, so I can't be objective. The problem I have with this code:
type var;
if(something){
var = something;
}

is that I can't tell what is returned if 'something' is true. Unless I look
at all the following code, var could easily be assigned a second time to
something different before it is returned.

Liebe Gruesse,
Joerg
 
E

Eric Sosman

[...]
Personally, I found your example considerably harder to read than the one
liner, as well as harder to read than what would have been my solution:

private boolean askYesNoquestion (String str){
if(str.equals("yes"))
return true;

return false;
}

Or, for even greater clarity:

private boolean askYesNoquestion(String str) {
boolean yes;
boolean no;
if (str != null && str.equals("yes")) {
yes = true;
no = false;
} else if (str != null && str.equals("no")) {
no = true;
yes = false;
} else {
yes = no = false;
}
return (no != true && yes != false) == true;
}

(If we put our minds to it, I bet we can turn the one-liner
into an entire class hierarchy with runtime-selected plug-in
provider implementations!)
 
A

Arved Sandstrom

[...]
Personally, I found your example considerably harder to read than the one
liner, as well as harder to read than what would have been my solution:

private boolean askYesNoquestion (String str){
if(str.equals("yes"))
return true;

return false;
}

Or, for even greater clarity:

private boolean askYesNoquestion(String str) {
boolean yes;
boolean no;
if (str != null && str.equals("yes")) {
yes = true;
no = false;
} else if (str != null && str.equals("no")) {
no = true;
yes = false;
} else {
yes = no = false;
}
return (no != true && yes != false) == true;
}

(If we put our minds to it, I bet we can turn the one-liner
into an entire class hierarchy with runtime-selected plug-in
provider implementations!)
We can joke about it, but the one-liner has problems, especially if not
wrapped in a method like Robert did. I've seen exactly that one-liner
cause dozens of defects over the past 15 years of me doing Java. Not all
programmers out there are superstars like all of us here in CLJP, in
fact 99 percent aren't. If they - not graced with our wisdom and keen
skills and perspicacity - decide to use that short form - they will
almost *never* wrap it in a method that constrains the type being
compared to, or does a null check if that's also unacceptable. In which
case sooner or later - sooner usually - lack of controls elsewhere in
the code, which is par for the course, will make that elegant little
snippet fail.

AHS
 
D

Daniele Futtorovic

[...]
Personally, I found your example considerably harder to read than the one
liner, as well as harder to read than what would have been my solution:

private boolean askYesNoquestion (String str){
if(str.equals("yes"))
return true;

return false;
}

Or, for even greater clarity:

private boolean askYesNoquestion(String str) {
boolean yes;
boolean no;
if (str != null && str.equals("yes")) {
yes = true;
no = false;
} else if (str != null && str.equals("no")) {
no = true;
yes = false;
} else {
yes = no = false;
}
return (no != true && yes != false) == true;
}

Call me sceptical, but I'm sceptical: I find that one-line return
statement kinda confusing. For more clarity, it should be encapsulated:

public static boolean isTrue( boolean b ){
boolean ret;
if( b == true ){
ret = true;
}
else {
ret = false;
}

return ret;
}

private boolean askYesNoquestion(String str){
...
return isTrue( ! isTrue(no) && isTrue(yes) );
}

Better, dontcha think?

;)
 
E

Eric Sosman

[...]
Personally, I found your example considerably harder to read than the
one
liner, as well as harder to read than what would have been my solution:

private boolean askYesNoquestion (String str){
if(str.equals("yes"))
return true;

return false;
}

Or, for even greater clarity:

private boolean askYesNoquestion(String str) {
boolean yes;
boolean no;
if (str != null && str.equals("yes")) {
yes = true;
no = false;
} else if (str != null && str.equals("no")) {
no = true;
yes = false;
} else {
yes = no = false;
}
return (no != true && yes != false) == true;
}

(If we put our minds to it, I bet we can turn the one-liner
into an entire class hierarchy with runtime-selected plug-in
provider implementations!)
We can joke about it, but the one-liner has problems, especially if not
wrapped in a method like Robert did. I've seen exactly that one-liner
cause dozens of defects over the past 15 years of me doing Java. Not all
programmers out there are superstars like all of us here in CLJP, in
fact 99 percent aren't. If they - not graced with our wisdom and keen
skills and perspicacity - decide to use that short form - they will
almost *never* wrap it in a method that constrains the type being
compared to, or does a null check if that's also unacceptable. In which
case sooner or later - sooner usually - lack of controls elsewhere in
the code, which is par for the course, will make that elegant little
snippet fail.

"As simple as possible, no simpler." The observation that
a simple construct can be misused -- a true observation -- does
not mean that the cure is to add complexity. For one thing, the
added bulk offers more opportunities for misuse.

static int sum(int a, int b) {
return a + b;
}

static int sum(int a, int b) {
int total = a;
total += b;
return total;
}

static int sum(int a, int b) {
assert Integer.MIN_VALUE <= a && a <= Integer.MAX_VALUE;
assert Integer.MAX_VALUE >= b && b >= Integer.MAX_VALUE;
Random rand = new Random();
int total;
do {
total = rand.nextInt();
} while (total - a != b);
return total;
}

Seriously, there are very few reasons to add complexity, and
many to reduce it. Complexity can (sometimes) make a needed
performance improvement; complexity can (occasionally) provide a
self-check or a debugging hook; complexity can (almost never)
add clarity.

(Truthfully, now: Did you spot the error above on first glance?)
 
J

Joshua Cranmer ðŸ§

... and what is your opinion of defensive coding?

The term, as I understand it, refers to coding under the assumption that
everyone who uses your API is a stupid idiot who can't follow your rules
properly. The matter at hand here is basically a stylistic concern about
which is mentally easier to follow, which falls under the category of
"everyone has an opinion which is strongly held and won't be changed."
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");

It's lazy coding and harder to understand than my example

To you, maybe. To me, no. This kind of one liner immediately indicates
to me that the function is equivalent with the notion that the string is
exactly "yes". In your example, by contrast, that equivalence is not
obvious: it says that the answer is false unless the string is exactly
"yes", and uncovering the functional equivalence requires resolving a
double-negative.
if(something){
return something;
}
else if(something else){
return something else;
}
else{
return some other value
}

It is much easier to understand and debug
the following

Style wars much? To me, personally, early-return is often valuable,
especially in languages like C++ or Java which have useful constructs
for handling post-call cleanup such as RAII or try-finally blocks. I'm
going to stop short of saying I prefer early-return, since it is very
much a decision that applies in a specific context, and these examples
are all trying to apply a universally generic rule.

An example of my preferred code style would be something like this (the
comments preceding most of those blocks of code are necessary in this
style--if how you got there isn't trivially obvious, explain what it
means to get there):

Frabnaz getResourceFromKey(String key) {
// Normalize the key so we know exactly how to refer to it in our
// caches.
key = normalize(key);

if (!isValid(key))
throw new IllegalArgumentException(...);

// We have a hyper-optimized variant of this if we know this is
// already on a local filesystem
if (isLocalFile(key))
return getLocalFileResource(key);

// This resource must be on the network. To keep this from killing
// performance, cache uses...
MagicCache cache = foobarToGrabTheCache();
if (cache.hasResource(key))
return cache.getResource(key);

// Can't find it in the cache, so download it but save off a copy
// in the cache.
Frabnaz result = getResourceFromNet(key);
cache.putResource(key, result);
return result;
}
 
R

Robert Klemme

The term, as I understand it, refers to coding under the assumption that
everyone who uses your API is a stupid idiot who can't follow your rules
properly. The matter at hand here is basically a stylistic concern about
which is mentally easier to follow, which falls under the category of
"everyone has an opinion which is strongly held and won't be changed."

I would say though that - as a rule of thumb - the less decision points
there are in a method the easier it is to read. Of course, there are
always degenerate cases but this is certainly not one of them.

That's not lazy. Looking through the real intent of the code and
stripping the code down to exactly the minimal readable solution is more
work than just applying if else. For me, _that_ is lazy coding: it's
much simpler to hack something that "just works" than to think about the
problem to solve more and come up with a more structured and more
concise solution.
To you, maybe. To me, no. This kind of one liner immediately indicates
to me that the function is equivalent with the notion that the string is
exactly "yes". In your example, by contrast, that equivalence is not
obvious: it says that the answer is false unless the string is exactly
"yes", and uncovering the functional equivalence requires resolving a
double-negative.
Exactly.

First of all, that code above is in a method which returns a boolean.
So there are just two outcomes which can be easily handled by the return
statement with ||. If there are more input values which yield true then
one would rather use HashSet<String> to calculate the return value. At
least that would be the OO solution to me - and not a cascade of, say 7,
if else.
Style wars much? To me, personally, early-return is often valuable,
especially in languages like C++ or Java which have useful constructs
for handling post-call cleanup such as RAII or try-finally blocks. I'm
going to stop short of saying I prefer early-return, since it is very
much a decision that applies in a specific context, and these examples
are all trying to apply a universally generic rule.

Same here.

Kind regards

robert
 
J

Jeff Higgins

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.
import acm.program.ConsoleProgram;

@SuppressWarnings("serial")
public class AskYesNoQuestion extends ConsoleProgram {

public void run() {
boolean answer =
readBoolean(
"Have you read the manual?", "Yes", "No");
if(answer)
println("Yes, I will read the manual.");
else println("Yes, I will read the manual.\n"

+"<http://jtf.acm.org/javadoc/student/acm/program/ConsoleProgram.html>");
}
}
 
J

Joshua Cranmer ðŸ§

Let me say first of all that this has been another very funny exchange.
It really is quite amazing how often you guys get all pompous and
self-righteous about issues that have nothing whatsoever to do with the
issue at hand. Seriously ROFL LOL.

At the risk of being called pompous, I wish to point out that you
yourself are not innocent of those charges, choosing the least germane
part of my message as the only part to discuss. I'll assume you're doing
the same thing I tend to do--only responding to the parts of the message
you disagree with.
Let me try again, I'll try to keep it simple as you are obviously
struggling.

Oh, I am not so incompetent in reading comprehension as to not know what
you meant by defensive programming. I was just pointing out that it
wasn't the definition I have heard used before by giving the definition
that I used.
When you write software to control a device that will be used to
interact with human beings you need to anticipate every possible **** up
in expected input. You need to deal with erroneous key sequences,
incorrect data, communications problems, canceled transactions and any
number of other unexpected occurrences and you need to do this in a way
that allows you to recover the device and place it in a state that
doesn't cause the entire edifice to lock up and crash.

*This* is what I mean by defensive programming.

And I'd call it "basic principles of good programming." :)
 
A

Arved Sandstrom

On 6/17/2013 2:32 PM, Joerg Meier wrote:
[...]
Personally, I found your example considerably harder to read than the
one
liner, as well as harder to read than what would have been my solution:

private boolean askYesNoquestion (String str){
if(str.equals("yes"))
return true;

return false;
}

Or, for even greater clarity:

private boolean askYesNoquestion(String str) {
boolean yes;
boolean no;
if (str != null && str.equals("yes")) {
yes = true;
no = false;
} else if (str != null && str.equals("no")) {
no = true;
yes = false;
} else {
yes = no = false;
}
return (no != true && yes != false) == true;
}

(If we put our minds to it, I bet we can turn the one-liner
into an entire class hierarchy with runtime-selected plug-in
provider implementations!)
We can joke about it, but the one-liner has problems, especially if not
wrapped in a method like Robert did. I've seen exactly that one-liner
cause dozens of defects over the past 15 years of me doing Java. Not all
programmers out there are superstars like all of us here in CLJP, in
fact 99 percent aren't. If they - not graced with our wisdom and keen
skills and perspicacity - decide to use that short form - they will
almost *never* wrap it in a method that constrains the type being
compared to, or does a null check if that's also unacceptable. In which
case sooner or later - sooner usually - lack of controls elsewhere in
the code, which is par for the course, will make that elegant little
snippet fail.

"As simple as possible, no simpler." The observation that
a simple construct can be misused -- a true observation -- does
not mean that the cure is to add complexity. For one thing, the
added bulk offers more opportunities for misuse.

static int sum(int a, int b) {
return a + b;
}

static int sum(int a, int b) {
int total = a;
total += b;
return total;
}

static int sum(int a, int b) {
assert Integer.MIN_VALUE <= a && a <= Integer.MAX_VALUE;
assert Integer.MAX_VALUE >= b && b >= Integer.MAX_VALUE;
Random rand = new Random();
int total;
do {
total = rand.nextInt();
} while (total - a != b);
return total;
}

Seriously, there are very few reasons to add complexity, and
many to reduce it. Complexity can (sometimes) make a needed
performance improvement; complexity can (occasionally) provide a
self-check or a debugging hook; complexity can (almost never)
add clarity.

(Truthfully, now: Did you spot the error above on first glance?)
I didn't spot the error at first glance until you said there might be
one and I went into code review mode. :) Having said that, I'd shoot a
coder who also perpetrated that while condition. :)

Those asserts are actually an example of poorly maintainable code, and
given the calibre of the average coder I'd rebuke the clever programmer
who felt he had to write that. His follow-on maintainers may not get it
completely.

Point being though, compactness is not always less complexity. It works
in some languages, not in others. In APL-like languages like J it's an
art form; in functional languages with powerful constructs it's often
natural too. In languages like Java, it may or may not be appropriate, IMO.

I often decide against method chaining in Java, for example, so that I
can break out the intermediate results and give them descriptive names.
This is if the methods are my own or part of the app under development,
I'm more willing to chain if the methods are part of a well-known and
established API.

I also don't much do complicated logic tests. Not that yours are overly
complex in your contrived example, but I wouldn't normally write that
way. The fact that it takes some careful study to spot the error is a
sign that maybe it's a maintenance problem waiting to happen.

That limits test is something that I might make a method actually. I do
something similar if I need to do a zero-closeness test for floating
points; I'll make that a carefully tested private utility method.

To recap, I don't think verbosity is always bad. I don't think that
unrolling stuff and avoiding cleverness is bad. I am in vehement
agreement with you that complexity almost never adds clarity; I dispute
in a friendly fashion that careful extra code checks are the kind of
complexity that is of concern. From a metrics standpoint, sure, there is
some addition of complexity, but not of the type that concerns me.

AHS
 
A

Arved Sandstrom

[...]
Personally, I found your example considerably harder to read than the one
liner, as well as harder to read than what would have been my solution:

private boolean askYesNoquestion (String str){
if(str.equals("yes"))
return true;

return false;
}

Or, for even greater clarity:

private boolean askYesNoquestion(String str) {
boolean yes;
boolean no;
if (str != null && str.equals("yes")) {
yes = true;
no = false;
} else if (str != null && str.equals("no")) {
no = true;
yes = false;
} else {
yes = no = false;
}
return (no != true && yes != false) == true;
}

Call me sceptical, but I'm sceptical: I find that one-line return
statement kinda confusing. For more clarity, it should be encapsulated:

public static boolean isTrue( boolean b ){
boolean ret;
if( b == true ){
ret = true;
}
else {
ret = false;
}

return ret;
}

private boolean askYesNoquestion(String str){
...
return isTrue( ! isTrue(no) && isTrue(yes) );
}

Better, dontcha think?

;)
See my answer to Eric, all this is just ridiculing reasonable
programming practices.

Even given Robert's example where the NPE-safe equals() is wrapped in a
method that constrains the type of object being compared to, it may not
be expected or acceptable that the String is null. So perhaps you do
want to check for that, maybe with Apache StringUtils.isBlank().

Sure, the contrived absurd examples are retarded; so is the mockery of
defensive programming. Oh well, there's a reason why most software
projects still fail or go vastly over budget.

AHS
 
L

Lew

lipska said:
Let me say first of all that this has been another very funny exchange.
It really is quite amazing how often you guys get all pompous and
self-righteous about issues that have nothing whatsoever to do with the
issue at hand. Seriously ROFL LOL.

Classic psychological projection.
Let me try again, I'll try to keep it simple as you are obviously
struggling.

You are obviously trolling.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,015
Latest member
AmbrosePal

Latest Threads

Top