Transform an unless statement into an if statement

To change an unless statement to an if statement what is the best practice?

Unless statement is @object_accept?

If statement could be:

  1. @object_accept? == false
    or
  2. !@object_accept

unless is simply “if not” So, in your example,

unless @object_accept? means if !@object_accept?, or in plain English, “If the instance variable called “object_accept” is false.”

Of course, using the if ! is not very idiomatic Ruby, so I would recommend sticking with the unless @object_accept?

1 Like

The way I approach this situation is by encapsulating the logic inside a method. For instance, “object_accept?” can be encapsulated inside a method called “object_not_accepted?”. That way we’ll be using the if instead of unless statement.

I’d rather do it when the if statement has an else case.

1 Like

I’d rename your variable @object_accepted for starters. Then I’d probably just go with an unless.

unless @object_accepted
  do_something
end

Unless you need an else branch. Never use unless... else....

If you only ever care about @object_accepted being false, I’d consider flipping the variable and the logic to @object_declined.

1 Like

encapsulating the logic in a “not” method sounds like a great idea! Thank you so much for that tip.

For testing purposes I need to be able to change the state of an object in various ways. So I can test the states when they are true or false. Is it good practice to create methods just for testing purposes?

For example for the thing object there are approximately 8 states I need to test for.

  • Ability to makes these states true for the object:
    @thing_state1, @thing_state2 and @thing_state3 etc

  • Ability to make these states false for the object.
    @thing_not_state1, @thing_not_state2 and @thing_not_state3 etc.

To control the objects states I just need to be able to delete or add the respective data to the object’s record. Is this correct?