Game programming: passing main class to every object - java

I know it's not efficient, but I don't really know why.
Most of the time, when you implement your game you got a main class which has a loop and updates every frame and creates certain objects.
My question is why it's not considered efficient to pass the main class to every object in its constructor?
In my case, I developed my game in Java for Android, using LibGDX.
Thank you!

It increases coupling (how much objects depend on each other) and therefore reduces re-usability and has the tenancy to produce 'spaghetti code'. I don't really understand what you mean by not being 'efficient', but this is why you shouldn't do it.
You should also consider why you need that main class in every single object. If you really think you do, you might need to reconsider your system design. Would you mind elaborating on why you think you need it?

Mostly, it is a matter of coupling the code and making proper design decisions.
You should avoid dependencies between classes whenever possible. It makes the code easily maintainable and the whole design clearer.
Consider the case: you are creating a simulation racing game. You have a few classes for such entities: wheel, engine, gearshift knob, etc... and non-entities: level, player...
Let's say, you have some main point (i.e. GameEngine class where you create instances).
According to you're approach you want to pass GameEngine's instance in entities constructors (or related mutator methods). It's not the best idea.
You really want to allow wheels or breaks to have the knowledge about the rest of the world (such as player's informations, scores, level etc.) and give them access to it's public interface methods?
All classes should have at small level of responsibility (and knowledge about other items) as possible.
If you really need reference to some kind of main point object in you're classes consider using dependency injection tools, such as Dagger.
It won't make you're game design better, but, at least, forces you to favor composition over inheritance - what leads to create better code.

It's not entirely inefficient, since (afiak in the general case) passing a reference to a method is quite cheap when you consider the number of JVM opcodes required, however, a possibly more efficient way of doing this would be to make a static instance of the game class and access that static field from the other classes. You would have to test these two options yourself.
In addition, passing a reference to the methods could make maintaining the code harder, as you have ultimately added a dependency.

Related

Extending class just for the sake of using it's methods and attributes

In many examples regarding Java extends found online, classes were used that have a certain "logical connection". For example, a banana extends a fruit, a Student extends a Person etc.
Is it good practice to extend a class with another class just to inherit the methods and attributes, even though both classes don't show a "connection" like in the example above?
For example, a class UserManagementService extends a class DatabaseConnectionService so that UserManagementService can simply connect to the database by calling the method connect() instead of instantiating DatabaseConnectionService and calling databaseConnectionService.connect().
Yes, this is obviously bad; that's because your type hierarchy is neccessarily public API. If your API exposes a UserManagementService, I can use it as a DatabaseConnectionService object. That means that your choice to have UMS extend DCS is locked in - if you ever change that, any code that uses your UMS may then fail. You can try to solve this in documentation:
/**
* Lets you query information about, and perform operations on,
* the storage of users allowed on this service.
*
* IMPORTANT NOTE: Even though this class extends DatabaseConnectionService,
* this is <em>not guaranteed</em> by this implementation,
* so do not rely on this!
*/
public class UserManagementService extends DatabaseConnectionService {
...
}
But surely you can see that this is pretty suboptimal and 'ugly' (hard to maintain - you can't test that other code you have no control over actually heeds your warning here).
It also applies in reverse: If ever DCS adds something that just makes no sense for a UMS to have, then your UMS is, all of a sudden, broken and exposes crazy stuff that makes no sense and causes many questions or worse.
Contrast this to declaring that a Student is some kind of Person: That's inherently true; that is not merely a convenient implementation detail. If the country at large gains some sort of servicenumber feature and you extend the Person class to support this, then Students all of a sudden also gain this servicenumber thing. But that's good: Students ARE persons, after all.
So, how do you fix it?
Easy. Don't extend DCS. Create a field of type DCS, and if there are a bunch of methods that DCS has that you want UMS to also have, write em out. Their implementations can be very simple oneliners:
public int count() {
return dataConService.count();
}
// and a lot more of this, if really needed.
Common retort to this logic: But I control it all and I don't foresee new features ever being added!
Well, okay, but understand that single-person throwaway projects are a very bad basis to talk 'style guides and code cleanliness' - it's just you, hacking away for a weekend, write it however you like, you'll be fine.
Style guides and approaches to coding become useful when a team of 50 programmers program an application that is to survive and be in the business for over a decade, with programmers leaving and new programmers joining the team, and 5 years after the project is started, features you didn't even think of yet need to be added because of customer demand.
With that in mind, understand that code bases become gigantic and it'll be very hard to safely change things and train new programmers to become familiar with it. One extremely useful way to make that a little easier is to aggressively modularize things: Anytime you can draw the entire sourcecode base on a whiteboard (which will be huge), but then draw a smallish circle around a tiny part of it and go: This stuff can be understood all by itself, tested by itself, and developed on without completely understanding all the other source code - that's good. That's what you want.
"UMS currently extends DCS but don't rely on that" is exactly the kind of thing that makes drawing that tiny circle more complicated, which is why it's not a good idea to do it.

encapsulation means putting related items together?

I was going through an article about Object Oriented Programming and it stated that encapsulation means putting related items together, but I don't understand how the article's representative example: UserProfile.js. Though this example is in JavaScript, I'm looking to understand these concepts in Java.
Can anyone explain me these two questions with a pseudo code:
What is encapsulation?
Why do we need encapsulation with pseudo code?
Encapsulation isn't necessarily about putting related items together, it's a technique of hiding internal information of an object. I'm not sure if I agree with the premise of the author of the article you linked... I don't accept that a struct is really a method of encapsulation in the object-oriented sense of the word.
Encapsulation
Psudo [sic] code is a technique for explicitly writing coding logic without the need for syntactical constraints. Considering this context, I don't understand your second question.
Pseudocode
No, that is cohesion.
Encapsulation is hidding things from who doesn't need them.
Michael has it correct.
In Object Oriented programming Encapsulation is the first
pace. Encapsulation is the procedure of covering up of data and
functions into a single unit (called class). An encapsulated object is
often called an abstract data type.
ref: http://www.c-sharpcorner.com/UploadFile/ggaganesh/EncapsulationInCS11082005064310AM/EncapsulationInCS.aspx
Encapsulation is the hiding of the non-essential features.
So why do we need it.
Programing is about translating a solution to a problem into logical code to solve that problem. Because of this, there maybe many complicated methods and functions that we don't want Mr.Joe Blow developer to use. We will encapsulate (or BlackBox) those methods so they cannot be used (they are still used internally). This reduces complexity by only representing important functions and hiding others.
As for needing it in pseudo code, i'm not sure. Michael did a good job with explaining that.
I haven't had enough coffee to give a good example,Plus my Rubik's cube broke :(, i'll write one up for you.
The encapsulation stand for "hiding element for free usage", is a part of Object Oriented Programming paradigm.
It is used to specify the range of visibility elements of code.
Let assume that we have a class with field called password where the password is stored. If this password would be visible for everyone, then there would be no need for a password.
Additional thing is that this helps to maintain the code in order.
Encapsulation isn't goal in OODesign. It is only way to achieve the finest, needed abstraction.
What is encapsulation?
in specific - it means hiding properties from non-desirable access
in overall - it means hiding every project design decision which could be changed in future. Therefore in encapsulation we should consider also e.g. concrete method implementation. From this POV we encapsulate its behavior so that for some POV we don't want to know how it is doing it, knowing only what this method is doing. Encapsulation could be achieved also for example using inheritance mechanism!
How we use encapsulation/
Example - hide every class property. You could as why do we have to do so - it is much effort and unnecessary code! Consider simple example where you can set some int properties. In your scenario - this variable should be in specific range. If someone sets it wrong - how would you design workflow to prevent this action?
More sophisticated but still simple example are collections. In many cases we shouldn't provide full collections to your's object neighbourhood. Encapsulation allows you to provide every property client just a copy of your object. In some cases - it could be helpful.
I think to really understand and appreciate encapsulation you really need a little bit of history.
It used to be that if you wrote a program it would be kind of as though every line of code were printed on a single sheet of paper where everything has knowledge and access to everything else and there are no fancy constructs in which to hide or store variables out of site of your functions.
Lets say you are trying to write some program with 100 different functions and 100 variables. Can you imagine how disorganized and ugly that would get? Effectively, all that code is just a giant formless script that gets executed in some linear fashion and has no real structure, rhyme or reason to it other than that one line of code comes before another line of code and so on.
Encapsulation was invented to take a program like that and give it a skeletal structure, allowing you to hide and organize those 100 functions and variables into a sensible whole. In the case of your user info class here, they take everything that is relating to UserProfile and stick it in a "Capsule" so that it can only be accessed through a reference to to UserProfile. It might look like overkill in this context, but if you have a much larger program, you will be extremely happy to be able to do this.
Its a fancy word for something that is extremely obvious once you understand where the people who created these terms were coming from.
I think encapsulation is closely related to information hiding and abstraction. It is simply the practice of hiding implementation details and object internals from the outside world. It helps both with clarity as well as reducing coupling.
The capabilities of a class are declared in the interface of methods it defines, not in the detail of how they are implemented. Good encapsulation ensures the public interface is sufficient for callers to use without revealing internal implementation details. A well encapsulated design reduces coupling, as the internals can be replaced without affecting everything else that uses that class (through its interface).

How to make a design "loose coupling"?

I'm making a simple 3D CAD software. in the class diagram, many objects need to distinguish with others by (x,y,z). I create a class so-called "Position", but the problem is it looks highly-coupling because many classese work with position.
Any ideas?
It is not a problem per se if a type is used by many other types. In your case, graphical objects obviously (usually) have a position so the coupling looks natural and reasonable from the perspective of the domain model.
Also, the Position class is probably going to be a fairly low-level class whose interface (and probably implementation too) is not going to change very often in the long run. So there is not much chance of such changes breaking client code.
First let me say after 12 years that your design is not bad. Assuming that the positioning logic of your classes shall be called from outside, all your classes need to have and offer this logic. So it is part of the interface and you must bring the functionalities in. And this means, you must depend on it and there is a coupling. The coupling is not between your objects. So it is not as bad.
But there are always alternatives. It is known that inheritance establishes a very tight coupling. Consider for example that the positioning logic is only called internally in your class. Then you don't have any benefit in inheritance. You could as well have another class (let us call it Position). And instead of deriving from this class, you integrate an object of this class. And whenever you want to do something with the position, you call the corresponding methods of this object.
This alternative looks like a nonsense change. Why should you do this? But let us have a look at the consequences. Assume you have a class Circle. Circle has such a position object as proposed above. (By the way, see the wording "has a position" instead of "is a position". The "object-and-composition" solution seems to be quite natural.) Somewhere in a file X of your code you may have created such a Circle. And now you decide you change the positioning logic. In X you don't have to worry that this has a side effect, because the interface of Circle has not changed. It is just one object inside of Circle that has changed. That is just an implementation detail. In contrast if you would have used inheritance, you cannot just change the base class without looking if this has a negative effect to X. So this "object-and-composition" solution has actually reduced the coupling between X and the positioning logic.
You can even reduce the coupling further. With the object-and-composition solution, whenever you change the positioning logic, you have to check all your classes if this has an effect. But what about using an interface for Position. Your classes don't see an object of a type Position, but an object that fullfils an interface Position. And the actual positioning logic implements this interface. This way most of your classes' code has no dependency to the implementation of the positioning logic.
That is not the end of the game. There is still a coupling, because your classes must somehow create the position objects. So at least the constructor must go into detail and for example pass x,y,z. But what if you use something like a factory for this purpose, so that your objects just get the position without even knowing how these have been created. Then you are absolutely flexible. You can use your classes in completely different situations. For example in a two dimensional coordinate system. There is no coupling between your positioning logic and your classes any more.
I hope you see that all these options exist. I suppose in your example this is a bit over-engineered. But your question was how to reduce the coupling. And there are always ways. Combinations are of course possible. For example you can have the object-and-composition and make the position object public in your base class. But then I would ask if not inheritance would have been the better option?

OO vs Simplicity when it comes to user interaction

As a project over summer while I have some downtime from Uni I am going to build a monopoly game. This question is more about the general idea of the problem however, rather than the specific task I'm trying to carry out.
I decided to build this with a bottom up approach, creating just movement around a forty space board and then moving on to interaction with spaces. I realised that I was quite unsure of the best way of proceeding with this and I am torn between two design ideas:
Giving every space its own object, all sub-classes of a Space object so the interaction can be defined by the space object itself. I could do this by implementing different land() methods for each type of space.
Only giving the Properties and Utilities (as each property has unique features) objects and creating methods for dealing with the buying/renting etc in the main class of the program (or Board as I'm calling it). Spaces like go and super tax could be implemented by a small set of conditionals checking to see if player is on a special space.
Option 1 is obviously the OO (and I feel the correct) way of doing things but I'd like to only have to handle user interaction from the programs main class. In other words, I don't want the space objects to be interacting with the player.
Why? Errr. A lot of the coding I've done thus far has had this simplicity but I'm not sure if this is a pipe dream or not for larger projects. Should I really be handling user interaction in an entirely separate class?
As you can see I am quite confused about this situation. Is there some way round this? And, does anyone have any advice on practical OO design that could help in general?
EDIT: Just like to note that I feel I lost a little focus on this question. I am interested in the general methodology of combining OO and any external action(command line, networking, GUI, file management etc) really.
In the end, it is up to you. That is the beauty of OO, in that it is subject to interpretation. There are some patterns that should usually be adhered to, but in general it is your decision how to approach it.
However, you should carefully consider what each actor in the system should know about the rest of it. Should a property really know about the player, his account balance, and the other players? Probably not. A property should know what it costs, how much its rent is, etc.
On the other hand, should the main playing thread be concerned about trivial matters such as paying rent? Probably not. Its main concern should be the state of the game itself, such as dice rolling, whether each player wants to trade or buy or unmortgage/mortgage, things like that.
Think for a moment about the action of landing on a square. Once landed, the player has 3 options:
Buy the property
Ignore the property
Pay rent
Now, which actor in the system knows all the information required to complete that. We have the Game class, which isn't concerned with such tedium. We have the Property, which doesn't really care about the players. But the Player object knows all this information. It keeps a record of what each player owns, and can easily access the proper data.
So, if it were me, I would make a Player.performMove(Die d) method. It has easy access to the accounts. This also allows for the least coupling among classes.
But in the end, it's up to you. I'm sure people have created Monopoly clones in perfect OO, as well as Functional or Procedural languages too. In the end, use what you know and keep refactoring until you're happy with the end design.
I agree option #1 seems better.
As for "user interaction" - it all depends. You could leave some of your code in another class. For example,
// in main class
user.landOn(space);
if (space.containsProperties()) doSomething(); // Option #1 for some user-interaction code
// in User.java
public void landOn(Space s) {
// do some checks
s.land(this);
if (s.containsProperties()) {...} // Option #2
// something else?
}
// in GetMoneySpace.java
#Override
public void land(User u) {
u.awardCash(200);
// Option #3 - no properties so nothing here
}
This is far more OOP-y (and better, in my opinion) than something like
if (space.isCashAwardSpace()) {
user.awardCash(space.getAward());
}
if (user.something()) doSomething(); // Some user-interaction code
I am not entirely sure if I understand it correctly. You have always such choice when designing software. I would personally go for the first choice. One argument is personal experience with small games (Scrabble), which prooved to me that good design matters for smaller projects as well. The point of OOP is that you can think differently about your design and you get some design benefits. For example imagine how hard it will be to add new field, change existing one, reuse behaviour of one field in multiple fields.
Your first approach is the one I'd go for. It encapsulates the behaviour where it's needed. So, you'd have Space subclasses for Utilities, Properties, GotoJail, FreeParking - basically all the different cateogires of spaces. What groups a category is it's common behaviour.
Your properties spaces may themselves have a group object as a member, e.g. to group all the dark blue properties together.
As to interaction with the user, you pass a Board (or better a GameController) instance to each space, so it knows which Game it is part of and can influence the game. The Space can then invoke specific actions on the board, such as, moving a piece, asking the user a question etc. The main point is that there is separation - the user interaction is not happening inside each Space - but the space is allowed to request that some interaction happens, or that a piece is moved. It's up to your GameController to actually do the interaction or move pieces etc. This separation makes it easy to test, and also provide alternative implementations as the need may arise (E.g. different game rules in different editions/countries?)
Go with the first design. You'd have a Property class, and subclass the special properties, overriding the default behavior.
As far as interaction, you could have a Token class, and move an instance of that around the board. You have to give the user some options, but yes, from the responses, you should be calling methods on objects, not putting complex logic in the user events.
Sample classes:
Property
name
price
baseRent
houseCount
hotelCount
mortgaged
getCurrentRent()
RailRoad extends Property
Utility extends Property
Board
properties
User
token
playerName
currentProperty
ownedProperties
buyProperty()
payRentOnProperty()
mortgageProperty()
move()
Option 2 doesn't make much sense, or at least it's not as clear to me as option 1. With option 1 you don't need to handle user interaction inside your space object. You could have in your main class or a separate class dedicated to handle user interaction:
public void move(Player p, int spaces){
Space landingSpace = board.getLandingSpace(p,spaces);
landingSpace.land(p); //apply your logic here
}
As you can see, the Space class is responsible for checking the Player p that intends to land on that space. It applies any custom logic, checks if it has enough money, if it's something that the player owns, etc. Each subclass of Space will have its own set of rules, as you described in option 1.
Part of the point of object-oriented design is to simplify the representation of the problem within the solution space (i.e., modeling the system in the computer). In this case, consider the relationships between objects. Is there enough functionality in a Space to warrant abstracting that into a class, or does it make more sense for there to be discrete Property and Utility classes unrelated to Space because of the unique features of both? Is a Property a special kind of Space, or merely a field within Space? These are the kinds of problems you probably will need to grapple with in designing the game.
As far as interaction, it's generally bad news for a design when you have a 'god class' that does all the work and merely asks the other classes for information. There are plenty of ways to fall into this trap; one way to determine whether you are dealing with a god class is to look for a class name including Manager or System. Thus, it's probably not the best idea to have some sort of "game manager" that asks all the other objects for data, makes all the changes, and keeps track of everything. Eliminate these as much as possible.
God classes violate the concept of encapsulation, which involves more than data hiding (though that's certainly a big part of it). Good encapsulation means that related methods and data are part of a single object. For example, a Property doesn't need to make requests of its owner, so a field containing a reference to the Player could violate encapsulation. Some of these encapsulation violations aren't obvious at all, and can be hard to spot. When designing the object, try to determine the smallest amount of information about the object that needs to be shared with external objects. Trim out anything unnecessary.
You can obviously go about this in a lot of ways, but my design would be something like this (iteration could certainly prove it wrong):
Space class that contains basic data and methods that are common to all spaces (such as their position on the board, occupied or not, etc.).
Subclasses moving from most common (Property and Utility) to most unique (Go, Jail, FreeParking, and so on; probably singletons) with fields and methods related to each.
Player class to contain player information.
GameState class that is concerned with game state; whose turn it is, how many houses are left in the bank, and so on.
Good luck with the game and your continued studies.
Naturally, Google is your friend, but here's a sampling of things I would recommend reading:
ATM simulation (this idea is
also discussed in Rebecca
Wirfs-Brock's book below)
Object-Oriented Design Heuristics - Arthur Riel
How Designs Differ (PDF), Designing Object-Oriented Software - Rebecca Wirfs-Brock

Would a singleton GUI be good in this case?

I am working on a project where I have lots of classes referring to my GUI (mainly the panels but sometimes the frame itself). So I was thinking that instead of passing the frame as an argument to every constructor and create getters in each class, I would make a singleton instance of the JFrame so all the classes get access to it instead. Is this a good approach or will it just punish my laziness in some way?
Edit: I'm not just lazy, I'm trying to think in models here: For example, let's say I have various Car objects and the Road is my GUI. All Cars should have access to the same Road, and the Road is not a part of a car.
There is plenty of opinions in the area, see referenced material below.
My feeling is that we should try to avoid Singletons because "there's no such number as 1".
[This follows on from my theory that "there is no such number as 2". If you have code, that allows for two of something, and only two of something, then you've missed a trick - there's almost certain to be more than two, instead solve how to deal with "many".]
The "no such number as 1 argument" is that just when you thought there could only be one of something there will be some context in which it's possible to have more ... and it's usually very little extra work to allow for more.
Look at your example ... I have various Car objects, they all have access to the same Road? Does that sound like a model of a realistic world? UK Roads and French Roads, any difference? ;-) Why build that "Only One" assumption into your code?
Use of factories and dependency injection of those factories will often be the better answer. Lots more material in answers to this question.
The Singleton pattern is considered today to be an "anti-pattern". The problem will become apparent when your Cars will need to be used with a different Road one day.
It will become even more apparent if you decide to unit-test the Cars for themselves. If you can't provide a Mock for the Road, how will you test them? And you won't be able to, since they refer to their Road through a Singleton.
(Obviously there's a workaround by having the Singleton return a MockRoad when in "test-mode", but that just means you're adding testing code into your production code.)
A better approach would be to hide the main JFrame behind static methods, but in general it is a good idea if you have only one JFrame object for the whole program to make it static anyway.
Hiding it behind static methods ensures that if you work on this with anyone else you can constrain what you want them to be able to access on the main JFrame, but would be useless for something like a school project etc.

Categories