I am new to using Protocol Buffers and was really surprised why a
compiler option is not available to control how scalar types are
mapped in Java when generating the message objects. I understand the
concept of having a null int in C++ is not possible, but isn't is
really backwards to have to call another method in order to check if a
value has been set in Java? Having a null reference in Java does
exactly this!
In reading the reference docs:
http://code.google.com/apis/protocolbuffers/docs/reference/java-generated.html
The compiler will generate the following accessor methods in both the
message class and its builder:
* bool hasFoo(): Returns true if the field is set.
* int getFoo(): Returns the current value of the field. If the
field is not set, returns the default value.
Why not give protoc another control flag that would map all primitive
data types to their corresponding objects? (i.e. This would just map
a int -> Integer or double -> Double or a long - > Long) This surely
would not break the protocol, but would give a much cleaner and "Java
like" way of programming. I just feel like I am working in Java but
with a "C++ like" interface. Java now has auto-boxing so really if
you like working with int and doubles instead of the Object
counterparts, you would still be okay...
Wouldn't you rather code like a "Java Programmer" by writing:
if(getFoo() != null)
{
// do something with getFoo()
}
instead of:
if(hasFoo())
{
// do something with getFoo()
}
Think of how this works when you are not trying to pass along the data
to another method that already takes an Integer object and that method
is ok with the reference being null.
I rather write:
doSomethingWithFoo(getFoo());
instead of
doSomethingWithFoo(hasFoo() ? getFoo() : null);