Save-Point
Making things the hard way - Printable Version

+- Save-Point (https://www.save-point.org)
+-- Forum: Games Development (https://www.save-point.org/forum-4.html)
+--- Forum: Tutorials (https://www.save-point.org/forum-19.html)
+--- Thread: Making things the hard way (/thread-7334.html)

Pages: 1 2


RE: Making things the hard way - kyonides - 12-10-2021

After a long hiatus and having reread the whole thread, I got to say that I still defend the usefulness of my initial position BUT I don't mind if we include a specific kind of safeguard in our methods; even if we had already crafted some test scripts in the process. Yet, I cannot claim that raising errors is the only way to prevent serious errors from showing up later on.

Let us say we passed a name like "Rufus" to the int_month method above.

Code:
int_month("Rufus")

It would display the following message on screen.

Quote:Current Month is Rufus or better known as invalid.

But that only happens because we chose to include the month variable there. That might not always be the case in any ingame script. Thus we need to come up with something else to fix this issue.

Code:
def int_month(month)
  # We are adding some New Code Here
  if !month.is_a?(Integer)
    puts "TypeError: #{month} is not an integer but some #{month.class} class object!"
  elsif !month.between?(1, 12)
    puts "RangeError: Wrong Value! found #{month}, expected 1 through 12"
  end
  # Most of the Old Code Goes Here
  month_name = months[month]
end

So passing "Rufus" as an argument would print the following message on screen:


Quote:TypeError: Rufus is not an integer but some String class object!


Or if had passed 20 instead...


Quote:RangeError: Wrong Value! found 20, expected 1 through 12


You could replace puts with raise if you prefer.

But why do I care about this if and elsif statements over there? Confused
Didn't I say it's better to let the game spit an error message on your face? Thinking

Well, it's true I stated that letting users cause certain runtime errors might be helpful, yet, we can and should avoid them if we are handling simple stuff like strings or numbers in weak typed languages like Ruby and its derivative RGSS. This does not mean we should let people try to load a non existing file that is supposed to be displayed as, I dunno, some backdrop on a given scene.

You see, sometimes the array or hash approach might be helpful but not always and this is something extremely important to keep in mind. You got to know the existing limitations of a language or an implementation of any method and plan accordingly. This also means that you got to accept that the time might have come to rewrite a whole method or script from scratch if deemed necessary by your current circumstances.