• Post Reply Bookmark Topic Watch Topic
  • New Topic

How to avoid assigning null to a object  RSS feed

 
Kumara SharmaS
Greenhorn
Posts: 21
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi All,

How to handle this scenario: where a POJO bean which has a Map<Integer, Integer> is initialized during POJO instantiation should never be assigned a null value by rest of the code(even assign a null value to one of the keys in the map).

Reason being once its null, we cannot persist it to the database. The object should contain default values in such cases and persistence should happen anyways(If something in the map is updated).

Cannot use final with that field, because it can be updated later in other places.

How can we enforce this rule?
 
Tudor Raneti
Ranch Hand
Posts: 145
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Make a check in the setter. If null, assign a default, if not, assign the incoming value?
 
Campbell Ritchie
Marshal
Posts: 56529
172
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What’s a POJO bean? I thought beans could not be POJOs.

Keep all access to that Map private. Make all methods which “put” anything in that Map check for nullity beforehand, with if (key != null && value != null)... or similar
I don’t like the idea of entering default objects instead of nulls. I would prefer to see a NullPointerException thrown if you attempt to put a null.
You could use older types of Map which don’t permit nulls.
 
Campbell Ritchie
Marshal
Posts: 56529
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Have I understood the question correctly?
 
Jeff Verdegan
Bartender
Posts: 6109
6
Android IntelliJ IDE Java
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Kumara SharmaS wrote:Reason being once its null, we cannot persist it to the database.


You can store null to a DB. PreparedStatement has a setNull() method. It may still not make semantic sense for you to do so, but it is allowed.

Also, regarding the title of your thread, "How to avoid assigning null to a object", note that objects are never null in Java. Only references can be null. The distinction between a reference and the object it points to (if that reference is not null) is an important one to know and keep in mind.

 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!