I have a large file of functions. Each of these functions is responsible for drawing a particular part of the application. My app has x and y parameters that I use in the setup function to move the whole app around in order to try different placements. So, naturally, I need to use these x and y values to anchor each function’s component rendering so that everything moves in unison if the global x,y values ever change.
My question is, is it bad practice/architecture to have these x,y values in the global namespace and having the each function directly access them like so?
function renderFace() {
var x = App.x;
var y = App.y;
// drawing here
}
is there a better way i’m missing?
…is it bad practice/architecture to have these x,y values in the global namespace… like so?
In your code, your x
and y
aren’t in the global namespace; they’re properties of App
. That’s a good start: you’re using App.x
instead of window.x
.
That said, App
and renderFace
are coupled: you can’t apply the functional behavior of renderFace
to anything but the values of App.x
/y
. If you want to reduce coupling to make renderFace
more general, it might be better to have renderFace
accept x
and y
as arguments:
function renderFace(x, y) {
// drawing here
}
and have some invoking code call renderFace(App.x, App.y)
instead of just renderFace()
.
Alternatively, make your render functions actual methods of App
and refer to the properties using this
.
var App = {
x: 0,
y: 0,
renderFace: function() {
var x = this.x;
var y = this.y;
// drawing here
}
}
By having App
“own” renderFace
as a method, it indicates logically that renderFace
is a behavior of App
.
When someone reading your code sees renderFace()
, they might not know it depends on the state of App
. When they see App.renderFace()
or renderFace(App.x, App.y)
the relationship is explicitly clear. Furthermore, by moving the identifer App
out of your function, it’s easy to re-use renderFace
in other non-App
contexts later.