Handle Boolean like boolean for Getter/Setter generation - java

We want to achieve that the Boolean are handled like boolean with lombok Getters/Setters when their name starting with an "is"-prefix. Is there a way to do so with lombok?
We always use the "is"-prefix for our member variables in Java (as well in SQL and JavaScript) as a coding convention. With boolean types we are very happy with default lombok behaviour for getters/setters. Now we want to achieve the same generation logic for Booleans as well, but the lombok default is a different between boolean and Boolean.
I tried the following:
#Data
public class BooleanChallenge {
// #Getter #Setter just work fine for boolean
private boolean isSmallBoolean;
// Boolean are handled different
private Boolean isBigBoolean;
#Accessors(fluent = true)
private Boolean isFluentAccessor;
#Accessors(prefix = "is")
private Boolean isWithPrefix;
#Accessors(prefix = "is", fluent = true)
private Boolean isWithPrefixAndFluent;
private void useThoseGetterzAndSetterz() {
this.isSmallBoolean(); // ✔ "is"-prefix for getter
this.setSmallBoolean(true); // ✔ "set"-prefix for setter
this.getIsBigBoolean(); // ❌ "get is"
this.setIsBigBoolean(true); // ❌ "set is"
this.isFluentAccessor(); // ✔
this.isFluentAccessor(true); // ❌ "is"-prefix instead of "get" prefix
this.getWithPrefix(); // ❌ no "is"-prefix
this.setWithPrefix(true); // ✔
this.withPrefixAndFluent(); // ❌
this.withPrefixAndFluent(true); // ❌
}
}

Here is some stuff.
Don't prefix your boolean field.
That is terrible and ridiculous because,
the JavaBean spec states that the getter for a boolean field must be named
isFieldName, which becomes isIsBlammy().
Stop using a terrible practice as your convention.
It seems that terrible is here to stay.
Also, Lombok recognizes terrible and generates correct getter methods
(isBlammy() in the example).
The correct (JavaBean spec compliant) name of the getter for a Boolean
(note the capital 'B') field is getFieldName.
this is intentional and is not a mistake.
Lombok generates compliant getter methods.
Java autoboxes and autounboxes between primatives and non-primatives
(in this case, between boolean and Boolean).
When you have a getter that returns boolean and you assign the return value
to a Boolean variable,
Java automatically generates the correct Boolean value for the assignment.
The only time you need Boolean is when null is a valid value (i.e. can happen).
If fluentAccessor can never be null,
change it to be boolean an autoboxing will solve your issue.
When null is a legit possible value,
Boolean is appropriate and boolean is not an option.
Additional stuff
Since changing the terrible naming convention is not an option,
you must create the getter yourself.
Here is an example:
// Disable the Lombok getIsHooty method creation.
#Getter(AccessLevel.NONE)
private Boolean isHooty;
public Boolean isHooty()
{
return isHooty;
}

Here are my 50 cents: boolean is binary/dual-state, whereas Boolean is ternary/tri-state, as it takes true, false and null, or to be more precise, Boolean.TRUE, Boolean.FALSE, any self-created object, and null.
When one has a function isSomething you expect it to return either true or false, not null. So a possible null value might screw something up big-time.
That being said, I cannot really help you with your actual problem. What I can suggest is that you enhance the Lombok library so that it creates functions that convert the Boolean return values into booleans, with some default annotation for default-if-null and default false-if-null behavior. But this approach with the 'hidden conversion' already looks quite hackish. A bit much just to keep up coding conventions.

Related

How to initialize booleans?

I am trying to write a boolean condition for genre fiction or non fiction for my program. However there is something wrong?
For the instance variable:
private boolean fiction, nonFiction;
or
private boolean Genre;
that compiles fine, but I don't know how to initialise this?
Genre = "";
No idea, I am a beginner to Java still learning.
Also I need to create a method which will give me true or false depending the input, can pointers be given so I can note how to create this method?
Java instance variables are automatically initialized either 0 (or equivalent) for numbers, null for objects, or false for booleans. So you don't need to explicitly do it. But you can, but you must provide something valid. eg.:
private boolean Genre = false;
You need to read up more in order to create functions, but the general signature should look like
<access qualifier> <return type> <method name>(parmeters ..){
// logic here
return <something with return type>;
}
eg.:
public boolean myFunction(int someparameter, int someotherparameter){
return true;
}
but I don't know how to initialise this?
boolean fiction = true;
There is no need to initialize boolean member to false, because that's its default value, so this is enough:
boolean fiction; // fiction is initialized automatically to false
also I need to create a method which will give me true or false depending the input, can pointers be given so I can note how to create this method?
boolean function(Object input) {
if (something) {
return true;
}
return false;
}

Passing and setting booleans - Java/Android

I have a class like so:
public class Achievements(){
boolean score100_Earned_Offline;
boolean score1000_Earned_Offline;
final String score100 = "xxxxxxxxxx" //where xxxxxxxxxx would be replaced with the achievement's Google Play Games ID
final String score1000 = "xxxxxxxxxx" //where xxxxxxxxxx would be replaced with the achievement's Google Play Games ID
}
In my Game class, I check the state of the achievements every tick and act on them as necessary like so (assume all methods to be valid and defined - this is cut down to provide the code necessary to the question).......
public class Game(){
public void checkAchievements(Achievements achievements){
if (score>=100){
unlockAchievement(achievements.score100, achievements.score100_Earned_Offline);
}
if (score>1000){
unlockAchievement(achievements.score100, achievements.score1000_Earned_Offline);
}
}
public void unlockAchievement(String achievementToUnlock, boolean thisAchievementOfflineFlag){
//If user is signed in, then we are ready to go, so go ahead and unlock the relevant achievement....
if (checkSignedIn()){
Games.Achievements.unlock(getApiClient(), achievementToUnlock);
//Otherwise, I want to do is set the relevant flag to true so it can be checked when the user does eventually log in
else{
thisAchievementOfflineFlag=true;
}
}
}
Pass by value
In the 'unlockAchievement' method, the boolean 'thisAchievementOfflineFlag' does get set to true if the user is not logged in, however, it doesn't effect the actual boolean that was originally sent into the method (which as you can see is defined in my 'Achievements' class). I'm guessing this is because Java is Pass by Value and is therefore, creating a local copy of the variable which is valid inside the method only. I did try using Boolean too (wrapper class) but got the same results.
Other ways to achieve this?
I've currently got it set up so I can define each achievement as an enum so each one will have it's own copy of the boolean flag. However, I'm aware that it's not recommended to use enums in Android so if there is a better way that I am missing, I would rather avoid them.
Please note that I don't want to use if checks or switch statements as this is taking place in a game-loop.
Any suggestions appreciated
This is all because Java's implementation of Boolean (also, for example String) is immutable for safety reasons. You can see it here: http://www.explain-java.com/is-string-mutable-in-java-why-wrapper-classes-immutable-in-java/
You can solve your problem by introducing an object wrapper for that boolean:
public class BooleanWrapper {
private boolean value;
public void set(boolean value) {
this.value = value;
}
public boolean get() {
return value;
}
}
Now, this object reference will be passed by value but will still point to the same BooleanWrapper object on the heap. You can simply use getters and setters to change the inner boolean value.
Then your code would become:
public void unlockAchievement(String achievementToUnlock, BooleanWrapper thisAchievementOfflineFlag){
if (checkSignedIn()){
Games.Achievements.unlock(getApiClient(), achievementToUnlock);
else {
thisAchievementOfflineFlag.set(true);
}
}
Java is pass-by-value:
When you pass boolean then you for sure passed it by value, while it is a primitive type. When you pass Boolean, you would think it's an object and that you can change it's state, but actually you cannot because Boolean is implemented as an immutable object (as already said). You can confirm this just by reading the code of java.lang.Boolean.
But if you create your own wrapper class, and in a sense, you control whether you implement it in immutable or mutable way. BooleanWrapper I wrote lets you change the state of that object. And when you pass an object such as this one to the method, it's passed by value. That means that another reference is created, but it points to the same object on heap (see image below).
You could use an AtomicBoolean, which will have pass-by-reference semantics.

boolean (Boolean) - getter is vs get

It looks like everyone says that right getter for:
primitive boolean -> getter is
object Boolean -> getter get
Example:
public class Test {
private boolean primitive;
private Boolean object;
public boolean isPrimitive() {
return primitive;
}
public Boolean getObject() {
return object;
}
//..
}
Question:
Is there any spec or document that states this is correct and this is the way to specify getters for boolean values? Or this is only a common assumption?
I'm asking becouse for example wsimport generates getter is for Boolean object. Is this a tool bug, or this is allowed and correct?
In the other hand some framweorks don't work properly with such getters. For example JSF (EL) or Dozer.
The getter method for the field boolean myField is getMyfield() or isMyField() (it's up to the user to choose). I personally use the second format, as many source code generating tools do.
This format is a standard, it is defined in the JavaBeans specification. See the section 8.3.2 of this documentation:
http://download.oracle.com/otndocs/jcp/7224-javabeans-1.01-fr-spec-oth-JSpec/
Quote from the docs:
In addition, for boolean properties, we allow a getter method to match the pattern:
public boolean is<PropertyName>();
The documentation doesn't talk about the primitive wrappers like the Boolean class.
// "is" used because the value can be either true or false. It's like asking isTrue?
public boolean isPrimitive() {
return primitive;
}
// "get" is used because the value returned can be either true, false or null.
// So, the third state 'null' makes you wonder if 'is' should be used or 'get'.
// "get" is more appropriate as Boolean can also have null.
public Boolean getObject() {
return object;
}
But frankly, it's left to the developer. There's nothing "wrong" in using getBoolean() on a boolean value (is makes more sense, that's it).

Guava Optional. How to use the correct

I have a class
private class TouchCommand {
private int action;
private int x;
private int y;
...
When the command is executed, it is necessary to verify the field values ​​- null / not null, and depending on it to produce longitudinal action. I want to use Options from Google Guava.
Which solution is right?
this:
public boolean executeCommand() {
Optional<Integer> optionalAction = Optional.fromNullable(action);
...
or:
private class TouchCommand {
private Optional<Integer> action;
private Optional<Integer> x;
private Optional<Integer> y;
...
Given that the call to parseAction may also return a null (or absent):
TouchCommand touchCommand = new TouchCommand();
touchCommand.mAction = parseAction(xmlParser.getAttributeValue(namespace, "action"));
...
Questions:
whether or not to do so: the method parseAction (and similar) returns Optional ?
whether or not to do so: the field of class objects Optional ?
whether or not to do so: when checking the fields of the class (assuming that they can be null) to convert them into objects Optional ?
Thx.
Guava contributor here...
Any or all of these things are fine, but some of them may be overkill.
Generally, as discussed in this StackOverflow answer, Optional is primarily used for two things: to make it clearer what you would've meant by null, and in method return values to make sure the caller takes care of the "absent" case (which it's easier to forget with null). We certainly don't advocate replacing every nullable value with an Optional everywhere in your code -- we certainly don't do that within Guava itself!
A lot of this will have to be your decision -- there's no universal rule, it's a relatively subjective judgement, and I don't have enough context to determine what I'd do in your place -- but based on what context you've provided, I'd consider making the methods return Optional, but probably wouldn't change any of the other fields or anything.

(no) Properties in Java?

So, I have willfully kept myself a Java n00b until recently, and my first real exposure brought about a minor shock: Java does not have C# style properties!
Ok, I can live with that. However, I can also swear that I have seen property getter/setter code in Java in one codebase, but I cannot remember where. How was that achieved? Is there a language extension for that? Is it related to NetBeans or something?
There is a "standard" pattern for getters and setters in Java, called Bean properties. Basically any method starting with get, taking no arguments and returning a value, is a property getter for a property named as the rest of the method name (with a lowercased start letter). Likewise set creates a setter of a void method with a single argument.
For example:
// Getter for "awesomeString"
public String getAwesomeString() {
return awesomeString;
}
// Setter for "awesomeString"
public void setAwesomeString( String awesomeString ) {
this.awesomeString = awesomeString;
}
Most Java IDEs will generate these methods for you if you ask them (in Eclipse it's as simple as moving the cursor to a field and hitting Ctrl-1, then selecting the option from the list).
For what it's worth, for readability you can actually use is and has in place of get for boolean-type properties too, as in:
public boolean isAwesome();
public boolean hasAwesomeStuff();
I am surprised that no one mentioned project lombok
Yes, currently there are no properties in java. There are some other missing features as well.
But luckily we have project lombok that is trying to improve the situation. It is also getting more and more popular every day.
So, if you're using lombok:
#Getter #Setter int awesomeInteger = 5;
This code is going to generate getAwesomeInteger and setAwesomeInteger as well. So it is quite similar to C# auto-implemented properties.
You can get more info about lombok getters and setters here.
You should definitely check out other features as well.
My favorites are:
val
NoArgsConstructor, RequiredArgsConstructor, AllArgsConstructor
Logs!
Lombok is well-integrated with IDEs, so it is going to show generated methods like if they existed (suggestions, class contents, go to declaration and refactoring).
The only problem with lombok is that other programmers might not know about it. You can always delombok the code but that is rather a workaround than a solution.
"Java Property Support" was proposed for Java 7, but did not make it into the language.
See http://tech.puredanger.com/java7#property for more links and info, if interested.
The bean convention is to write code like this:
private int foo;
public int getFoo() {
return foo;
}
public void setFoo(int newFoo) {
foo = newFoo;
}
In some of the other languages on the JVM, e.g., Groovy, you get overridable properties similar to C#, e.g.,
int foo
which is accessed with a simple .foo and leverages default getFoo and setFoo implementations that you can override as necessary.
public class Animal {
#Getter #Setter private String name;
#Getter #Setter private String gender;
#Getter #Setter private String species;
}
This is something like C# properties. It's http://projectlombok.org/
You may not need for "get" and "set" prefixes, to make it look more like properties, you may do it like this:
public class Person {
private String firstName = "";
private Integer age = 0;
public String firstName() { return firstName; } // getter
public void firstName(String val) { firstName = val; } // setter
public Integer age() { return age; } // getter
public void age(Integer val) { age = val; } //setter
public static void main(String[] args) {
Person p = new Person();
//set
p.firstName("Lemuel");
p.age(40);
//get
System.out.println(String.format("I'm %s, %d yearsold",
p.firstName(),
p.age());
}
}
Most IDEs for Java will automatically generate getter and setter code for you if you want them to. There are a number of different conventions, and an IDE like Eclipse will allow you to choose which one you want to use, and even let you define your own.
Eclipse even includes automated refactoring that will allow you to wrap a property up in a getter and setter and it will modify all the code that accesses the property directly, to make it use the getter and/or setter.
Of course, Eclipse can only modify code that it knows about - any external dependencies you have could be broken by such a refactoring.
My Java experience is not that high either, so anyone feel free to correct me. But AFAIK, the general convention is to write two methods like so:
public string getMyString() {
// return it here
}
public void setMyString(string myString) {
// set it here
}
From Jeffrey Richter's book CLR via C#: (I think these might be the reasons why properties are still not added in JAVA)
A property method may throw an exception; field access never throws an exception.
A property cannot be passed as an out or ref parameter to a method; a field can.
A property method can take a long time to execute; field access always completes
immediately. A common reason to use properties is to perform thread synchronization,
which can stop the thread forever, and therefore, a property should not be
used if thread synchronization is required. In that situation, a method is preferred.
Also, if your class can be accessed remotely (for example, your class is derived from
System.MarshalByRefObject), calling the property method will be very slow, and
therefore, a method is preferred to a property. In my opinion, classes derived from
MarshalByRefObject should never use properties.
If called multiple times in a row, a property method may return a different value each
time; a field returns the same value each time. The System.DateTime class has a readonly
Now property that returns the current date and time. Each time you query this
property, it will return a different value. This is a mistake, and Microsoft wishes that
they could fix the class by making Now a method instead of a property. Environment’s
TickCount property is another example of this mistake.
A property method may cause observable side effects; field access never does. In other
words, a user of a type should be able to set various properties defined by a type in
any order he or she chooses without noticing any different behavior in the type.
A property method may require additional memory or return a reference to something
that is not actually part of the object’s state, so modifying the returned object has no
effect on the original object; querying a field always returns a reference to an object
that is guaranteed to be part of the original object’s state. Working with a property
that returns a copy can be very confusing to developers, and this characteristic is frequently
not documented.
If you're using eclipse then it has the capabilities to auto generate the getter and setter method for the internal attributes, it can be a usefull and timesaving tool.
I'm just releasing Java 5/6 annotations and an annotation processor to help this.
Check out http://code.google.com/p/javadude/wiki/Annotations
The documentation is a bit light right now, but the quickref should get the idea across.
Basically it generates a superclass with the getters/setters (and many other code generation options).
A sample class might look like
#Bean(properties = {
#Property(name="name", bound=true),
#Property(name="age,type=int.class)
})
public class Person extends PersonGen {
}
There are many more samples available, and there are no runtime dependencies in the generated code.
Send me an email if you try it out and find it useful!
-- Scott
There is no property keyword in java (like you could find it in C#) the nearest way to have 1 word getter/setter is to do like in C++:
public class MyClass
{
private int aMyAttribute;
public MyClass()
{
this.aMyAttribute = 0;
}
public void mMyAttribute(int pMyAttributeParameter)
{
this.aMyAttribute = pMyAttributeParameter;
}
public int mMyAttribute()
{
return this.aMyAttribute;
}
}
//usage :
int vIndex = 1;
MyClass vClass = new MyClass();
vClass.mMyAttribute(vIndex);
vIndex = 0;
vIndex = vClass.mMyAttribute();
// vIndex == 1
As previously mentioned for eclipse, integrated development environment (IDE) often can create accessor methods automatically.
You can also do it using NetBeans.
To create accessor methods for your class, open a class file, then Right-click anywhere in the source code editor and choose the menu command Refactor, Encapsulate Fields.
A dialog opens. Click Select All, then click Refactor.
Voilà,
Good luck,
For me the problem is two fold:
All these extra methods {get*/set*} cluttering up the class code.
NOT being able to treat them like properties:
public class Test {
private String _testField;
public String testProperty {
get {
return _testField;
}
set {
_testField = value;
}
}
}
public class TestUser {
private Test test;
public TestUser() {
test = new Test();
test.testProperty = "Just something to store";
System.out.printLn(test.testProperty);
}
}
This is the sort of easy assignment I would like to get back to using. NOT having to use 'method' calling syntax. Can anyone provide some answers as to what happened to Java?
I think that the issue is also about the unnecessary clutter in the code, and not the 'difficulty' of creating the setters/getters. I consider them as ugly-code. I like what C# has. I don't understand the resistance to adding that capability to Java.
My current solution is to use 'public' members when protection is not required:
public class IntReturn {
public int val;
}
public class StringReturn {
public String val;
}
These would be used to return value from say a Lambda:
StringReturn sRtn = new StringReturn()
if(add(2, 3, sRtn)){
System.out.println("Value greater than zero");
}
public boolean add(final int a, final int b, final StringReturn sRtn){
int rtn = a + b;
sRtn.val = "" + rtn;
return rtn > 0; // Just something to use the return for.
}
I also really don't like using a method call to set or get an internal value from a class.
If your information is being transferred as 'immutable', then the new Java record could be a solution. However, it still uses the setter/getter methodology, just without the set/get prefixes.

Categories