Using constants

I want to use constants in my projects, i.e. final values that never changes throughout the code, that can be accessed anywhere. What is the proper way of using constants in processing?

1 Like

Whenever we declare variables outside of any function or {} blocks, they become global variables.

We can also add keywords static & final if they’re truly immutable; or at least if they’re supposed to be kept unchanged during the execution of the program.

We should also follow the SCREAMING_SNAKE_CASE naming convention for them.

We can define global variables inside any “.pde” tab, and they become available on other “.pde” files within the same sketch.

Also, if we have too many global variables, we can group them inside enum, interface or class structures as static fields.

Those structures will function as container namespaces for those constants.

1 Like

Thanks for your reply.

When should I choose to make constants global, encapsulate them in a class structure, or use an enum class?

Contrary to global variables, which we should be more strict about it, we can pretty much abuse global constants, b/c they don’t keep state and have a permanent fixed value, which will always be the same during the execution of our code.

Here’s a sketch example using lotsa global constants:

If we have immutable values that are intimately related to a class or a group of classes, it makes total sense to define them as static final fields inside that class.

However, only primitive and string fields can be declared static inside an inner class.

As a workaround, we can define those constants inside an interface, and have the class or a group of related classes to implements that interface:

interface IPlayer {
  static final color OUTLINE = 0;
  static final float BOLD = 2;
  static final int MODE = CENTER;
  static final int UP = 0, DOWN = 1, LEFT = 2, RIGHT = 3;
}

class Player implements IPlayer {
  int x, y, d, v;
  color ink;
  byte[] keys;

  Player(int x, int y, int d, int v, color ink, byte[] keys) {
    this.x = x;
    this.y = y;
    this.d = d;
    this.v = v;
    this.ink = ink;
    this.keys = keys;
  }

  Player display() {
    fill(ink);
    ellipse(x, y, d, d);
    return this;
  }

  Player move() {
    final int
      r = d >> 1, 
      hor = keysDown[keys[RIGHT]] - keysDown[keys[LEFT]], 
      ver = keysDown[keys[DOWN]] - keysDown[keys[UP]];

    x = constrain(x + v*hor, r, width - r);
    y = constrain(y + v*ver, r, height - r);

    return this;
  }
}

An enum is a structure where its fields are themselves values.
It’s a very good choice when we need to represent different, but related states.
The enum name will become the namespace for its values.

As an example, we can group these 4 static final related fields from the previous code:
static final int UP = 0, DOWN = 1, LEFT = 2, RIGHT = 3;

Inside an enum structure:

static enum Direction {
  UP, DOWN, LEFT, RIGHT;
}
2 Likes