Why Not Directly Call the storyText variable

In the State.cs we create the variable storyText, then we create a GetStateStory method which returns the variable.

Why can’t we directly call storyText from AdventureGame.cs by making it public? I have gotten through the lecture and understood it, however this seems like an extra, possibly unnecessary step. I understand that calling a full Method from another class can be useful if you are doing multiple things within it, but here, since we are only having it do one thing, it seems extraneous.

Enjoying the course so far, this is my first time coding!

Hi,

In object-oriented programming, allowing “everything” to override the value of a variable is considered bad practice because that could easily break something. Furthermore, it makes debugging challenging because if “everything” could manipulate our variable, we will have to check “everything” to find the problem. As you can probably imagine, such a task could become quite time-consuming in larger projects. For this reason, we prefer to keep our variables private if possible and to “send” the value only. While the “receiver” could change the received value, it cannot change the value of our variable.

If you need an analogy: Assuming you got an e-mail and your friend wants to read it. Instead of giving them the password to your e-mail account, you forward the e-mail to them.

Did this clear it up for you? :slight_smile:


See also:

3 Likes

Yes, this makes complete sense! Thank you very much Nina!

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms