Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > Java > About java program.

Reply
Thread Tools

About java program.

 
 
Arved Sandstrom
Guest
Posts: n/a
 
      06-17-2013
On 06/17/2013 03:49 PM, Eric Sosman wrote:
> 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.

AHS

--
When a true genius appears, you can know him by this sign:
that all the dunces are in a confederacy against him.
-- Jonathan Swift
 
Reply With Quote
 
 
 
 
Daniele Futtorovic
Guest
Posts: n/a
 
      06-17-2013
On 17/06/2013 20:49, Eric Sosman allegedly wrote:
> 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;
> }


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?



--
DF.
 
Reply With Quote
 
 
 
 
Eric Sosman
Guest
Posts: n/a
 
      06-17-2013
On 6/17/2013 5:38 PM, Arved Sandstrom wrote:
> On 06/17/2013 03:49 PM, Eric Sosman wrote:
>> 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?)

--
Eric Sosman
http://www.velocityreviews.com/forums/(E-Mail Removed)d
 
Reply With Quote
 
Joshua Cranmer 🐧
Guest
Posts: n/a
 
      06-17-2013
On 6/17/2013 8:46 AM, lipska the kat wrote:
> ... 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;
}

--
Beware of bugs in the above code; I have only proved it correct, not
tried it. -- Donald E. Knuth
 
Reply With Quote
 
Robert Klemme
Guest
Posts: n/a
 
      06-18-2013
On 18.06.2013 00:36, Joshua Cranmer 🐧 wrote:
> On 6/17/2013 8:46 AM, lipska the kat wrote:
>> ... 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."


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.

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


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.

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


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

--
remember.guy do |as, often| as.you_can - without end
http://blog.rubybestpractices.com/

 
Reply With Quote
 
Jeff Higgins
Guest
Posts: n/a
 
      06-18-2013
On 06/15/2013 04:38 PM, (E-Mail 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.
>

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>");
}
}
 
Reply With Quote
 
Joshua Cranmer 🐧
Guest
Posts: n/a
 
      06-18-2013
On 6/18/2013 3:03 AM, lipska the kat wrote:
> On 17/06/13 23:36, Joshua Cranmer 🐧 wrote:
>> On 6/17/2013 8:46 AM, lipska the kat wrote:
>>> ... 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.

>
> 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 cock 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."

--
Beware of bugs in the above code; I have only proved it correct, not
tried it. -- Donald E. Knuth
 
Reply With Quote
 
Arved Sandstrom
Guest
Posts: n/a
 
      06-18-2013
On 06/17/2013 07:30 PM, Eric Sosman wrote:
> On 6/17/2013 5:38 PM, Arved Sandstrom wrote:
>> On 06/17/2013 03:49 PM, Eric Sosman wrote:
>>> 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

--
When a true genius appears, you can know him by this sign:
that all the dunces are in a confederacy against him.
-- Jonathan Swift
 
Reply With Quote
 
Arved Sandstrom
Guest
Posts: n/a
 
      06-18-2013
On 06/17/2013 07:13 PM, Daniele Futtorovic wrote:
> On 17/06/2013 20:49, Eric Sosman allegedly wrote:
>> 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;
>> }

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

--
When a true genius appears, you can know him by this sign:
that all the dunces are in a confederacy against him.
-- Jonathan Swift
 
Reply With Quote
 
Lew
Guest
Posts: n/a
 
      06-18-2013
lipska the kat wrote:
> 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.

--
Lew
 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
I need your advices about C prg. Dogukan Bayraktar C Programming 76 06-16-2013 08:54 AM
Survey about Software Integration Martin Dias C Programming 0 04-29-2013 03:23 PM
Quesion about running a exe file in Python(Not enough memory) yuyaxuan0@gmail.com Python 5 04-26-2013 06:30 AM
silly question about Running a script from the command line A.Rock Python 0 04-10-2013 11:21 AM
newbie question about confusing exception handling in urllib cabbar@gmail.com Python 6 04-09-2013 07:11 PM



Advertisments