Question about using new method versus using "if else" statement

I understand why and how we wrote a new method to use in the case of the end scene linking to the start scene, but when I connected scenes, I wrote it all in one method using an “if…else” statement where the method would change to scene one if it was on the final scene, else it would simply move onto the next scene in the load order.

Can someone tell me when it would be appropriate to write it all in one method like I did and when it would be appropriate to simply write a new method like we did during the lesson?

I want to make sure my coding habits are spot on.


For reference, here is the method I used.

public void LoadScene()

	int currentSceneIndex = SceneManager.GetActiveScene().buildIndex;

	if(currentSceneIndex = 2)
        SceneManager.LoadScene(currentSceneIndex + 1); 

It’s more art than science, but you want to refactor into additional methods when you get or see a feel for any of the following happening:

  • The purpose of the method you are in, vs. what you are putting into it, seem not to match
  • The method begins to do multiple different things and the detail of those things are all in the same method together
  • The method has to keep going deeper into multiple levels of nesting to get a task done. One or two levels of nesting maybe OK
  • The method grows too big and you can’t see at a glance all that it is trying to do / the logic needed in the method is too complex to describe in a couple of lines at the top of the method

These are mostly nuances of the same problem - complexity - but sometimes only some will apply and not others. As long as one or more are applying, it’s probably time to consider if it should be refactored.

An unrelated but obvious reason to consider doing this, is if you end up repeating the same code in multiple methods. You want to avoid having to maintain that situation if the same code starts ending up in 3 places or more.

Thanks topdog. That makes sense. When in doubt, simplify.

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

Privacy & Terms