0

We are using AutoBeans to create our Pojo objects for use in RPC-Calls. What is the recommended approach for the Pojo to have a default value or other class initialization?

For example

 public interface SamplePojo {
        // should default to 5
        int getSampleProperty();
        void setSampleProperty(int sampleProperty);
    }


    public interface ModelFactory extends AutoBeanFactory {
        AutoBean<SamplePojo> getSamplePojo();   
    }

And SamplePojo has a int property that we always want to default to 5.

Kenoyer130
  • 6,874
  • 9
  • 51
  • 73

2 Answers2

1

AutoBeans should be seen as low-level, mapping straight to/from JSON. With that in mind, you don't want getSampleProperty() to be 5, you rather want to detect the absence of specific value for the property and use 5 in that case.

So, if 0 (the default value of an int) is not an acceptable value for the property, then simply "use 5 if the property is 0". Otherwise, change the return type to Integer and "use 5 if the property is null".

Thomas Broyer
  • 64,353
  • 7
  • 91
  • 164
  • This doesn't address the problem that we want the initialization logic centralized. In our case we don't want every place that the SamplePojo is used to have to repeat the "use 5 if the property is null". – Kenoyer130 Oct 22 '12 at 13:16
  • 1
    And yet, AutoBeans are hardly more than a type-checked `Map`; so either explicitly put a 5 each time you create such an AutoBean (i.e. use a factory method that hides the AutoBeanFactory and adds the initialization logic), but then you'll explicitly send a 5 over the wire; or somehow hide the AutoBean and/or its `getSampleProperty` (did I say AutoBeans are a low-level API?) to implement the "use 5 if the property is null" behavior (and have optimized wire payload, without the `sampleProperty` unless it's explicitly been set). If you know protobuf, AutoBean heavily borrows from them: low-level! – Thomas Broyer Oct 22 '12 at 14:47
0

Would this work?

public interface SamplePojo {
        // should default to 5
        int getSampleProperty();
        void setSampleProperty(int sampleProperty);
    }

public class SamplePojoImpl implements SamplePojo{
    private int sampleProperty = 5
    // getters/setters
    int getSampleProperty(){ return sampleProperty;}
    void setSampleProperty(int sampleProperty){this.sampleProperty = sampleProperty;}

}

public interface ModelFactory extends AutoBeanFactory {
    AutoBean<SamplePojo> getSamplePojo(SamplePojoImpl samplePojo );   
}
Kenoyer130
  • 6,874
  • 9
  • 51
  • 73