I build a game that includes moving between worlds. The main class of the program suppose to start by presenting the first world (world1 which is an instance of the firstWorldClass). It should stay in this world until a variable within the class world1 is changing (checked by world1.getMoveWorldIndicator()). Then, it should move to the next world- remove world1, build world2 and add it to the graphic view. Same from world 2 to 3.
It works fine when I do it between 2 worlds (delete all the code after add(world2)) or if I leave only the transition between the second and the third worlds. When I put both in a row it stops working (when adding the second while loop).
My code:
public class GameManager extends Program implements GameContstants{
public void init() {
world1=new firstWorldClass();
add(world1);
while(!world1.getMoveWorldIndicator()){
pause(200);
if(world1.getMoveWorldIndicator())break;
}
remove(world1);
world1=null;
world2=new secondWorldClass();
add(world2);
pause(200);
while(! world2.getMoveWorldIndicator()){
pause(200);
if(world2.getMoveWorldIndicator()) break;
}
remove(world2);
world2=null;
world3=new thirdWorldClass();
add(world3);
}
private firstWorldClass world1;
private secondWorldClass world2;
private thirdWorldClass world3;
}
I suspect that there's some kind of interaction between the while loops or a memory problem but am open to hear any idea/different way to do it.
Thanks!
I think there are lots of factors coming into play here:
Clean up your code. Keeping a few coding rules is important for bug fixing!
Don't use repetitive code over and over again. Extract to method or Class
Keep to class naming conventions => Upper camel case for classes
Don't set variables to null. Usually compilers will do that for you while optimizing. If you still feel like manually freeing up space or variable names, you should use scope brackets {} around the code instead!
Breaking down your code, we see lots of redundancies, like "getMoveWorldIndicator()" checks twice per loop, without any different effect from using it only once
I have provided a cleaner - but different - version here, to show you.
But for actually helping you with your code, we really DO NEED more of your code to gain some insight to the problem.
public class GameManager /* extends ... */{
static class WorldBase {
public boolean getMoveWorldIndicator() {
return false;
}
}
static class FirstWorld extends WorldBase {}
static class SecondWorld extends WorldBase {}
static class ThirdWorld extends WorldBase {}
public void init() {
playWorld(new FirstWorld());
playWorld(new SecondWorld());
playWorld(new ThirdWorld());
}
private void playWorld(final WorldBase pWorld) {
add(pWorld);
while (!pWorld.getMoveWorldIndicator()) {
pause(200);
}
remove(pWorld);
}
private void remove(final WorldBase pWorld1) {}
private void pause(final int pI) {}
private void add(final WorldBase pWorld1) {}
}
Related
I decided to split the last part of that question here into a new question here: https://softwareengineering.stackexchange.com/questions/411738/extension-of-classes-where-to-put-behaviour-how-much-direct-access-is-allowe
If i have a lib and i want to use it, i wrote mostly a own class. This class has one method. In that there is the code how to instantiate the lib/framework. Sometimes there are a few more methods, with them i not only instantiate the class but use it. For example if i want to start a http-server i have there a start-method.
class Container
{
TheLib theLib;
public void init() //or a constructor
{
//some init of the theLib
}
public void start() //
{
theLib.doSomething(...)
theLib.doSomethingmore(...);
theLib.start(...);
}
//important!
public TheLib getTheLib()
{
return this.theLib; //after i started configured it and so on, i want of course use all methods,
which the lib have in some other parts in my application
}
}
But it seems not to be the best solution.
Are there any better solutions, that OO is?
Often i also use only one method, a own class for this seems to be here a big overhead?
Exposing the lib breaks encapsulation? Tell-Dont-Ask is also violated?
Everything depend on what you actually need or how you have access to your 'the lib' instance.
public class Container {
private TheLib theLib;
/* #1: Do you already created the instance before? */
public Container(TheLib theLib) {
this.theLib = theLib;
}
/* #2: Do you need to created the instance each time? */
public Container() {
this.theLib = new TheLib();
}
public void start() {
theLib.doSomething(...)
theLib.doSomethingmore(...);
theLib.start(...);
}
public TheLib getTheLib() {
return this.theLib;
}
public static void main(String[] args) {
/* #1 */
TheLib theLib = ...;
Container container = new Container(theLib);
/* #2 */
Container container = new Container();
/* Continue the flow of your program */
container.start();
container.getTheLib().doSomethingEvenMore();
}
}
Or maybe you actually need only one instance of your 'Container' class. In this case, you should look on how to make a singleton: Java Singleton and Synchronization
Anwser: Often i also use only one method, a own class for this seems to be here a big overhead?
Well, in Java, you cannot do formal programming like in C, so everything line of code that you write, or will be using, has to be in a class of some sort.
If your piece of code is small and don't really need an object, static function might do the work.
So I'm learning JavaFX programming and MVC. The control is also its own class and isn't integrated into the view (Which I've heard is one way to go at it). I want it to be separated from the view but because I'm trying to encapsulate everything and leave everything private with limited access to the controls/nodes, I find myself using methods to do almost anything inside of my object almost entirely when using event handlers in the control.
Example (Not an actual program, just wrote it here because I have no short examples.):
View:
public class SamplePane extends BorderPane {
private TextField tfScoreOne;
private Button btnScore, btnPenalty;
private int scoreOne;
public SamplePane() {
// Some constructor
}
public void giveScore() {
scoreOne++;
tfScoreOne.textProperty().setValue("Score: " + Integer.toString(scoreOne);
}
public void takeScore() {
scoreOne--;
tfScoreOne.textProperty().setValue("Score: " + Integer.toString(scoreOne);
}
}
public void btnScoreAddHandler(EventHandler<ActionEvent> handler) {
btnOneAdd.setOnAction(handler);
}
public void btnPenaltyAddHandler(EventHandler<ActionEvent> handler) {
btnOneAdd.setOnAction(handler);
}
Control:
public class SampleController {
public ModuleSelectionController() {
// Some contorller stuff again
samplePaneObj.btnScoreAddHandler(btnScoreHandler);
samplePaneObj.btnPenaltyAddHandler(btnScoreHandler);
}
private class btnScoreHandler implements EventHandler<ActionEvent> {
public void handle(ActionEvent arg0) {
samplePaneObj.giveScore();
}
}
private class btnPenaltyHandler implements EventHandler<ActionEvent> {
public void handle(ActionEvent arg0) {
samplePaneObj.takeScore();
}
}
}
This is mostly pseudocode so forgive me if there are any errors but do you get the point? It seems very arbitrary to just be calling methods but without passing the TextField in the example its hard to not do everything without a method doing all the work.
But is that decoupled enough for MVC? I don't really wanna break encapsulation is the main issue so I can't make the controls public and operate on them directly in the controller.
Is this all just normal? I want to make sure I'm grasping it right.
There is too much that could be said about this here. I'd advise you to have a look at a JavaFX application framework and read its documentation. I learned a lot from it. E.g., have a look here: https://github.com/sialcasa/mvvmFX
Don't make the mistake and try to derive some implementation patterns yourself from all the hello world examples out there on the internet. They all don't teach you how things should be done so that they scale well for real-world projects.
I'm searching for a concept to forward an object to subobjects.
Example:
I would like to create log files for several main Objects, that include sub objects (imagine a REST server that would log every single connection by ID).
Creating one big log file is simple ( redirect System.out.println, I already encapsulated that)
Example code:
class SubElementA{
public SubElementA(){
Debugger.debug("I am called, too");
}
}
Application.java
package com.dev4ag;
class Application{
private ElementA elA;
private String prefix;
public Application(String name){
this.elA = new ElementA();
this.prefix = name;
}
public void countUp(){
Debugger.debug(this.prefix+": I will now count up");
this.elA.doSomeStuff();
}
}
ElementA.java
package com.dev4ag;
class ElementA{
private int counter;
private SubElementA subElementA;
public void doSomeStuff(){
counter++;
Debugger.debug("Counter is: "+counter);
}
//Constructor
public ElementA(){
subElementA = new SubElementA();
this.counter = 0;
};
}
SubElementA.java
package com.dev4ag;
class SubElementA{
public SubElementA(){
Debugger.debug("I am called, too");
}
}
Debugger.java
package com.dev4ag;
public class Debugger {
public static void debug(String output){
//Just imagine we would write to a file here ;)
System.out.println(output);
}
}
(it was more easy to write system.out.println than to create a file, just imagine, Debugger.debug would write to a file).
Now I am thinking about a solution to create one Debug output target for each App. I could definitely change debug to not being static and create a debug object within Application.
But is there any way to use this object in the sub classes without forwarding the debug object either through Constructor or setter function, which would mean to have to add an object for the debugger to each class?
What would be the most beautiful solution for that?
Note that this solution might decrease performance a lot and it is pretty dirty way, but some loggers include such data.
But you can use Thread.currentThread().getStackTrace() to get stacktrace like in error and get class and method from where your method was called.
If you are using java9+ then you should probably use StackWalker API instead, especially that it have nice filters and other useful features.
So then you could guess app by class/method names on the stack.
I have a Java assignment in which my professor requires me to use a LeJOS NXT to make a robot that simulates a certain animal's behaviors. I chose to develop a dragon. All the possible behaviors that I've come up so far is:
Turning around if it's too close to an obstacle.
Going to sleep when battery is low.
Pushing an object if touches.
If it's too bright, find a dark spot.
etc.
I'm now quite confused because I don't know whether to develop it sequentially in one class or to split all the dragon's behaviors into different classes. Please have a look at my explanation below.
Instead of writing everything inside one class like this:
Dragon.java
public class Dragon {
LightSensor ls = new LightSensor
public static main(String args[]) {
while (!BUTTON.Escape.IsPressed()) {
if (this.closeToObject()) {
this.turnAround();
}
// more conditions
}
}
private boolean closeToObject() {
//TODO
return false;
}
private void turnAround() {
//TODO
}
//... more methods
}
However, I want to make it appears to be more object-oriented as the course is meant to help us gain more OOP skills. So what my second option is to create action classes that extends Dragon's Behavior abstract class like this (roughly):
Dragon.java
public class Dragon {
Detect detect = new Detect(); // carry all the detection methods: distance, sound, etc.
TurnAround turnAround = new TurnAround();
public static main(String args[]) {
while (!BUTTON.Escape.IsPressed()) {
if (detect.tooCloseToObject()) {
turnAround.prepare(); // beep beep alert
turnAround.setDerection(true); // e.g. turn right
turnAround.turn();
}
}
}
}
DragonBehaviors.java
abstract class DragonBehavior {
abstract void prepare();
public void setDirection(boolean direction) {
//...
}
}
TurnAround.java
public class TurnAround extends DragonBehaviors {
String direction;
public void TurnAround() {}
public void prepare() {
// sound alert
}
public void setDirection(boolean direction) {
if (direction) this.direction = "Right";
else this.direction = "Left";
}
public void turn() {
// TODO
}
}
The code above is roughly a draft, don't focus on it. Eventually, I want to ask if my idea about the OO structure above is reasonable, otherwise it's much easier to develop the whole thing in one class, but it has nothing to do with OOP. I also have several group members to make the code finished, so I think it could be better if we share the classes to develop in an OOP way.
Which way should I go in this circumstance?
I appreciate all the comments (:
Your choice of extracting different actions into classes with common super class is IMHO reasonable. However I would make Dragon class only aware of the DragonBehavior abstract class, not the subclasses. This way you can add and remove behaviours to the dragon without actually changing it.
How? Look at Chain-of-responsibility pattern - each behaviour has its place in the chain. If behaviour decides to activate itself (i.e. perform something) it may or may not allow further behaviours to be triggered. Moreover, you can and remove behaviours (even at runtime!) and rearrange them to change the precedence (is pushing the obstacle more or less important than going to sleep?).
I have a public class which has the following method and instance variable:
public void setImagePanel(JPanel value) {
imagePanel = value;
if (imagePanel != null) {
//method 1 : works
imagePanel.addComponentListener(new ComponentAdapter() {
public void componentResized(ComponentEvent evt) {
System.out.println("Here 1");
}
});
//method 2 : does not work
panelResizeListener = new ResizeListener();
imagePanel.addComponentListener(panelResizeListener);
//method 3 : works
//ResizeListener listener = new ResizeListener();
//imagePanel.addComponentListener(listener);
//method 4 : works
//imagePanel.addComponentListener(new ResizeListener());
//method 5 : does not work -- THIS IS THE DESIRED CODE I WANT TO USE
imagePanel.addComponentListener(panelResizeListener);
}
}
public class ResizeListener extends ComponentAdapter {
#Override
public void componentResized(ComponentEvent evt) {
System.out.println("RESIZE 3");
}
}
private ResizeListener panelResizeListener = new ResizeListener();
private static JPanel imagePanel;
Each of the methods above correspond the to code immediately below until the next //method comment. What i don't understand is why i can't use the class instance variable and add that to the JPanel as a component listener.
What happens in the cases above where i say that the method does not work is that i don't get the "RESIZE 3" log messages. In all cases where i list that it works, then i get the "RESIZE 3" messages.
The outer class is public with no other modification except that it implements an interface that i created (which has no methods or variables in common with the methods and variables listed above).
If anyone can help me i would greatly appreciate it. This problem makes no sense to me, the code should be identical.
Man camickr, you were right. Man this was a weird one to solve. There was something else wrong with my code. The order of the methods calls into my class resulted in me adding the listener then another method would end up removing the listener referenced by that variable so of course i would never get events. Thanks a lot for all the help ppl.
I think your problem is that you're declaring panelResizeListener after you're using it. That normally kills just about anything.