Search code examples
javascriptecmascript-6maintainabilitycode-readability

Using parameters vs global variables -- Code readability / maintainability


I'm trying to understand the sweet spot between readability vs repeating myself in my code.

I'm creating Conway's game of life in Javascript. My functions use many of the same variables over and over again like so...

const BOARD_HEIGHT = 50
const BOARD_WIDTH = 50
let gameBoard = createGameBoard();

function createGameBoard(width, height){}
function randomizeGameBoard(gameBoard, width, height){}
function updateGameBoard(gameBoard, width, height){}
function runGameLoop(gameBoard, width, height){}

Should I declare functions like this? Where all functions take in the exact same parameters OR should my functions NOT take parameters and instead access commonly used variables directly (globals)?

function createGameBoard() {do stuff with BOARD_WIDTH, BOARD_HEIGHT};
function randomizeGameBoard() {do stuff with gameBoard};

Solution

  • Neither global variables nor passing around variables are the way to go here (IMO). If you look closely, width and height are actually properties of the gameBoard ... and all those functions could actually be methods of a class:

      class GameBoard {
        constructor(width, height) {
          this.width = width; this.height = height;
          //...
        }
    
        randomize() { /*...*/ }
        update() { /*...*/ }
      }
    
      const board = new GameBoard();
    

    If there is just one board, then an object is enough:

      const board = {
        width: 50, height: 50,
        randomize() { /*...*/ },
        update() { /*...*/ },
      };