Initializing a JavaBean - java

I am finding myself making a lot of Classes for use in GUI building (hence they must conform to the JavaBean pattern). This has created some issues for me regarding initialising. I often have some method that is quite time intensive that must be executed once the state has been set.
One approach is to document that the method init() must be executed and hope that people read and respect it, but that is clumsy and means that the GUIBuilder can't just be used as intended, but rather extra code has to be added.
I've checked Bloch's "Effective Java", these forums and of course I asked Dr Google, but I haven't come up with anything. To be fair, it's a bit of a wishy-washy set of search terms.
The following short example (obviously trivialised) demonstrates my current approach. I have an "isInitialised" variable and invalidate the instance whenever a setter is called. Whenever a getter is called on a calculated variable (or any other complicated method), the isInitialised variable is checked and if needed the init() method is called.
public class BeanTest {
private int someValue; // Just some number
private float anotherValue; // Just another number
private double calculatedValue; // Calculated by some expensive process
private boolean isInitialised = false; // Is calculatedValue valid?
/**
* Default constructor made available for JavaBean pattern
*/
public BeanTest() {
someValue = 0;
anotherValue = 0;
}
//******* Getters and setters follow ************/
public int getSomeValue() {
return someValue;
}
public void setSomeValue(int someValue) {
if (someValue == this.someValue) {
return;
}
isInitialised = false; // Calculated value is now invalid
this.someValue = someValue;
}
public float getAnotherValue() {
return anotherValue;
}
public void setAnotherValue(float anotherValue) {
if (anotherValue == this.anotherValue) {
return;
}
isInitialised = false; // Calculated value is now invalid
this.anotherValue = anotherValue;
}
/**
* This is where the time expensive stuff is done.
*/
public void init() {
if (isInitialised) {
return;
}
/* In reality this is some very costly process that I don't want to run often,
* probably run in another thread */
calculatedValue = someValue * anotherValue;
isInitialised = true;
}
/**
* Only valid if initialised
*/
public double getCalculatedValue() {
init();
return calculatedValue;
}
/**
* Code for testing
*/
public static void main(String[] args) {
BeanTest myBean = new BeanTest();
myBean.setSomeValue(3);
myBean.setAnotherValue(2);
System.out.println("Calculated value: " + myBean.getCalculatedValue());
}
}
This approach has multiple issues. For example, it doesn't extend well (and some of these really are intended to be extended). Also, I show only a simple case here with three variables; the real classes have many more. Things are becoming a mess.
Can anybody suggest a different method or pattern that could help me keep the code more elegant and readable and still allow things to work as expected in a GUI builder please?
P.S.
This is meant to be mutable.
EDITED
I think by trivialising I hid the point a bit.
The trick is I want to run the init() stuff only once, and only when everything is set. If I was using a builder pattern, this would be easy, as I would put it in the build() method, but this is in a GUI element and so is in a JavaBean pattern.
The code I have above is a trivialised version of the "pattern" I am using. The pattern does work, but there are many weaknesses as I have noted, particularly with extensability (is that a word?) and as the number of variables grows. The trivial example looks alright, but the real code is starting to look horrendous.
I guess this could just be a weakness of the JavaBean pattern, but I thought I'd ask before I crafted another dozen dodgy classes in my package.

Naive approach: why not simply call init() in the setter instead?
A bit more fancy: use a PropertyChangeSupport object. Sample usage:
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
public class TestBean implements PropertyChangeListener{
private int someValue;
private PropertyChangeSupport changeSupport;
public TestBean() {
changeSupport = new PropertyChangeSupport(this);
changeSupport.addPropertyChangeListener(this);
}
private void init() {
//do something time consuming, maybe even on a different thread, using Futures?
}
#Override
public void propertyChange(PropertyChangeEvent evt) {
init();
}
public int getSomeValue() {
return someValue;
}
public void setSomeValue(int someValue) {
int oldValue = this.someValue;
this.someValue = someValue;
changeSupport.firePropertyChange("someValue", oldValue, someValue);
}
}

I think I have to accept that what I'm trying to achieve can't be done. Here is a quote from Bloch's "Effective Java":
Unfortunately, the JavaBeans pattern has serious disadvantages of its
own. Because construction is split across multiple calls, a JavaBean
may be in an inconsistent state partway through its construction. The
class does not have the option of enforcing consistency merely by
checking the validity of the constructor parameters.
While it doesn't exactly answer my question, I think any answer that gets around the isInitialized variable would run into the issue that Bloch describes.

Related

What are the patterns/idioms for introducing [boolean] configuration flags/parameters in a Java application?

I have a Java application (an interpreter written in antlr4 to be precise) with numerous options in the code I would like to be [power] user configurable. Something like a config.properties file. Most of them are Boolean flags, if set, do this, else do that.
Currently, I have one class per flag, and the classes are scattered through-out the code, mostly in the same package where the implementation needs it. And, you can say:
import my.package.DoThis;
if (DoThis.isSet()) {
doThis();
} else {
doThat();
}
where the code for DoThis is something like
package my.package;
public class DoThis {
private static Boolean doThis = true; // the default
public static Boolean isSet() { return doThis; }
public static void set() { doThis = true; }
public static void clear() { doThis = false; }
}
And, there is a centralized part of the code that main calls, that initializes these options.
public void setup() {
DoThis.set();
DoAnother.clear();
if (cmd.option.debug()) { DoThird.set(); } else { DoThird.clear(): }
}
But, as I said, I'd like to clean the code up and use a configuration file that I can keep in the resources or a power user can override. A properties file or maybe a json file would seem like the right user interface.
However, properties read strings, do I check for yes/no, true/false? to set the flag. Or is there something better to do?
Should I also make all the options part of one class and perhaps store them in a map? What will make adding configuration options easiest?
Most importantly, I'd like to follow some form of Java best practices for doing so. I don't want to be that person who can write FORTRAN in any language. I want the code to look like what other Java programmers would naturally write. I'm pretty certain what I have now is not it.
I am not aware of a universally-accepted "best" approach for this. My preference would be not to have a separate class per flag, but rather to rather to centralise all the flags within a single class called, say, Config. It's public API might be something like the following (assuming the flags are called x, y and z):
public class Config {
private boolean x;
private boolean y;
private boolean z;
void setX(boolean value) { x = value; }
boolean getX() { return x; }
void setY(boolean value) { y = value; }
boolean getY() { return y; }
void setZ(boolean value) { z = value; }
boolean getZ() { return z; }
}
If you don't want to have to pass an instance of Config as a parameter to lots of different operations/constructors in your application, then you could create a singleton instance of Config.
I don't think my suggestion above would be too controversial among programmers. What is more likely to attract controversy is opinions about the "best" way to initialise the Config object. Some people might suggest that the Spring Framework should be used to inject values obtained from an XML file. Some other people might suggest that your setup() operation should read values from a configuration file in whatever happens to be your favourite syntax (properties, JSON, XML or whatever) and possibly allowing command-line options to override values specified in the configuration file

How to instantiate, configure and use a lib/framework in a oo-application?

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.

How to find out whether Method has called for given instance. Like "Object obj" check whether obj called "equals" method or not

I want to find out whether method for some object is being called for that instance or not.
Is it possible in java ?
Like ...
class Button {
public void focus(){}
public void setName(){}
}
class MyTest {
public static void main(String[] args){
Button button = new Button();
button.focus();
// I want to find out on button instance whether focus() or setName() is called or not.
whetherMethodCalled(button);
// OR
whetherMethodCalled(button, 'focus');
whetherMethodCalled(button, 'setName');
}
}
EDIT : Forgot to add Button class is third party class which I cannot modify... Also I want to check in my code whether method has called for given object instance or not on basis of that I have to write some code.
In order to reduce extra work, perhaps profiling your application with JConsole or another tool is good enough to show if certain methods have run. Another option is using a code coverage tool like EMMA which detects dead code. There is a list of open-source profilers for Java at http://java-source.net/open-source/profilers and EMMA is at http://emma.sourceforge.net/.
With some extra work AspectJ could be use to intercept method calls without changing existing code. For example, the following would intercept calls to Button.focus()
#Aspect
public class InterceptButtonMethods {
#Before("execution(* Button.focus())")
public void beforeInvoke() {
System.out.println("Button.focus invoked");
incrementFocusCount();
}
}
If more extra work is ok, there is a way to wrap all calls to the Button's focus() and setName() methods so that they update separate counters in addition to their normal functions. This can be done by extending Button in YourButton class which is identical to Button except for a couple of int counters with getters, setters and increment methods; and countingFocus() and countingSetName() methods which update their counters and call focus() and setName() respectively, such as in outline:
Class YourButton extends Button {
int focusCount;
int setNameCount
int getFocusCount() {return this.focusCount;}
void setFocusCount(int counter) {this.focusCount = counter} // optional to reset counter
void incrementFocusCount() {this.focusCount = getFocusCount() + 1;)
...
void countingFocus() {
incrementFocusCount();
focus()
}
...
}
If it is required in many places and involves complex things, I recommend to use Mockito to test your code. Using that you can verify if the method was invoked (also how many times if invoked)
You can mock the button and verify in your MyTest how many times the method must be called. Using Mockito you can mock and stub your methods(Stubbing voids requires different approach from when(Object) because the compiler does not like void methods inside brackets) and then verify it using verify statement.
verify(mockButton, times(1)).focus();
verify(mockButton, times(1)).setName();
You can write a wrapper class over the 3rd party Button class through which all calls to Button class will be made.
This wrapper class can keep track of whether each method has been called or not
class ButtonCaller {
private Button button = null;
private boolean focusCalled;
private boolean setNameCalled;
public ButtonCaller() {
button = new Button();
focusCalled = false;
setNameCalled = false;
}
public void focus() {
button.focus();
focusCalled = true;
}
public void setName() {
button.setName();
setNameCalled = true;
}
public void whetherMethodCalled(ButtonMethod method) {
switch (method) {
case FOCUS:
return focusCalled;
case SET_NAME:
return setNameCalled;
}
throw new RuntimeException("Unknown ButtonMethod !!!");
}
public static Enum ButtonMethod {
FOCUS,
SET_NAME;
}
}

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.

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