1

I've got an app that has a Main Page, a Room page, and then a subroom of the room page.

To know what to show on the detail page, the detail page needs a string value from the Main page, and in the subroom it needs a Room class object from the room page.

I've been just setting these as static variables on my Room class, so when I'm needing the string or object I'd do

selectedRoomname = Room.selectedName
selectedInstance = Room.selectedInstance

It would be very possible to pass these variables around with segues or use delegegates, but is there any reason to NOT continue what I'm doing? Considering it's only two variables I'm doing this with I can't imagine there's a big impact on memory usage. Is there a limit to how far I could go with using static variables? If I'm needing to access a variable such as the user's username, profile image, etc on almost every one of my view controllers, is there any issue with making a static User class object?

tl;dr, how intense is it to use static variables and is there such a thing as abusing them?

1 Answer 1

3

The pragmatic reason would be that it limits you to one unique instance of a Room. If you ever want to show more than 1 room, you'll have to redesign it. That type of design is fragile and inflexible.

The more philosophical reason is that it breaks OOP. A class should not keep track of itself, that's it's parent's job (with a possible exception singletons but that's a whole other can-o-worms). It also makes subclassing tricky. Should a LaundryRoom class have it's own static variables? should the LaundryRoom class also use Room's static variable? That's inherently confusing.

The way I tend to solve these problems is think about it from an IRL perspective. Do all rooms have the same name? Can only 1 room ever be inhabited? If these attributes are individual to an instance and not the concept, it should be an instance variable.

Sign up to request clarification or add additional context in comments.

2 Comments

Awesome way of explaining it all, makes perfect sense. Thank ya kindly.
No problem. Good luck!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.