Using class methods, I want to make sure that the getAverage method is always called before the setAverage method
If setAverage is called first, it should return an error.
I'm confused as to how to check if the set is called before the get.
If getAverable returns a non primitive object, you can check if the value is null.
If you return primitive value, like integer, you can use a boolean to check if the setMethod was called.
class Name {
int value;
boolean isCalled;
public int getValue() {
if(isCalled == false) {
throw new Exception();
}
else {
return value;
}
}
public void setValue(int value) {
isCalled = true;
this.value = value;
}
}
There is no direct Java support for doing this. Of course, you could implement directly in the methods some algorithm which memorize which method was executed in which order. Better way to do this is with Aspect-oriented programming.
The simplest way to do what you want is to write an Aspect which writes in a Boolean that getter was executed and allows execution of setter only in case where Boolean flag is true.
Of course, this is only a first step and would be very error prone. (Concurrency, Repetiton etc.)
(I have written such a framework during my master thesis. Of course, it was a bit more complex than just checking single sequential method invocations.)
Related
For a project I am working on, I have to retrieve some entries from a NoSQL database. The values may either be Strings or Doubles, however, at the time of calling the method that retrieves these values, I do not know what type of value the field contains.
For the sake of argument here is a minimal working example, which is of course oversimplified:
public class ReturnType {
public static void main(String[] args) {
String s = "This is a string.";
double d = 23.5;
getValue(s);
getValue(d);
}
private static Object getValue(Object obj) {
return obj;
}
}
I have thought about checking the class of the object that is returned by the function and casting the returned object to that class:
if (getValue(s).getClass() == String.class){
String result = s;
} else if (getValue(s).getClass() == double.class)
{
Double result = d;
}
However, I do not like this solution at all, as I have to hardcode every possible return type into an if or case statement.
I have also thought about creating an additional method that checks the class before calling the method retrieving the value and using different methods with different return types, depending on the result of that. But this seems just like the same approach, albeit implemented differently.
What would be a best practice solution to this problem?
Which approach of checking beeing valid is better? The first one:
public class Order {
...
private boolean valid;
public boolean isValid() {
return valid;
}
public boolean setValid(boolean valid) {
this.valid = valid;
}
// getters, setters, etc.
}
where valid is kept as boolean in DB and set by Java code somewhere else, e.g. in DAO.
Or the second one:
public class Order {
...
public boolean isValid() {
// some business code, e.g.:
return !orderItems.isEmpty();
}
// getters, setters, etc.
}
where we don't have valid value keeped in DB, but everytime when it's needed it is been calculated on demand.
Which approach is better?
In the first example you are treating 'valid' as a POJO field, ie just like a getter() or setter() method, except because it is boolean it is an isser() method. This is OK, as I would not break this bean-like pattern. Getters and setters should have no logic behind them.
Insetad I would have another method validate() which does the heavy stuff.
validate() performs the validation and sets the valid variable. isValid() returns the last validation performed.
An antipattern I often see is a getXXXXX() method which takes about 30 seconds to complete because it is performing calculations and database hits, confusing the user of this class as the user assumes it is a normal getter in a normal POJO class.
There's no exact answer. It just depends. Depends on the design of your class and the business rules of your business.
For example, if the valid state of an order only checks for a simple rule like checking the current state of the object reference, then have it as a method with a body.
public class Order {
public boolean isValid() {
//validate current state of object reference
//re using your same example
return !orderDetail.isEmpty();
}
}
But in the case you have a business rule that demands the order should pass for a validation process before sending it to the client and this status (and a proper description) should be known at any moment of the application, then having a valid field in database is one way to solve it. In fact, if this was the case, it would be even better to store the valid field as a VARCHAR(X) and limit the values of this field by using an enum OrderStatus. But then again, this depends on the design for your class.
Fisrt structure with setValid method is ugly. I can not imagine the usage of setValid method.
If you want to use separate property, the better way is to use lazy initialization:
public class Order
{
...
private Boolean valid;
public boolean isValid()
{
if (valid == null)
{
valid = !orderItems.isEmpty();
}
// some business code, e.g.:
return valid;
}
}
If isValid method contains hard logic and your class is immutable (orderItems is a constant) then you can use this variant.
In other cases second variant is better.
Can we modify a Boolean value in class function in java, something like this wont work as the change is local to function. How can we make the following change passed variable reflect outside the method call?
public void changeboolean(Boolean b)
{
if( somecondition )
{
b=true;
}
else
{
b=false;
}
}
EDIT
The code could be like this:
public String changeboolean(Boolean b,int show)
{
if( somecondition )
{
b=true;
show=1;
return "verify again";
}
else
{
b=false;
show=2;
return "Logout";
}
show=3;
return verifed;
}
I'm searching for something like this
b.setvalue(true);
Is it possible?
Can we modify a Boolean value in class function in java
No, Boolean is immutable, like all the wrappers for the primitive types.
Options:
Return a boolean from your method (best choice)
Create a mutable equivalent of Boolean which allows you to set the embedded value. You would then need to modify the value within the instance that the parameter refers to - changing the value of the parameter to refer to a different instance wouldn't help you, because arguments are always passed by value in Java. That value is either a primitive value or a reference, but it's still passed by value. Changing the value of a parameter never changes the caller's variable.
Use a boolean[] with a single element as the wrapper type
Use AtomicBoolean as the wrapper type
Boolean is immutable, like all the wrappers for the primitive types.
Soln:
Trying using MutableBoolean of apacheCommon
http://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/mutable/MutableBoolean.html
I have a Java method something like this
public boolean ReadBool(String ValueName, Boolean Value)
{
boolean Retval = ...;
...
Value = true;
...
return bRetval;
}
that I call from native code (C++) like this:
jMethodID MethodId = pEnv->GetMethodID(ClassId, "ReadBool", "(Ljava/lang/String;Ljava/lang/Boolean;)Z");
// What goes instead of "??" ?
bool bOk = pEnv->CallBooleanMethod(myobject, MethodId, pEnv->NewStringUTF("Value1"), "??");
My intention is for the Java method to "return" a boolean value in Value. I understand that a built-in boolean will not work for this purpose. Is it possible to do this with a Boolean wrapper? How does one construct the object to pass in place of "??" ?
I have googled around, but some questions remain. For example, I suppose I could pass an object created by calling Boolean's <init> "method". But wouldn't the assignment in the Java ReadBool make Value refer to a newly created wrapper, throwing away that first object? In that case I would have called <init> for nothing. I think it should be possible to create (in the native code) something that Java sees as an object that is null and whose type is Boolean. Is that possible? Or am I on the wrong track altogether?
Booleans are immutable in Java, so you need your own wrapper class, which can be really simple though:
public class BooleanWrapper {
public boolean val;
// public is fine here imo, but you can obviously use [g|s]etters as well
}
Or if you don't want this, we can use a.. well not really pretty, but nice to know hack:
public void hack(boolean[] vals) {
vals[0] = true; // voila, now you change the value itself
}
Has some obvious drawbacks when calling (and looks strange), but if you're fine with keeping a specific parameter sequence, you can do:
public void hack(boolean.. vals) {
vals[0] = true; // voila, now you change the value itself
}
that way the caller doesn't have to use stuff like new boolean[] {};
You can obviously cheat and change the internal state of the Boolean object itself, but that will have unwanted consequences (booleans are cached ergo if you change the Boolean.TRUE instance to false internally this will give interesting results). So don't do that.
I have a question about making a compareTo function in Java.
In Java, we have the String.compareTo(String) method.
However, I need to make a compareTo function with only only parameter, like: compareTo(String).
I assume that I need to use this to hold another string.
For example:
public static boolean compareTo(String word)
{
private string this.word = word;
if(word.equals(this.word))
{
return true;
}
else
{
return false;
}
}
Is this the right idea?
Do I need to create get and set functions to hold first word to compare with second word?
Thanks
To compare two objects, you need to implement the Comparable interface. As part of the implementation, you will write your own compareTo() method. This method compares your current object with the object being passed.
public MyObj implements Comparable<MyObj> {
...
public int compareTo(MyObj anObj) {
// if your obj greater than anObj, return 1
// if equal, return 0
// else return -1
}
}
Further down in your code, you can then do --
`MyObj anObj = new MyObj();
MyObj anObj1 = new MyObj();
// anObj.compareTo(anObj1) ....
// This will also be useful if you have a collection of MyObjs.
Collections.sort(arrayListOfMyObjs);
That's not the right idea in many ways...
You cannot use this in a static function.
You cannot add a visibility declaration to a local variable of a function.
There is no string but String in Java.
You make this.word equals to word then check if they are equal...
You don't need to do if/else to return a boolean: just do return x.equals(y); (not necessarily wrong, but that's a personal pet peeve...).
compareTo, the classical one, isn't equals, but returns -1, 0 or 1 depending if one object is lower, equals or higher than the other.
Revise your lessons... :-)
In your code, the method compareTo is static, so you can not use "this."
I suggest you'd better NOT make compareTo method static.