programming best practices

S

swille

I have a couple of standard programming questions. The first is that
I often like to return true or false in a method when no other return
value is really needed. Is that bad form? I was talking to someone
the other day who said said something that made me think that maybe it
was. For example:

def login()
rc =3D false
begin
perform action
rescue
rc =3D false
some error
end

return rc
end

I like that because it reads well when you use it

if login
do_stuff
else
complain
end

My second question is this. I occasionally see stuff like
if -1 =3D=3D result

rather than
if result =3D=3D -1

What, if any, is the benefit of one over the other?

Thanks
 
J

jwheeler1

Is that bad form?

I do the same thing. Not taking return values into account could have
adverse effects on clients when you release a new version of your API.
no benefit, just stylistic preference.
 
E

Eero Saynatkari

swille said:
I have a couple of standard programming questions. The first is that
I often like to return true or false in a method when no other return
value is really needed. Is that bad form? I was talking to someone
the other day who said said something that made me think that maybe it
was. For example:

def login()
rc = false
begin
perform action
rescue
rc = false
some error
end

return rc
end

I like that because it reads well when you use it

if login
do_stuff
else
complain
end

Whenever it makes sense, do it. If you do not have a use case
like above there is no point in returning a value here it would
seem to be fine. Because in Ruby we can use '?' as a method suffix,
there is really no source of confusion whether you are testing if
someone has logged in (you would use 'login?' for that). In Java,
I imagine, you would use something like 'try_login' instead to
convey the idea of an attempt to do something and a subsequent
test.

Then again, I may be biased. I just tried to suggest Kernel.puts
return true :)
My second question is this. I occasionally see stuff like
if -1 == result

rather than
if result == -1

What, if any, is the benefit of one over the other?

I think this habit is from C and so on; if instead of typing
'if result == -1' you typed 'if result = -1', a possible error
condition would ensue. Many languages and compilers do not issue
a warning about this (lack of a) conditional.

However, when you write 'if -1 == result' there is no possibility
of confusion because the interpreter/compiler would immediately
complain when seeing 'if -1 = result' (can not assign to a literal).


E
 
D

David A. Black

Hi --

I have a couple of standard programming questions. The first is that
I often like to return true or false in a method when no other return
value is really needed. Is that bad form? I was talking to someone
the other day who said said something that made me think that maybe it
was. For example:

def login()
rc = false
begin
perform action
rescue
rc = false
some error
end

return rc
end

I like that because it reads well when you use it

if login
do_stuff
else
complain
end

But the way you've written it, rc is always false. Did you mean true
in the first line? :)

Also, it seems a little bit like you've got two error-reporting
systems going on. Maybe you could combine them:

def login
perform action
end

begin
login
rescue
...
end

etc.
My second question is this. I occasionally see stuff like
if -1 == result

rather than
if result == -1

What, if any, is the benefit of one over the other?

As another answerer said, the first one (if -1 == result) protects you
from accidentally writing = instead of ==. In Ruby it's less of an
issue than in other languages because you'll get a warning:

if a = 1; end
(irb):1: warning: found = in conditional, should be ==

It's considered worthy of warning because there would never be any
"if" about a case like this: 1 is true, so the expression "a = 1" is
true.

The cool thing about this is that you *don't* get the warning when you
might actually want to do it:

b = 1
if a = b # no warning


David
 
L

Lyndon Samson

I have a couple of standard programming questions. The first is that
I often like to return true or false in a method when no other return
value is really needed. Is that bad form? I was talking to someone
the other day who said said something that made me think that maybe it
was. For example:

def login()
rc =3D false
begin
perform action
rescue
rc =3D false
some error
end

return rc
end

I like that because it reads well when you use it

if login
do_stuff
else
complain
end

Ruby doesnt have procedures, so every method call returns a value. Its
just nil by default.

Also, error conditions are usually best signalled with exceptions,
which sort of make checking return values redundant.



My second question is this. I occasionally see stuff like
if -1 =3D=3D result
Poor programmers do this to avoid accidental assignment :)
 
L

Lloyd Zusman

swille said:
[ ... ]

My second question is this. I occasionally see stuff like
if -1 == result

rather than
if result == -1

What, if any, is the benefit of one over the other?

Thanks

Well, the traditional reason is because by putting the number to the
left of the comparison, you're protected against the case where you
might accidentally type a single equal sign instead of a double:

#!/usr/bin/ruby -W0
result = 0
if result = 1 # programmer meant to type "result == 1"
puts "one"
else
puts "not one"
end

This will print "one", even though "not one" is what is expected.

However, if you do the following, the compiler will give you an
error:

#!/usr/bin/ruby -W0
result = 0
if 1 = result # programmer meant to type "1 == result"
puts "one"
else
puts "not one"
end

The first case can lead to subtle, very hard to find bugs. The second
case won't even compile, so you know right away that there's a problem.

Of course, without -W0, you will get a warning in the first case, which
helps you see the potential problem. Nonetheless, many people have
gotten in the habit of using this little trick, just to be on the safe
side.
 
S

swille

But the way you've written it, rc is always false. Did you mean true
in the first line? :)

Also, it seems a little bit like you've got two error-reporting
systems going on. Maybe you could combine them:

def login
perform action
end

begin
login
rescue
...
end

etc.

Ah, yes, that was a typo. My example possibly wasn't the greatest...
I couldn't think of exactly when I had used it last in Ruby. It's
actually something I've been using in Java quite a bit because I've
been writing interfaces into JavaScript and there's no way (in
JavaScript) to handle the exceptions from Java, so I use a boolean
return value. I decided at some point that I really like the
aesthetics of it. After a colleague questioned that behavior in
another context though, I thought twice about whether it was a good
idea. Basically, I suggested he use a boolean return value to a
method and he said something to the effect that it would be more
proper to return int-based return codes because "some_method true?"
didn't sound right. I wondered if maybe I was going to regret not
going to college :O)
 
Z

zdennis

swille said:
I have a couple of standard programming questions. The first is that
I often like to return true or false in a method when no other return
value is really needed. Is that bad form? I was talking to someone
the other day who said said something that made me think that maybe it
was. For example:

def login()
rc = false
begin
perform action
rescue
rc = false
some error
end

return rc
end

Not really pertinent to your question, but another way to do your example code is to utilize the
rescue clause at the method level which gets rid of the need for a temporary variable and makes your
method shorter, which IMO can go towards better readability.

def login
perform action
true
rescue
false
end

Zach
 
R

Robert Klemme

swille said:
Ah, yes, that was a typo. My example possibly wasn't the greatest...
I couldn't think of exactly when I had used it last in Ruby. It's
actually something I've been using in Java quite a bit because I've
been writing interfaces into JavaScript and there's no way (in
JavaScript) to handle the exceptions from Java, so I use a boolean
return value. I decided at some point that I really like the
aesthetics of it. After a colleague questioned that behavior in
another context though, I thought twice about whether it was a good
idea. Basically, I suggested he use a boolean return value to a
method and he said something to the effect that it would be more
proper to return int-based return codes because "some_method true?"
didn't sound right. I wondered if maybe I was going to regret not
going to college :O)

<soapbox>
IMHO using int's as return values is as bad as using boolean return values
in a language that has exceptions. Exceptions are a far more elegant way
of handling errors and also often code will be shorter and cleaner. One
of the reasons for this is that you can throw an exception somewhere deep
down in an application or lib and catch it several layers above - at the
level where it makes most sense. If you want to do that with boolean /
int return values you'll have checking and returning code in all
intermediate layers - this is bloated, ugly and unflexible.
</soapbox>

Kind regards

robert
 
L

Lyndon Samson

<soapbox>
IMHO using int's as return values is as bad as using boolean return value= s
in a language that has exceptions. Exceptions are a far more elegant way
of handling errors and also often code will be shorter and cleaner. One
of the reasons for this is that you can throw an exception somewhere deep
down in an application or lib and catch it several layers above - at the

Well if you were really against Exceptions you could allways use
continuations to do this more elegantly than nested returns.
 
R

Robert Klemme

Lyndon said:
Well if you were really against Exceptions you could allways use
continuations to do this more elegantly than nested returns.

I'd be curious how an exception equivalent behavior with continuations
would look like. ATM I have the impression that it'll be far more
complex...

Kind regards

robert
 
G

gwtmp01

IMHO using int's as return values is as bad as using boolean return
values
in a language that has exceptions. Exceptions are a far more
elegant way
of handling errors and also often code will be shorter and cleaner.

I tend to think there is a middle ground also. Bertrand Meyer has
written
a lot about the use of exceptions in programming. I tend towards his
model
where an exception is, well, exceptional. That is to say that an
exception
shouldn't be used to model an outcome that is *expected*.

There is a nice side bar in Agile Web Development in Rails where
David talks
about Active Record and exceptions. He explains why:

Person.find(5)

raises an exception if the record is not found while

Person.find:)first, :condition => "name = 'Dave'")

returns an empty result if the record is not found. The difference is
that
in the first case, the assumption is that the record exists (otherwise I
wouldn't have known to use 5 versus some other key). If the record
doesn't
exist then something bad or exceptional has happened.

In the second example, we are trying to determine if the record
exists and
so the fact that it may not exist is entirely expected. In this case
an exception is not warranted because the outcome "doesn't exist" is
anticipated by the caller.

Bertrand Meyer ties this all back to his Design by Contract philosophy.
If the outcome is part of the contract then an exception is probably not
needed. If the outcome violates the contract then the exception is
probably desired.



Gary Wright
 
K

klancaster1957

Lyndon Samson wrote:

Also, error conditions are usually best signalled with exceptions,
which sort of make checking return values redundant.


That is true as long as the error condition is truly an exception (disk
error, memory, file IO error, etc.). Using exceptions as control flow
is not a good idea - very expensive generally and not true to the
intent of exceptions.

Keith
 
R

Robert Klemme

I tend to think there is a middle ground also.

Well, yes. My statement was of course too strong. I wanted to make clear
that the quality of the code doesn't necessarily improve with the number
of distinct return values (int vs. boolean) and that it's not a good idea
to augment every method with a boolean return value that indicates success
or failure.
Bertrand Meyer has
written
a lot about the use of exceptions in programming. I tend towards his
model
where an exception is, well, exceptional. That is to say that an
exception
shouldn't be used to model an outcome that is *expected*.

There is a nice side bar in Agile Web Development in Rails where
David talks
about Active Record and exceptions. He explains why:

Person.find(5)

raises an exception if the record is not found while

Person.find:)first, :condition => "name = 'Dave'")

returns an empty result if the record is not found. The difference is
that
in the first case, the assumption is that the record exists
(otherwise I wouldn't have known to use 5 versus some other key). If
the record doesn't
exist then something bad or exceptional has happened.

In the second example, we are trying to determine if the record
exists and
so the fact that it may not exist is entirely expected. In this case
an exception is not warranted because the outcome "doesn't exist" is
anticipated by the caller.

Bertrand Meyer ties this all back to his Design by Contract
philosophy. If the outcome is part of the contract then an exception
is probably not needed. If the outcome violates the contract then
the exception is probably desired.

That sums it up pretty good. After all, there is no general one size fits
all rule. Even for the orginial example it's debatable whether a failed
login is an exceptional event or an expected event. I'd probably lean
more towards expected as users occasionally mistype their id or password.

Thanks for taking the discussion one step further!

Kind regards

robert
 
L

Lyndon Samson

I'd be curious how an exception equivalent behavior with continuations
would look like. ATM I have the impression that it'll be far more
complex...
Sorry, I meant deeply nested method calls returning one-by-one up the
call stack being replaced with Continuations, not replacing
Exceptions.
 
S

Stu Glaser

I feel that if a function fails so badly that the "do_stuff" section of
your code will fail, then you should really throw an exception. This
way if someone forgets to check the return value, they will not become
confused as to why later code does not work. Throwing an exception
forces downstream programmers to use your code properly.

Especially if you plan to "complain" if login fails.

See the "Samurai Principle"
http://c2.com/cgi/wiki?SamuraiPrinciple

Return victorious or not at all!
-Stu
 

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

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top