Polymorphism and boxes - java

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.

Related

assign data from dto to group of text fields in javafx

I'm new to JavaFX and what I'm trying to do is I have a DTO object with 15 fields that I fetch from backend which I need to show all the fields in screen
for now what I did for each filed will create textfield in fxml file and inject it in the controller using textfield id then set the text for that from the dto for example
#FXML
TextField firstName;
........
firstName.setText(dto.getFirstName)
so is there is any other way than going through each textfield and using setText to set their value
As you state that you are new to JavaFX, I do not recommend that you try to implement the potential approaches in this answer.
Investigate the controlsfx BeanPropertyUtils, PropertySheet and PropertyEditor.
Different potential implementation strategies:
You could use a collection of TextFields, e.g. a list and assign values sequentially based on, for example, position in an sql row set.
Or perform a lookup on a map of strings to TextFields based on a column name key.
Or use reflection on Java Beans (this is how controlsfx works).
But none of them would be worth implementing unless you have a great many fields and need some generic system to handle values. Otherwise I wouldn’t recommend implementing such abstract functionality.
An example of a generic use case would be if you were introspecting on an unknown large database schema.
If you do need to do this, probably your best place to start would be the controlsfx library.
SceneBuilderKit, which was used to build SceneBuilder, has similar functionality but it is not as easily accesible as ControlsFX.
I advise you review the above comments then decide if you really want to do this.
If you do, then choose one potential strategy and implement it (this won’t be done in a StackOverflow answer).
If stuck, provide a complete minimal reproducible example for a concrete example and implementation attempt in code, only for the art of the problem you are stuck on. This allows you to create a more concrete question that is greatly reduced in scope.

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.

ActionListeners, multiple field updates, and reloading user GUI selections from a file

I have multiple places where I convert between one coordinate system and another. In each case there is a cosine/sine calculation between, let's call them x, y and x', y'. These are all JFormattedTextFields.
If the user enters a value in any of the 4, an ActionListener is called. Lets call the fields fieldx, fieldy, fieldx1, and fieldy1. If the user enters anything in fieldx or fieldy, I HAD keyboard and focus listeners (the same one for all four fields) that would update fieldx1 and fieldy1 from the current values in fieldx and fieldy. If the call to the listener was from fieldx1 or fieldy1 it would calculate fieldx and fieldy.
Then I decided to save fields chosen (including a bunch of check-boxes on/off and some spinners' values) in a config file (new requirement after development). I thought that by setting values and states all would be fine BUT certain things were not happening (behind the scenes). I decided that part of this is that the triggered methods by various checking and entering and etc were not happening because the fields did not trigger keyboard and focus listeners when they were set by a piece of code.
After reading online I changed all the KeyboardAdapter to ActionListener and after I set the value I call postActionEvent() on the fields I mentioned above and now all the background stuff happens (though order is an issue and I'm going to save extra information about state to update this properly). I made this change because I thought it would be more difficult to fire off so many fake keyboard events?
There are probably more clever/smart ways to do this but for now I'm trying not to touch too much code.
Does anyone have a suggestion on a way to save the state of a panel and refresh this (the current object, the panel)?
If I continue to do it in this way, can someone suggest a way to MINIMIZE the times the ActionListener fires? It seems to fire so often it is ridiculous!
Should I instead do things as suggested here?
Should your class implement ActionListener or use an object of an anonymous ActionListener class
That seems like a lot more coding involved but a lot more precise in what triggers when...
If this kind of question/discussion is out of place here, just let me know :). Just typing up this page has made me think of more things to read up on and to try.
I'm trying not to touch too much code.
This is a foundational mistake; the trash can is an important design tool, and one or more minimal examples will be invaluable in learning to compose more complex applications.
Does anyone have a suggestion on a way to save the state of a panel and refresh this (the current object, the panel)?
Using the Model–View–Controller pattern, the program's data should be stored in a suitable model, and transformations should be done when model elements are rendered in the view; the Converter example shows how to manage custom events, and this example expands on the topic
If I continue to do it in this way, can someone suggest a way to MINIMIZE the times the ActionListener fires?
As suggested in the original article, use Action to encapsulate behavior. See Java SE Application Design With MVC: Issues With Application Design for a deeper examination of the problem.

Design difficulty with function containing objects passed as parameters

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

How to implement the idea of objects that access objects of other classes?

Say I want to implement a work place. There are objects of class Employee and there is also a class WorkArrangement, which is like a box into which the employees submit their desired shifts for the next week. (The manager then empties the box and uses this information to arrange shifts for the next week).
The problem is, that the code in the class Employee doesn't know the object box (of class WorkArrangement), so I can't write a method which says "put your next week shifts in the box". I can send the box object as a parameter to the constructor of Employee, but it looks like a bad design in the sense of OOP.
So, is it a bad design?
If it is, then what is a possible solution?
Sounds more like there's a Box (could just be a list) that takes Shifts, and an Employee has multiple collections of Shifts, desiredShifts and actualShifts.
The Manager then looks at each employee's desired shifts, juggles everything around, and assigns actual shifts to each employee, and/or puts them in a shared structure for use in a company calendar.
IMHO, I would use event-driven logic (e.g. using property change listeners). Once an Employee instance is ready to submit the desired shifts, fire off an event (e.g. PropertyChangeEvent). And in this event object, pass the shift information and other relevant information. From there, the receiver (i.e. WorkArrangement) can do what it pleases with such information (e.g. firing off another change event that notifies the Manager that is has received shift information).
A straightforward approach would be for WorkArrangement to have a method where the Employee submits requests. e.g.
public void requestShift(Employee employee, Shift requestedShift);
This way Employeee doesn't know how or what WorkArrangement does with the requests (they may get thrown into the trash for all you know!) but it knows how to sumbit a request. You might need an argument for which week it is, but I'd prefer that already be in WorkArrangement, e.g. every week you construct a new WorkArrangement() for that week. Later on, Employee could find out what they got via a call:
public Shift getActualShift(Employee employee);
BTW, this guides us to a better name than "WorkArrangement", which doesn't really mean a whole lot: something like "WeeklySchedule". Not all class names can be simple and clear, but when one of the first classes you design has a fuzzy name, that's a sign that you are not on the right track.
If you really don't want WeeklySchedule to know what an Employee is, note that the argument is really just used as an identifier, on which you will use equals() (and probably hashCode()) at some point. So that argument could be an Object, an integer or String employeeID, etc...

Categories

Resources