Creating Annotations in Java like Mockito's before - java

In processing I have several functions that change the properties of applet to draw stuff, for instance:
public void resetBackground(PApplet pApplet){
pApplet.fill(175);
pApplet.noStroke();
pApplet.rect(0,0,100,100);
}
But I want these functions to preserve the state of the pApplet after the function call, for that I have something like:
public void resetBackground(PApplet pApplet){
SaveAndRestoreDefaults saveAndRestoreDefaults = new SaveAndRestoreDefaults(pApplet);
// Code that changes state.
saveAndRestoreDefaults.restoreOriginals();
}
Now this works for me but I would like this not to clutter my code here but rather be annotation driven, something like:
#PreserveState
public void resetBackground(){
// code that changes state.
}
I have done a little research on it but it seems to be not an easy task. The googling took me to AOP and I don't want to spend time to learn that. Is there an easier way to achieve the same?
Thanks :)

I'd strongly recommend staying in Processing, instead of reaching into the underlying virtual machine API (just because you run it in java, doesn't mean every implementation of Processing has a JVM. Processing.js comes to mind).
Just make a state class and keep track that way:
class SketchState {
color background_color, stroke_color, fill_color;
SketchState(color bg, color st, color fl) {
sketch = s; background_color = bg; stroke_color = st; fill_color = fl;
}
}
ArrayList<SketchState> stateCache = new ArrayList<SketchState>();
void cacheState() {
stateCache.add(new SketchState(...));
}
void restoreState() {
SketchState rest = stateCache.remove(stateCache.size()-1);
background(rest.background_color);
stroke(rest.stroke_color);
fill(rest.fill_color);
}
and add whatever other state aspects you want saved to that class.

Related

What is the (best)name or description of this "method linking" to other components

First off, sorry for the strange "title", but since I don't know the name, it's quite tough to describe in a short sentence.
I've been here many-many times before, however this is my first actual activity.
I usually search, read and fight my way trough what I want to know. However, I just can't seem to get to my answer this time, which I find pitty.
Lately I've read "Head First Design Patterns", which I can't recall it was covered in there. Also I've hit quite some Google terms in the box, but without the correct defenition. I just can't find the right combination of search-words to nail the answer.
I've got a question about the correct name of "forward sharing / linking"
of methods and their parameters.
I'm writing the JavaDocs comments to keep my code understandable, but I can't get the right term or Design Pattern name that fits to this.
But just asking this won't get me what I need i think. So I've got a little sample to demonstrate my question as BASIC as possible. I hope it is a bit understandable.
public class Framework()
{
private Game game = new Game();
public Framework()
{
loadComponents();
}
public void loadComponents()
{
// first loading framework requirements.. (lets say a button graphic)
game.load(); // lets start loading the game....
}
public static void main (String[] args)
{
new Framework();
}
}
public class Game()
{
private World world = new World();
public void load()
{
// now we load some of the basic graphics.. (lets say a few borders)
world.load(); // lets start loading the world!
}
}
public class World()
{
private Textures textures = new Textures();
public void load()
{
// now we load the worlds grid...
textures.load(); // ofcourse we need textures, lets load...
}
}
public class Textures()
{
public void load()
{
// loading the textures...
// end of this loading link.
}
}
In this example we started off in the Framework, called the load method in Game, then called the load method in World,
then called the load method in Textures. Lets make it a little simpler:
Framework.load()->Game.load()->World.load()->Texture.load();
But ofcourse we got more of these "links".
Framework.load()->Editor.load()->Entities.load();
Framework.input(Input input)->Game.input(Input input)->Player.input(Input input);
Framework.draw(Graphics2D g2d)->Game.draw(Graphics2D g2d)->World.draw(Graphics2D g2d);
How can I describe or call this "chaining/linking" the best? Becouse chaining in Java is like: Player.getLocation().setLocation(12,12).etc();
I hope my question is a little clear now,
thank you for your time in advance!
Edwin
I believe this is called the Delegator pattern

Method Generator in java

I am using Kmax to create a DAQ software. The philosophy of the GUI and the code is that every object on the GUI(radio buttons, check boxes, progress bars etc) has to have the same name with the relevant method. For instance an object named BUTTON is linked with the method public void BUTTON(KmaxWidget widget){code}.
My code is
import kmax.ext.*;
public class Runtime implements KmaxRuntime {
KmaxToolsheet tlsh; // Store a reference to the toolsheet environment
KmaxHist hist1D;
KmaxWidget checkBoxWidget;
public void init(KmaxToolsheet toolsheet) {
tlsh = toolsheet; // Save this reference for use in the toolsheet
hist1D = tlsh.getKmaxHist("HIST1D");
checkBoxWidget = tlsh.getKmaxWidget("CHECK_BOX_CALIB_METH");
tlsh.getKmaxWidget("CHECK_BOX_CALIB_METH").setProperty("VALUE", "1");
}
public static boolean stringToBool(String s) {
if (s.equals("1"))
return true;
if (s.equals("0"))
return false;
return true;
}
public void CalibInit(KmaxWidget widget, KmaxHist histo){
histo.setUseXAxisCalibration(stringToBool(widget.getProperty("VALUE")));
histo.update();
}
public void chooseCalib(){
checkBoxWidget = tlsh.getKmaxWidget("CHECK_BOX_CALIB_METH");
checkCalib(checkBoxWidget,hist1D);
}
public void GO(KmaxToolsheet toolsheet){}
public void SRQ(KmaxDevice device) {}
public void HALT(KmaxToolsheet toolsheet) {}
} // End of the Runtime object
In the above code I have the check box CHECK_BOX_CALIB_METH. The problem arises when someone wants to create many objects;one has to create many methods. In the above code you can see what I am trying to do. I want to create a "main" method that will do every function that is needed and then another method will apply those functions to each object.
This code compiles without any errors, but the check box isn't working. So I was thinking if there is a way around this. For instance a method that will include "submethods" that will do the job! Or perhaps a method that will construct methods in a for loop for each radio button, check box, progress bar etc. Something like
for(int i=0; i<number_of_buttons ; i++){public void BUTTON_i(){code}}
The above code may look ridiculous but I don't know what else to think and I really want to avoid having one method for each button.
Is something like that possible or is there another way around this?
EDIT
For instance I have 6 methods that do exactly the same;they just have different names.
public void SET_CALIB_1(KmaxWidget widget) {
double C0 = (getValueFrom("Ch2_1")*getValueFrom("En1_1")-getValueFrom("Ch1_1")*getValueFrom("En2_1"))/(getValueFrom("Ch2_1")-getValueFrom("Ch1_1"));
double C1 = (getValueFrom("En2_1")-getValueFrom("En1_1"))/(getValueFrom("Ch2_1")-getValueFrom("Ch1_1"));
double C2 = 0;
double[] coef = {C0, C1, C2};
hist1.setXCalibration(coef);
hist1.setUseXAxisCalibration(true);
hist1.update();
} // SET_CALIB_1
Is there a way to have a generator method to generate methods like the above?
what are the design goals for this software?
reflection may be a much better way to get access to the members; and/or put all the components into an array for access.
I find that I tend to over-engineer things a lot; since I enjoy building things; but then they get way too complicated and don't work.
so I advise to take a walk (or trudge through the snow) and think about it some more.

I'm new to java from a javascript background: how do they manage event listeners properly and not tighting classes together?

I've been trying to do some "simple thing" in java that in javascript would look like:
// Main class
var model = new Model();
this.callback = function(e){/* do something */}
model.addListener("change", callback);
Well in java what I found so far is making the Main class deriving from java.util.Observer and Model from java.util.Observable; Then when the model will dispatch the event it will call the update method on the Main class. I found really ugly and not elegant at all. I can't even think of how I could work with this;
Is there any cleaner and flexible ways, maybe some libs to help me out here, because I have not found any acceptable tutorial about how to do it like this?
thanks a lot
Well what I've managed so far, and I quite I like it a lot more than creating "empty" classes just for simple events (but still not good, at least for me):
private ArrayList __items;
public void addListener(Method method, Object object){
this.__listeners.add(new Object[] {method, object});
}
public void dispatch(){
int i = this.__listeners.size();
Method method;
Object context;
while(i>0){
i--;
method = (Method)(this.__listeners.get(i))[0];
context = (Object)(this.__listeners.get(i))[1];
try{
method.invoke(context);
}catch(java.lang.reflect.InvocationTargetException e){
}catch(java.lang.IllegalAccessException e){
}
}
}
Then I use like this:
Gifts gifts = prendastotty.PrendasTotty.getMain().getLoggedUserGifts();
Class[] parameterTypes = new Class[0];
try{
Method m = Home.class.getMethod("__updateTable", parameterTypes);
gifts.addListener(m, this);
}catch(NoSuchMethodException e){
}
It this leaky/anti-pattern/buggy?
I must say that I had a bit of trouble keeping up with your code because in my head some of the stuff didn't make sense (from a Java way of thinking, or at least my Java way of thinking). So I hope I understood you correctly and can help you out.
Let's first take your simple example:
var model = new Model();
this.callback = function(e){/* do something */}
model.addListener("change", callback);
In Java a good approach,for example, would be:
public interface ModelListener {
public void execute(Model context);
}
public class Model {
private List<ModelListener> listeners;
public Model() {
this.listeners = new ArrayList<ModelListener>();
}
public void addListener(ModelListener listener) {
this.listeners.add(listener);
}
public void dispatch() {
for (ModelListener listener: listeners) {
listener.execute(this);
}
}
}
With this sort of design you can now do one of two things:
Use anonymous classes
In Java the most common case is that all your classes have a name, although there are cases when you can create anonymous classes, these are basically classes that
are implemented inline. Since they are implemented inline, they're usually only
used when they're small and it's known they won't be re-usable.
Example:
Model model = new Model();
model.add(new ModelListener() {
public void execute(Model model) { /* do something here */ }
});
Notice how the new ModelListener object is created (which is an interface) and the execute implementation is provided inline. That is the anonymous class.
Interface Implementations
You can create classes that implement your interface and use them instead of anonymous classes. This approach is often use when you want your listeners to be re-usable, have names that give semantic meaning to the code and/or they're logic isn't just a few lines of code.
Example:
public class LogListener implements ModelListener {
public void execute(Model model) {
// Do my logging here
}
}
Model model = new Model();
model.addListener(new LogListener());
Side note
As a side note, I saw that the method you were trying to bind as a listener was called __updateTable are you by any chance trying to detect object's changes so you can commit them to the database? If so I strongly suggest you to look at some ORM frameworks such as Hibernate or JPA they'll keep all that hassle from you, keeping track of changes and committing them to the database.
Hope it helps, regards from a fellow portuguese StackOverflow user ;)
You will find it a bit difficult to try to directly map javascript ideology into java. Their underlying philosophies are different. Without more definite code and expectations it is difficult to give you a clearer answer. Here is a sample of code in GWT(written in java) that attaches a click handler to a button.
Hope this helps you get started.
myButton.addSelectionListener(new SelectionListener<ComponentEvent>(){
#Override
public void componentSelected(ComponentEvent ce) {
// do your processing here
}
});
In Java, a function can't exist outside of a class as it can in Javascript. So when you need to provide a function implementation at runtime, you have to wrap that function inside a class and pass an instance of the class, unfortunately.
The solution you have using reflection will work (I assume), but it is not the preferred way to do it in Java since what used to be compile-time errors will now be runtime errors.

Looking for an appropriate design pattern

I have a game that tracks user stats after every match, such as how far they travelled, how many times they attacked, how far they fell, etc, and my current implementations looks somewhat as follows (simplified version):
Class Player{
int id;
public Player(){
int id = Math.random()*100000;
PlayerData.players.put(id,new PlayerData());
}
public void jump(){
//Logic to make the user jump
//...
//call the playerManager
PlayerManager.jump(this);
}
public void attack(Player target){
//logic to attack the player
//...
//call the player manager
PlayerManager.attack(this,target);
}
}
Class PlayerData{
public static HashMap<int, PlayerData> players = new HashMap<int,PlayerData>();
int id;
int timesJumped;
int timesAttacked;
}
public void incrementJumped(){
timesJumped++;
}
public void incrementAttacked(){
timesAttacked++;
}
}
Class PlayerManager{
public static void jump(Player player){
players.get(player.getId()).incrementJumped();
}
public void incrementAttacked(Player player, Player target){
players.get(player.getId()).incrementAttacked();
}
}
So I have a PlayerData class which holds all of the statistics, and brings it out of the player class because it isn't part of the player logic. Then I have PlayerManager, which would be on the server, and that controls the interactions between players (a lot of the logic that does that is excluded so I could keep this simple). I put the calls to the PlayerData class in the Manager class because sometimes you have to do certain checks between players, for instance if the attack actually hits, then you increment "attackHits".
The main problem (in my opinion, correct me if I'm wrong) is that this is not very extensible. I will have to touch the PlayerData class if I want to keep track of a new stat, by adding methods and fields, and then I have to potentially add more methods to my PlayerManager, so it isn't very modulized.
If there is an improvement to this that you would recommend, I would be very appreciative. Thanks.
I am not at all an expert in design patterns. But this is what I think might be useful:
To add actions to the player, you might wanna look at the Strategy Pattern. Just google for it and you will get lot of examples.
Here is an attempt by me:
For updating the player stats, I guess Observer Pattern will be helpful.
The Observer Pattern defines one-to-many dependency between objects so
that when one object changes state, all of its dependents are notified
and updated automatically.
It enforces loose coupling so that future changes are easy.
(You will have to read about Observer Pattern and also will have to see some examples. It is not as straight forward as Strategy.)
Due to the fact that you said you want to be able to add new stats and actions later, I would tend to make a stats object that doesn't need to know anything about the game it's recording. The advantage is that the Stats class would never need to change as you added new features.
public interface Stats {
void incrementStat(Object subject, String stat);
int getStat(Object subject, String stat);
}
You Player implementation would look something like:
public void jump() {
// Logic to make the player jump...
stats.incrementStat(this, "jump");
}
Of course, what you're trading for that flexibility is static type-checking on those increment methods. But in cases like this I tend to think the simplicity is worth it. In addition to removing tons of boiler plate from the PlayerData and PlayerManager classes, you also end up with a reusable component, and you can get rid of the cyclic dependency between PlayerManager and Player.

What OO structure should I use to describe animal's behaviors?

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?).

Categories