Avoiding main class to be static. Opinions about this lousy hack

If you have code like this:


public void setBounds(Rectangle bounds) {
   this.bounds = bounds;
}

public Rectangle getBounds() {
   return bounds;
}

Then all you’ve done is add boilerplate code that does nothing.

If you’ve got code like this:


public void setBounds(Rectangle bounds) {
   this.bounds.set(bounds);
}

public Rectangle getBounds() {
   return new Rectangle(bounds);
}

Then fair enough, you’ve protected your internal state. You should always try to do this.

However you’ve exposed to the outside that the object has a bounds. The object oriented way would be to have methods on the object that uses the bounds instead of exposing it. So instead of:


public void mousePressed(MouseEvent e) {
    if (object.getBounds().contains(e.getPoint())) {
        object.activate();
    }
}

You could do:


public void mousePressed(MouseEvent e) {
    object.activateIfPointIsInside(e.getPoint());
}

Now in general, things are not black or white. You don’t always use one method over another. But knowing about different ways of doing things can help you write better code.

@tom, @sproingie, @ReBirth: I read Item 16 of Effective Java. This item example is clear on when composition is better than inheritance. It took me long but now I’m convinced that composition is a real alternative, thanks! :slight_smile:

Stupid, stupid me! You are so right that I feel ashamed! I translated from C++ without realizing it doesn’t work like this in Java.

That makes sense, but I’m not sure I know how to implement it in the design I have so far :_(

Ok, the thing I get from this discussion is I have to keep reading/learning to improve my code AND kevglass/Riven advice 1) make a game, 2) make it efficient enough so it is fast, and 3) make it pretty. I’ll try to advance in both paths in parallel!

Kev’s actual advice is “Make it quick enough.”
Or to put it another way, make it efficient enough so it is not slow.
A subtle but important difference. :wink:
Simon

In general I find that exposing the fields of objects makes my toes curl and hang my head in shame, and I’ve always tried to design systems such that no such access is required for classes of any reasonable abstraction beyond what amounts to a struct (eg. tuples and such).

But the longer I code games and need to get shit out of the door the more I find myself bodging them in to get something to work quickly. Game ships, money is made, the Perfect Code Angel quietly weeps and the Great Pile Of Money Daemon cackles.

Cas :slight_smile:

I’ve unleashed the power of the medal gatling to appreciate all your contributions.

http://www.robotmutant.com/wp-content/uploads/2011/07/hqdefault-1.jpg

Thanks for making this thread so helpful to me :slight_smile:

Yes yes! work first! ;D

GREATEST THING I HAVE EVER SEEN!!!