On Thu, Nov 24, 2016 at 1:13 PM, Andy Jones <Andy.Jones / jameshall.co.uk> wrote:
>> I think that highlights that using #empty? to detect "unset" is just
>> the wrong approach. Any variable is nil - unless assigned otherwise.
>> So it's much more easier to rely on nil as the unassigned state.
>
> Well, sure.  But if you are capturing the state from somewhere else then you don't get to make that assumption.  For example, if you are entering it on the command line with `gets()` (the simplest example), if the user presses return you will get an empty string, not nil.

But you surely would not process user input without validation, would you?

> I can certainly say
>
>     entered_value = nil if entered_value.empty?
>
> ... and then pass it to your very elegant class -- but this is back to the same problem we had before, except that the code is now in two different places.

But that makes a difference. If the value is passed on via some public
method and there are illegal string values that method should ideally
do validation. The whole point of OO is that you restrict the set of
states an instance can be in (class invariant). OTOH it makes sense to
immediately validate user input to give better UX (e.g. by presenting
an error message and repeating the input).

Now, whether that should be done for every script is a different
question. I know too little about the use case of OP so lots of
speculations here. I am trying to throw up alternatives which might or
might not be better suited to the OPs situation.

The real motivation for my earlier response was to avoid situations
where people initialize with an empty string. I have seen examples of
this on this list and most of the time that was done because people
thought they need to give all member variables explicitly a value
during construction.

Kind regards

robert

-- 
[guy, jim, charlie].each {|him| remember.him do |as, often| as.you_can
- without end}
http://blog.rubybestpractices.com/

Unsubscribe: <mailto:ruby-talk-request / ruby-lang.org?subject=unsubscribe>
<http://lists.ruby-lang.org/cgi-bin/mailman/options/ruby-talk>