HiveBrain v1.2.0
Get Started
← Back to all entries
patternphpMinor

Avoiding globals in gumball machine class

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
gumballclassglobalsmachineavoiding

Problem

I'm planning to transition from years of forced procedural programming to OOP. I decided I'd start off small with a little gumball machine object to get my bearings. Everything seems to run ok, but I feel strange having all these globals in my class.

Code in action here.

Two questions:

-
Is there a way to avoid globals in my code?

-
Are there any glaring issues with the way I've used OOP to put this gumball machine together?

```
maxGumballs / $this->numColors));
$blueGumballs = rand(1,$this->maxGumballs/$this->numColors);
$whiteGumballs = rand(1,$this->maxGumballs/$this->numColors);
$greenGumballs = rand(1,$this->maxGumballs/$this->numColors);
$yellowGumballs = rand(1,$this->maxGumballs/$this->numColors);
$totalGumballs = $redGumballs+$blueGumballs+$whiteGumballs+$greenGumballs+$yellowGumballs;
$iTotalGumballs = $totalGumballs;
echo 'You walk up to a gumball machine.';
}

public function estimateTotalGumballs() {
global $totalGumballs;
echo 'You glance at the gumball machine and guess it is about '. round(($totalGumballs/$this->maxGumballs 100+5/2)/5)5 .'% full. You know the gumball machine can hold about '.$this->maxGumballs.' gumballs total.';
}

public function estimateTotalColorGumballs($color) {
$color = strtolower($color);
switch ($color) {
case 'red':
global $redGumballs;
$colorGumballs = $redGumballs;
break;
case 'blue':
global $blueGumballs;
$colorGumballs = $blueGumballs;
break;
case 'white':
global $whiteGumballs;
$colorGumballs = $whiteGumballs;
break;
case 'green':
global $greenGumballs;
$colorGumballs = $greenGumballs;
break;

Solution

First of all, all your gumballs counters have no good reason to be global. As they are part of the state of the gumball machine, why don't you make the counters instance variables?

Also, there might be a much more concise way to handle this counters : instead of having multiple variables, you could use a associate array to map colors to the corresponding number of gumball. As a cool side-effect, you don't need to maintain a variable containing the total number of gumballs : just use sum and you'll be allright.

Context

StackExchange Code Review Q#47199, answer score: 5

Revisions (0)

No revisions yet.