Design difficulty with function containing objects passed as parameters - java

So I'm working through some programming exercises in java right now and the current exercise I'm using involves using the acm.graphics library. Basic shapes and stuff drawing pictures.
What I want to do, is create a function which has parameters for a GObject and a Color object and call setFilled() and setColor appropriately (since retyping this for each shape object is extremely redundant).
The problem I'm running into is this,
The GObject class is a superclass of GRect, GOval, GLine, etc but doesn't actually contain a setFilled function (thus throwing an error when trying a parameter header such as function f(GOBject A, Color ArgC).
So how should I go about creating this function, or is it even possible without editing the standardized library for GObject. I was thinking I could deal with this error by simply creating an empty setFilled function in GObject but from what I understand its generally a bad idea to go into standardized libraries and make changes arbitrarily and the right approach for making changes should be to extend / overload from a subclass as needed. Anyways I'm at an impasse with my compiler so I'm open to ideas, thanks.
P.S/Nonrelevant Question why is the word "problem" banned from the Title Box?

Write it for the GFillable interface instead since this is implemented by the shapes you are after. http://jtf.acm.org/javadoc/complete/acm/graphics/GFillable.html

Related

Event handling between immutable objects

I am making a simple notepad application in Java and trying to use a fluid and immutable style, for the sake of trying it out. I have found it a lot of fun and am seeing lots of the great advantages that get talked about in regards to functional programming (code clarity etc.).
But I have an issue with event handling in general. I have one class TextArea that provides a Notepad-like document like you'd expect. Then I have another class ScrollBar . They are manipulated by a master class CentralController that keeps the scroll bar and text area working together (not the real class name, it's just for this example).
So if the user presses the down arrow, CentralController simply calls TextArea.withDownArrow() and that returns a new copy of the TextArea with the cursor moved down. The problem is the Scroll Bar now needs to be moved, so the CentralController needs to know whether the TextArea got scrolled by that down arrow.
My first attempt to solve it was to return an object that contained not only the new TextArea, but also a flag saying whether the scroll needs updating. That worked well but didn't feel right because I was no longer returning the TextArea whereas you really should in 'proper' functional programming (roughly speaking).
So then I tried having a flag inside TextArea that would get set if TextArea.withDownArrow() caused scrolling. That also works well but seems wrong to have a method result stored 'globally' in the class. It also has issues where you might call withDownArrow() twice and then the flag gets overwritten with a new result.
I have read a bit about Reactive Programming and it does seem interesting, but I'm not sure of it's suitable for this situation where you have a 'child' class sending a message to a sibling.
Just to add, I am under the impression normal event handling won't work in this situation. With immutable objects when you change something you create a new object. So any objects that try to send an event to a listener will be sending to an old pointer.
Am I missing an obvious way to do this because I feel like I am? Or is it actually ok to use normal Java event handling techniques and I'm worried about nothing?
Edit: I think I have worked out a good enough solution now. Even though the class that receives events (ScrollBar) is recreated all the time, the members of that class do not get recreated. Only things that change.
So I will just have an simple event receiver method in ScrollBar, and TextArea can have a list of listeners (basically the 'normal' way of doing events with listeners).
In summary my error was thinking I needed to send an event to a instance, rather than a member of that instance.
You have to differentiate between value objects and logic objects. Value objects contain nothing but values, no logic(*). They can be immutable.
But of course a text area cannot be a value object, nor can a scrollbar be a value object, because they must contain logic. Nor can they be immutable, because they contain state. So, scratch all that. It won't work.
(*) Or at least no logic that deals with external entities, or manipulates any of their own state.

LibGDX public sprite batch for the entire application

The question at hand here is whether it is a good idea to have one public SpriteBatch in the Game class, which is then used by all Screens. This would avoid reallocating objects whenever the active Screen changes.
However, I see people using new and private SpriteBatches in each and every Screen. Why do people do this? Am I missing something here?
Using a single Batch instance is advised, but I don't think public (or static) variables are a good idea, since they break the encapsulation and make it harder to refactor the code. Imagine moving the screen class to another application: you would have to replace all references to the batch in your Game extension or you'd be forced to create such field in yet another project.
Instead, I'd pass the batch in screen constructor. Screens are for displaying views, after all: no need to inform them about the rest of the application.
You're right. They should not be doing that. You can make it final if you want to protect it a bit. All objects that use it should know to set the parameters that they need, such as applying their own projection matrix and blend mode.

How can I generate and compile Java files in Android at Runtime

I know with javax.tools.* it is possible, but since this is not included in the Android API, I'm desperately wondering, is this possible?
Right now, my goal is to create a drag-and-drop tool to allow users to create their own layouts (as not everyone wants to learn Mobile Development, as it requires a lot of time, dedication and practice) similar to how Android Studio does it's own. However, of course the most important thing is to implement functionality via onClickListener and onTouchListeners. I've begun remedying this by creating my own DSL (Domain-Specific-Language) with a GUI front-end allowing users to choose what they want via PopupMenu and SubMenus. For example...
Statements
{ if, for, while }
Statements must be followed immediately by a reference and then a conditional (obtained from that reference), like a "if(Object.conditional())" statement.
References
{ Object1, Object2, Object3 }
The objects are references to other Views (I.E, Buttons, Layouts, WebView, etc.).
Conditionals|Actions|Getters|Setters
{ isSomething(), doSomething(), getSomething(), setSomething() }
Each Reference's methods, wrapped so that each wrapper keeps track of it's method's attributes and description (hence documentation).
It would go something like such...
IF ImageView1.isVisible()
ImageView1.setVisible(false)
ELSE
ImageView1.setVisible(true)
Of course, the method setVisible(boolean) is a wrapped version of setVisiblity(int).None of this is typed, it is obtained from a simple PopupMenu which shows them the applicable selections based on current context.
How I plan on transcribing this to compiling code was to convert the statement into Java code, inserting references on the fly as they are needed (I.E, ImageView1 would be defined in java as private ImageView ImageView1;), generate methods somewhat similar to how ButterKnife generates it's extra classes for it's onClick and onTouch annotations, etc.
Then, after planning all of this (been working on it for 2 weeks now), I find out that Android does not have support for compiling code like this. Please tell me something like this is possible. It's something I 100% wanted to do. Is this possible with any third party libraries?
If not, is there some possible way to mimic doing so? I could do it the long and slow way, of preparing every such possible way, keeping track of the references myself through a map, and when it is about to be called, directly call the implemented method for the View associated with that key, which theoretically COULD work. In fact, that'd be my second go-to if I can't. It'd be messy though.
Sorry if this is too long, I just want to get this to work.
TL;DR: Is there a way to compile a generated Java file created at Runtime in Android (since javax.tools.* does not exist), and if not what would be the best way to do so?

Generalize many similar functions into one using varags

Background:
I currently have a working java application that uses WorldWind to display various types of data on a world map. The data comes from various clients via RPC. Each call is tied into a data type and has various arguments like so:
public synchronised ObjectID draw2DCircle(UUID userID, Position centre, Double radius){...}
public synchronised ObjectID draw2DRectangle(UUID userID, Position centre, Double width, Double length){...}
For every draw method there is also an update method:
public synchronised boolean update2DCircle(UUID userID, ObjectID objID, Position newCentre, Double newRadius).
Each data type has its own class so draw2DCircle has a MapSurfaceCircle class, draw2DRectangle has a MapSurfaceRectangle. There is a lot of commonality between the types and I have various interfaces for the groupings of datatypes such as 2D shapes, 3D shapes etc but the one interface that all objects have in common is the IMapObject interface that has the render, preRender, move etc calls.
The flow of operation for the draw functions is something like this:
Check function arguments.
Create MapObject.
Add MapObject to map layer (allows WorldWind to call render on it).
Update internal map that has a list of MapObjects and who owns them.
Return the ID of the MapObject to the caller.
The flow of operation for the update functions is something like this:
Check the function arguments.
Check that the caller owns the objects.
Create new Callable that will run the MapObjects updateXXX method.
Pass the callable to a FutureTask where it will then be fired off into the EDT.
Await the return via get() and return this back to the caller.
The Problem:
Normally I would not be too concerned with the setup of this but there are about 50 different types of shape that can be put on the map. That means 50 different drawXXX methods and 50 updateXXX methods each with different arguments but very similar code underneath. I have a rather large file with lots of repetitive code which is not really that great for maintainability.
My Thoughts:
I need to keep the different shape type classes so will still need to have the different constructors for each one but I think I can generalize the update calls. If I remove the specific update2DCircle, update2DRectagle etc.... in the shape classes and replace with a simple update (from the base IMapObject interface) and use varags I should be able to funnel all the RPC update calls into one method like so:
update2DCircle(Args){return shape.updateShape(Args);}
update2DRectangle(Args){return shape.updateShape(Args);}
and each shape have the implemenation:
private boolean updateShape(Object ...){}
I understand that i'm loosing type checking with the varags but the type checking is done on the RPC implementation that made the call.
Another thought I had was to not update the shape but create a new one each time the draw/update method is called but this is slightly more complicated by the fact that the shape might be changing from internal WorldWind methods (on EDT) and the RPC methods happen on a different thread so I would need some sort of shape locking.
Question:
From what I have explained, does it look like any of my proposed solutions are the correct way to do it or my existing setup was OK? Is there are better solution using some design pattern i've not thought of?
I've tried to make this as much a programming question as possible (as opposed to opinion) to meet the SO rules although I do understand how it may read but this is not my intention :)
I believe the Template method pattern is the one you should use

Polymorphism and boxes

I am trying to get round a rather annoying issue in my homework.
Basically the task is to create a fake ordering UI where the user puts in some variables about the type of box they need to order and then presses a button. Behind the scenes the app should be validating which pipe fits the users needs and then instantiate a new box object and execute the methods inside the new object.
I am basically struggling to find a way that isn't stupid which allows for the UI to validate a choice before creating a new object, a method is given to us to begin with and is referred to a 'brute force method' which has a massive if statement inside the button click which does the checking there, now I am 100% sure there is an easier way to do it although the only thing I can come up with is holding constants or statics in a class and checking each class before creating one.
Scenario:
The idea is that each box the company sells has certain features (thickness, laminated, colour and other things) while others boxes don't, I need to be able to figure out when the order button is clicked what box the order fits once I know the box type that the order fits I should create a new object of that box and run the cost() method, if it doesn't fit any box the company sells then I should prompt the user. The program must use abstraction.
The class isn't at a high level at the moment so I can't use enums and lookup tables which is causing me problems.
Thanks for any help in advance.
Sounds to me like they just want you to show several classes (one for each type of box) which all inherit or implement a common interface with methods like 'getWidth', 'getHeight' etc. You can then write a simple loop to iterate over a collection of box type instances, evaluating their suitability before returning the list of compatible box types.

Categories

Resources