Testing If Person Is Male or Female - If Not Male, Can I Assume It's Female? [closed]

StackOverflow https://stackoverflow.com/questions/21467506

  •  05-10-2022
  •  | 
  •  

Question

I would like to hear from you experts what I should do as a programmer in the following case.

Person is a class that has properties like name, birthday, etc, and one of which is gender that takes either "m" for male or "f" for female. Person class has instance method #male? and #female? to test if gender is "m" or "f", respectively.

The important thing here is that, by design, gender always has "m" or "f" and never becomes nil or any other value.

Now, I often come across the situation where I need to switch logic, depending on which value a given Person instance has in its gender field.

My question then is, is it normal to assume that the gender value is always either "m" or "f", so if it is not "m", then it must be "f", like the following?

if (person.male?)
  # do male stuff
else
  # must be female. do female stuff
end

OR should I always test to make sure person is female even if it is tested to be non-male like the following?

if (person.male?)
  # do male stuff
elsif (person.female?)
  # do female stuff
else
  raise "Person is neither male nor female."
end

I feel that the second example is a bit repetitive, and that, more importantly, this if/else clause is not the place for testing the data inconsistency of the model, so I tend to go with the first case, but everytime I do this, I wonder if this is the way it should be. I mean, if this is a boolean field, I would not worry about it, but it's not.

Any thoughts?

Cheers,

SAKI

Was it helpful?

Solution

Ok, let's simplicity your class to contain only sex:

class Person
  def initialize sex
      raise "wrong sex" unless ['m', 'f'].include?(sex)
    @sex=sex
  end
  attr_reader :sex
end

tom   = Person.new 'm'   # ok
anna  = Person.new 'f'   # ok
drwho = Person.new       # ArgumentError: wrong number of arguments (0 for 1)
wrong = Person.new 'cat' # RuntimeError: wrong sex

You cannot create Person with sex other than m or f (as you said).

Can you change the sex?

tom.sex='ff'
# NoMethodError: undefined method `sex=' for #<Person:0x3f32148 @sex="m">

Is there other way to change sex?

tom.instance_variable_set '@sex', 'cat'
# => "cat"
tom.sex
# => "cat"

To sum up:

Can I Assume It's Female

It depends on 2 factors:

  1. Speed
  2. Correctness

If you care about speed, you can avoid it, as you can see I used hackish way to change sex.
If you must be 100% sure, use that elsif.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top