Declare final variable, but set later - java

I know this is fairly simple topic, but I really want to wrap my head around it.
This is what I'm trying to do, but it doesn't like the final modifier. Is there another way to achieve the effect I'm looking for? Which is basically that I want to make sure the id can not change durning the Activities entire life.
private final long mId;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mId = getIntent().getLongExtra(ID_KEY, -1);
}
I should point out that this is Android code. Thanks for all the help. I'm not worried about getters or setters or anyone changing my code. The reason I asked was to future proof my code for the next developer to take over. I found this post that also helps shed some light. Android - Activity Constructor vs onCreate

You can set a final variable only in a constructor or in an initializer. Regular methods cannot change the value of variables declared final.

You can't. But you can guarantee no external object changes it if it's private and you don't have a setter for it.
Alternatively, you can wrap the long value in another class - LazyImmutableLong. But this is a more verbose approach, and you probably don't need it (note: the class below is not thread-safe)
class LazyImmutableLong {
private Long value;
public void setValue(long value) {
if (this.value != null) {
return; // the value has already been set
}
this.value = value;
}
public long getValue() {return value;}
}
And in your activity
private LazyImmutableLong id = new LazyImmutableLong();
public void onCreate(..) {
id.setValue(..);
}

The following Worm (Write-Once-Read-Many) class could help in this kind of scenario.
We could create a nested Wrapper class, that stores the final variable you need. To initialize this variable, you just should call a constructor of the wrapper object. When you call the method getData(), you will get a reference of the final variable in case it is initialized, otherwise, you will get null.
The methods getData() and setData(T data) are required to be thread-safe. To provide it, we use a volatile modifier for the wrapper object. Reading a volatile variable is synchronized and writing to a volatile variable is synchronized, too. Even though some efforts were made to make this code thread-safe I didn't test it in this respect. Depending on the level of thread safety you may consider to make setter and getter synchronized.
public class Worm<T> {
private volatile Wrapper<T> wrapper;
public Worm() {}
public Worm(T data) throws IllegalAccessError
{
setData(data);
}
public T getData()
{
if (wrapper == null)
return null;
return wrapper.data;
}
public void setData(T data) throws IllegalAccessError
{
if (wrapper != null)
throw new IllegalAccessError();
else
wrapper = this.new Wrapper<>(data);
}
#Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Worm<T> other = (Worm<T>) obj;
return Objects.equals(this.getData(), other.getData());
}
#Override
public int hashCode() {
return Objects.hashCode(this.getData());
}
final private class Wrapper<T> {
final private T data;
Wrapper(T data) {
this.data = data;
}
}
}

private final long mId;
final reference cann't be modified at runtime as per java spec. So, once you declared it as final, mId can't point to something else throughout its lifetime (Unless you use reflection (or) wrap the value in object and modify it through other reference).

You can set later a global final Variable only in your constructor. Example:
public class ClassA {
private final long mID;
public ClassA(final long mID) {
this.mID = mID;
}
}
In this case in each constructor you have to initialize the final variable.

you have to initialize the constructor as soon as you create it, or you could initialize it at the max, in the constructor. Not later than that..

NO it can not be done
if you can declare final at one place and initialize it later, Then What is the mean of final.
If you want to have a constant ID, why don't you use Shared Preferences , store it in SP and retrieve whenever want.

Related

Java How to access data from local inner class

Below code is some example analogous to what I am trying to achieve. I have to store the data from internal class but the compiler complains following:
returnedValue=(MyXYZClass)value.toString();
Local variable selectedBusinessArea defined in an enclosing scope must be final or effectively final
private String methodInMainClass(Object someRef){
String returnedValue="";
new SomeInnerClass(Object someRef){
#Override
public String getData(Object value){
if(value instanceof MyXYZClass){
returnedValue=(MyXYZClass)value.toString(); // Not Happening. I cannot assign it to the outer variable.
}
return super.getData(value);
}
}
How can I store the value from the overriden method in internal class?
The local variable in your code sample is returnedValue. It has to be final or effectively final but it's neither declared final nor effectively final since it gets a value assigned.
How to solve this:
All you need is final or effectively final variable which can store the state of returnedValue. There are many ways to do it.
One way would be to define a class like BoxedValue.
public class BoxedValue<T> {
private T value;
public void set(T value) {
this.value = value;
}
public T get() {
return value;
}
}
Using it in the code:
private String methodInMainClass(Object someRef){
BoxedValue<String> returnedValue = new BoxedValue<>("");
new SomeInnerClass(Object someRef){
#Override
public String getData(Object value){
if(value instanceof MyXYZClass){
returnedValue.set((MyXYZClass)value.toString()); // Not Happening. I cannot assign it to the outer variable.
}
return super.getData(value);
}
}
return returnedValue.get();
}
The variable returnedValue is now effectively final.
If you don't want to define an additional class, you can use any other to store the state, i.e. Optional<String> returnedValue = Optional.of("").
You can use an array in order to do the trick
private String methodInMainClass(Object someRef){
String[] returnedValue= {""};
new SomeInnerClass(someRef){
#Override
public String getData(Object value){
if(value instanceof MyXYZClass){
returnedValue[0] = ((MyXYZClass)value).toString(); // Not Happening. I cannot assign it to the outer variable.
}
return super.getData(value);
}
}
// [...]
it is not about inner class this also happened in lambda, the you can not change value of var from out of scope of lambda or inner class, otherwise you may make access issue and for multithread race condition, as workaround you may use one of Atomic family classes for that like AtomicReference<T> or AtomicInteger for ex. :
AtomicInteger count = new AtomicInteger(0);
Runnable r = () -> {
count.getAndIncrement();
};
r.run();
System.out.println(count);
Note here that I used only main thread not created new one to not face race condition.

In Java, how do we protect access of lazy fields?

If a Java class has a field that is initialized lazily or on demand, how can we ensure that access to the lazy field is via it's initializing access method?
By way of context, we recently had a situation in which a developer added access to an object that was initialized lazily, but not via its initializing access method. This wasn't caught at compilation or in unit tests, but then caused runtime errors.
For example - in the following SSCCE, _lazyObject is initialized via the getLazyObject() method. However, if there are other methods (in the class, because it already has a private access modifier) that would want to use _lazyObject, we should access via the getLazyObject() method, as otherwise it may not have been initialized.
public class MyObject {
private transient volatile Object _lazyObject;
public Object getLazyObject() {
if (_lazyObject == null) {
synchronized (this) {
if (_lazyObject == null) {
_lazyObject = new Object();
}
}
}
return _lazyObject;
}
public void doSomething() {
Object a = _lazyObject; // may be null - will compile, but may cause runtime errors!
Object b = getLazyObject(); // subject to exceptions, will not be null - this is how it should be accessed.
// do something...
}
}
How can we ensure that the access of _lazyObject is via getLazyObject()?
Is this possible in the code within MyObject?
Alternatively, is it possible to ensure this via unit tests?
Ok, so I'm open to further suggestions, but this is the best solution that I have come up with so far.
We can 'protect' the lazy variable in an initializing object - I thought about writing this myself, but found that there are good implementations of this in Apache Commons Lang (LazyInitializer) and Google Guava (Supplier). (Credit to Kenston Choi's answer to this question.)
For example - to clarify, I've changed the lazy object class from Object to a placeholder T:
public class MyObject {
private transient Supplier<T> _lazyObject = Suppliers.memoize(new Supplier<T>() {
#Override
public T get() {
return ...; // make T
}
});
public T getLazyObject() {
return _lazyObject.get();
}
public void doSomething() {
Supplier<T> a = _lazyObject; // a is actually the Supplier
// ... but we can access either via the method
T b = getLazyObject();
// or the Supplier:
T c = _lazyObject.get();
// do something...
}
}
However, as per the comments above - one of my main use cases is serializing/de-serializing objects containing lazy fields across JVMs. In this case, after de-serialization, the Supplier will be null. As such, we need to initialize the Supplier after deserialization.
For example, using the most simple approach:
public class MyObject {
private transient Supplier<T> _lazyObject = makeSupplier();
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
in.defaultReadObject();
_lazyObject = makeSupplier();
}
private Supplier<T> makeSupplier() {
return Suppliers.memoize(new Supplier<T>() {
#Override
public Tget() {
return ...; // make T
}
});
}
}

Which method should change the field, when calling a hierarcy of private methods?

When a class' public method needs to call a private method that results in a field being changed, which method should change the field? Is there any common convention for this? Is one approach preferable over the other?
Consider these two code snippets:
public class boolHolder {
private boolean theBool = false;
public void doYourThing() {
// Do a lot of other stuff
setBool();
}
private void setBool() {
// Do a lot of other stuff, justifying a private method for this
this.theBool = true;
}
}
VS
public class boolHolder {
private boolean theBool = false;
public void doYourThing() {
// Do a lot of other stuff
theBool = setBool();
}
private boolean setBool() {
// Do a lot of other stuff, justifying a private method for this
return true;
}
}
These two snipped of course being a very simple case, but I'm sure I'm not the only one ending up with public methods calling a huge tree of private methods. Should the field be set at the end of the branch, or should a value be passed back?
I think it makes more sense that only a single place would set the value of the field, and it should be the last method being called. It makes the code easier to understand. Your first snippet looks much more readable to me.
Here's another snippet which, in my opinion, supports this convention :
Lets say we have an int member with two setters - one accepts an int and the other accepts a String representation of that int (which is used, for example, if we de-serialize an instance from an XML String).
int value;
public void setIntField (String value)
throws SomeException
{
if (value == null)
throw new SomeException();
try {
int val = Integer.parseInt (value);
setIntField (val);
}
catch (NumberFormatException ex) {
throw new SomeException();
}
}
public void setIntField (int value)
throws SomeException ()
{
if (value < MIN_ALLOWED || value > MAX_ALLOWED)
throw new SomeException ();
this.value = value;
}
Apart from renaming theBool and setBool to something more understandable (which I'm going to assume you did eitherway in the real application), I'd go with the first one. Methods with the word set are expected to be setters and not many people will expect a return value.
It doesn't change much, but you can try to use a better naming for your methods: i don't like that you name your second method setBool().
If you write "Do a lot of other stuff, justifying a private method for this" you can try to associate a verb to that stuff you do.
Say you update an account status and upon completion want to signal with the boolean the status, well use something like what you did but call it in a meaningful way, e.g. updateAccount() and either return a true if the update went fine or set it inside:
public class boolHolder {
private boolean accountUpdated = false;
public void doYourThing() {
// Do a lot of preliminary stuff
updateAccount();
}
private void updateAccount() {
// try to update account
// if update went fine
this.accountUpdated = true;
}
}
or
public class boolHolder {
private boolean accountUpdated = false;
public void doYourThing() {
// Do a lot of preliminary stuff
this.accountUpdated = updateAccount();
}
private boolean updateAccount() {
// try to update account
// if error happens, rollback change and set
return false;
// else (update went fine)
return true;
}
}
are both perfectly fine, but make your method tell what they do, since updating the bool is not the main action since you "Do a lot of other stuff, justifying a private method for this".
The value setting inside is more compact if you use a default to false as you did, but the other is more explicit in what it does. So I tend to prefer that: returning a result for you operation.

The pattern of final array instead of non-final variable for boolean flag in inner class

I often have a situation in my Java code when I need to set a boolean flag inside an inner class. It is not possible to use primitive boolean type for that, because inner class could only work with final variables from outside, so I use pattern like this:
// class from gnu.trove is not of big importance, just to have an example
private final TIntIntHashMap team = new TIntIntHashMap();
// ....... code ............
final boolean[] flag = new boolean[]{false};
team.forEachValue(new TIntProcedure() {
#Override
public boolean execute(int score) {
if(score >= VICTORY_SCORE) {
flag[0] = true;
}
return true; // to continue iteration over hash map values
}
});
// ....... code ..............
The pattern of final array instead of non-final variable works well, except it is not look beautiful enough to me. Does someone know better pattern in Java ?
Use AtomicBoolean.
Here's a popular StackOverflow question about this issue: Why are only final variables accessible in anonymous class?
How about having a generic holder class which holds object of any type. In your case, it can hold a Boolean type. Something like:
class Holder<T> {
private T genericObj;
public Holder(T genericObj) {
this.genericObj = genericObj;
}
public T getGenericObj() {
return genericObj;
}
public void setGenericObj(T genericObj) {
this.genericObj = genericObj;
}
}
And use it as:
public class Test {
public static void main(String[] args) throws Exception {
final Holder<Boolean> boolHolder = new Holder<Boolean>(Boolean.TRUE);
new Runnable() {
#Override
public void run() {
boolHolder.setGenericObj(Boolean.FALSE);
}
};
}
}
Of course, this has the usual problems that occur with mutable objects that are shared across threads but you get the idea. Plus for applications where memory requirements are tight, this might get crossed off when doing optimizations in case you have a lot of invocations of such methods. Also, using AtomicReference to swap/set references should take care of use from multiple threads though using it across threads would still be a bit questionable.
There are situations where this is the best pattern.
The only improvement I can suggest is return false when you have found a match.
One problem is that the TIntIntHashMap does not have a fold/reduce method so you have to simulate it using foreach. You could try to write your own class extending TIntIntHashMap adding a reduce method.
Other solution is to just extend TIntProcedure to have a value. Something like:
abstract class TIntProcedureWithValue<T> implements TIntProcedure {
private T accumulator;
public T getValue() {return accumulator;}
}
Then you can pass an instance of this class to foreach, set the internal accumulator instead of the external flag array, and get the resulting value afterwards.
I am not familiar with gnu.trove, but generally it's better for the "algortihm" function to be more specific, leaving less code here.
private final IntIntHashMap team = new IntIntHashMap();
boolean found = team.value().containsMatch(new IntPredicate() {
public boolean is(int score) {
return score >= VICTORY_SCORE;
}
});
(More concise syntax should be available in Java SE 8.)
maybe something like that? (implements or extends... I don't know what is TIntProcedure, unfortunately) :
class FlagResult implements TIntProcedure {
boolean flag = false;
#Override
public boolean execute(int score) {
flag = score >= VICTORY_SCORE;
return !flag;
}
};
FlagResult result = new FlagResult();
team.forEachValue(result);
boolean flag = result.flag;

Mutable boolean field in Java

I need a mutable boolean field in Java (I will return this field via get* method later and it should be possible to modify this field).
Boolean doesn't work because there are no set* methods in the Boolean class (I would say that Boolean is immutable, you can only change the reference, but you can't change the object itself).
I guess I can use Boolean array of size 1. But probably there are more elegant solutions?
Why doesn't Java have such a simple thing?
Immutable classes are easier to work with. They'll never change and there will be no problems with concurrent code. (Basically, there are fewer possibilities to break them.)
If you would like to return a reference to your Boolean value, you can use java.util.concurrent.atomic.AtomicBoolean if you're working with multiple threads or plain old org.apache.commons.lang.mutable.MutableBoolean.
Maybe write yourself a wrapper class
class BooleanHolder {
public boolean value;
}
Or make a generic holder class (which means you will have to use class Boolean instead of primitive boolean):
class Holder<T> {
public T value;
}
You then return the wrapper class instead of the value itself, which allows the value inside the wrapper to be modified.
If you are using Java 5 or higher then use AtomicBoolean
You can use a boolean array
final boolean[] values = { false };
values[0] = true;
What about just using the boolean primitive?
private boolean value;
public void setValue(boolean value) {
this.value = value;
}
public boolean getValue() {
return value;
}
Why not use the boolean primitive ?
e.g.
private boolean myFlag = false;
public void setMyFlag(boolean flag) {
myFlag = flag;
}
Note your getter method can return a Boolean if required, due to the magic of autoboxing. This allows easy interchangeability between using primitives and their object equivalents (e.g. boolean vs. Boolean, or int vs. Integer).
So to address your edited responses re. the methods you have available,
public Object getAttribute(String attributeName)
can be implemented by returning an autoboxed boolean,.
The answer I liked most was from Adam to write your own wrapper class... OK
/* Boolean to be passed as reference parameter */
public class Bool {
private boolean value;
public Bool() {
this.value = false;
}
public boolean is() {
return this.value;
}
public void setTrue() {
this.value = true;
}
public void setFalse() {
this.value = false;
}
}
If you are using Android, you can use the android.util.Mutable* objects which wrap various primitive values. For example, quoting from the SDK source:
public final class MutableBoolean {
public boolean value;
public MutableBoolean(boolean value) {
this.value = value;
}
}
Are you really saying that you want callers to be able to modify the object's boolean value by manipulating what gets returned? So that the object and caller would share a reference to it?
Just so I understand, given:
class OddClass {
private Boolean strangeFlag;
public Object getAttrbiute(String attributeName) {
if (attributeName.equals("strangeflag")) return (Object)strangeFlag;
...
}
}
And then caller does:
Boolean manipulableFlag = (Boolean) myOddClass.getAttrbiute ("strangeflag");
And then later, if caller changes the value of manipulableFlag, you want that change to happen in the OddClass instance, just as though caller had instead used a setAttrbiute method.
Is that what you're asking?
In that case, you'd need a holder class, as suggested by Adam.

Categories

Resources