I could use some guidance on when to place code in...
# codingconventions
e
I could use some guidance on when to place code in a companion objects vs. at the top level. For example, I have:
Copy code
class WordleGame(val secretWord: String) {
  // lots of stuff in here pertaining to a single game of Wordle.
  val guesses = mutableListOf<String>()

  fun guessWord(guess: String): String {
    ...
  }
}

fun playGame() {
  // Load dictionary.
  val wordleGame = WordleGame(dictionary.random())
  // Solicit guesses from user and feed them to game object, etc.
}
Should
playGame()
be in a
companion object
in
WordleGame
? It certainly would be a handy place to keep the dictionary.
c
In my experience this tends to play out according to whether you are using extension methods and whether they need to access private values, say. If they need to access private values, then this values need to be top level. At the same time, you might also expose public values on
companion object
. That’s been my experience anyway.