Fun with Number readFrom: What should we do ?

nicolas cellier ncellier at ifrance.com
Thu Apr 27 12:29:56 UTC 2006


Le Jeudi 27 Avril 2006 12:14, vous avez écrit :
> nicolas cellier wrote:
> ...
>
> > What do you vote for ? exception, answering 0, any other idea ?
> > What to do with the stream in case of error ? rewind, keep in place ?
> > I'am waiting for your comments.
>
> Answering nil of course. To answer 0 is outright wrong and raising an
> exception is at least to cumbersome. One could rate it being wrong too,
> because unknown text that has to be converted is a valid input, and thus
> finding no correct float is a valid result - nil.
>
> Regards,
> Martin

I will formulate my first answer in good Smalltalk, this will be more 
expressive than my bad english:

My proposition is:

Number>>readFrom: aStringOrStream
    ^self readFrom: aStringOrStream ifFail: [^self error: 'cannot read a 
number']

If nil is what you want, you will have to write:
    value := Number readFrom: aStream ifFail: [nil].
A little longer than your proposition:
    value := Number readfrom: aStream.

But in the case you really want an exception (i guess this is most wanted 
behavior), mine is better:
    value := Number readfrom: aStream.
Yours would be:
    (value := Number readFrom: aStream) ifNil: [self error: 'etc...'].

And if you have a local exception handling:
    value := Number readFrom: aStream ifFail: [local handler block]
not much different from what would be implied by your proposition:
    (value := Number readFrom: aStream) ifNil: [local handler block]

But with mine, you can also have a global exception handling:
  [value1 := Number readfrom: aStream.
    value2 := Number readFrom: aStream]
      ifError: [global handler block]

Maybe a new exception class is better than Error, but i do not take this 
responsability alone.
  [value1 := Number readfrom: aStream.
    value2 := Number readFrom: aStream]
      on: NumberReadError do: [:exc | global handler block]

Hope i convinced someone.

Nicolas




More information about the Squeak-dev mailing list