Weak requirements: how to make sure an object is initialized - java

I want to write bean-friendly classes. I have observed a tendency (mostly with beans) to move required parameters to setters from the constructor (and use an init() method when done setting up the initial state).
This method concerns me because I want my classes to be usable without a bean infrastructure, just as Java objects. As I imagine I'd have to check for the proper state of the object in every method assert style.
Quick demo for the above:
class A {
public int x;
public int y;
private int sum;
private boolean initialized = false;
public void init() {
sum = x + y;
initialized = true;
}
private void initCheck() {
if (!initialized) {
throw new IllegalStateException("Uninitialized object.");
}
}
public int getXMulSum() {
initCheck();
return x * sum;
}
public int getYMulSum() {
initCheck();
return y * sum;
}
}
Is there a better practice?

Given that you don't want to use a framework...
If a class is not fit for use until it has been initialised, I would prefer using constructors. Don't be swayed by blogs and books. Constructors are there for this purpose. Using constructors also removes any requirement to synchronize your code.
One reason I can see for not using constructors, is if there is a lot of initialisation code and perhaps dependencies external to the class. If too much logic resides in a constructor, then it can make your application brittle and difficult to recover from Exceptions in the constructor. In this case you have the option of using a Factory class that will handle the instantiation and initialisation of the bean. This way, the calling code only ever receives a bean that is ready and fit for use.
A good pattern to use is the Builder pattern where you have a long list of constructor arguments.
"I have observed a tendency (mostly with beans) to move required parameters to setters from the constructor"
The main reason for this testability. If you can test a feature of the bean without having to initialise "expensive" dependencies, than not having them in the constructor is of benefit. Having said that, I would also argue that if this is an issue, you probably have too much functionality in your bean and you'd be better off breaking it up. As suggested by the Single responsibility principle.

The setters are more general than constructor arguments because they allow you to handle circular dependencies.
If you don't have circular dependencies, I'd recommend staying with constructor arguments, exacly for the purpose of enforsing the dependencies.
However, if at all possible, do not put any logic into constructor. As Brad said, it makes the application brittle. The entire Spring environment may not be available during constructor.
Try to design in a way that allows the constructor to simply remember the references for later use in the real methids. Avoid init() method if you can.

Related

Java Annotation and Processor to mark a method as so it can be called once and only once?

I need to be able to mark methods so that they throw a RuntimeException if they are called more than once.
I am trying to enforce some single assignment semantics and the number of parameters to my class is too large to put in a single constructor and I need to be able to make these classes JAXB aware as well, so the objects need to be mutable but I want to enforce single assignment semantics.
I am pretty sure I can do this with Aspects, but I would really like to be able to use my own Annotations processor instead.
I know how to do this with Decorators in Python.
How do I write an Annotation processor that can intercept calls to the annotated method at runtime and not just at compile time?
I think I am on to something with with Dynamic Proxies intercepting the method calls, I just need to figure out how to integrate them with my Annotation processor.
Dynamic Proxies require you to use an Interface, that is way to cumbersome, I have a CGLib MethodInterceptor working now, much less requirements on what gets intercepted and decorated, at the expense of adding a dependency.
Nope, there's nothing ready-to-use. And AspectJ seems the only way to make it work in a more general manner. As JB Nizet noted - the annotation should have a parser to parse it.
However, I would advise for a better and simpler solution - the Builder pattern. What does it look like:
you have a FooBuilder (it may also be a static inner class) which is mutable and has a setter and getter for each of the fields
FooBuilder has a build() method that returns an instance of Foo
Foo has a constructor that takes only FooBuilder, and you assign each field there.
That way:
Foo is immutable, which is your end goal
It is easy to use. You only set the fields that you need. Something like:
Foo foo = new Foo.FooBuilder().setBar(..).setBaz(..).build();
That way the builder can be JAXB-aware. For example:
FooBuilder builder = (FooBuilder) unmarshaller.unmarshal(stream);
Foo foo = builder.build();
JAXB objects need to be mutable, and your requirement is an immutable object. Hence the builder comes handy to bridge that.
This question shows some resemblance with question Applying CGLib Proxy from a Annotation Processor.
If you want to be able to change the behavior of the original source code in an annotation processor have a look at how http://projectlombok.org/ achieves this. The only downside IMO is that lombok relies on com.sun.* classes.
Since I need this kind of stuff myself I wonder if someone knows of a better way to achieve this, still using annotation processors.
You can configure JAXB to use field (instance variable) access using #XmlAccessorType(XmlAccessType.FIELD). This will allow you to do what you need to with the set method:
http://blog.bdoughan.com/2011/06/using-jaxbs-xmlaccessortype-to.html
You can also use JAXB's XmlAdapter mechanism to support immutable objects:
http://blog.bdoughan.com/2010/12/jaxb-and-immutable-objects.html
Instead of using an annotation you can use.
assert count++ != 0;
You would need one counter per method.
I had a similar requirement. Long story short when you inject components in Spring the cyclic dependency situation like A depends on B and B depends on A is perfectly fine, but you need to inject these components as fields or setters. Constructor injection causes a stack overflow. Therefore I had to introduce a method init() for these components, which unlike constructors might be erroneously called more than once. Needless to say boilerplate code like:
private volatile boolean wasInit = false;
public void init() {
if (wasInit) {
throw new IllegalStateException("Method has already been called");
}
wasInit = true;
logger.fine("ENTRY");
...
}
started to emerge everywhere. Since this is nowhere close to being a critical spot of the application, I made a decision to introduce an elegant thread-safe one-liner solution favoring conciseness over speed:
public class Guard {
private static final Map<String, Object> callersByMethods = new ConcurrentHashMap<String, Object>();
public static void requireCalledOnce(Object source) {
StackTraceElement[] stackTrace = new Throwable().getStackTrace();
String fullClassName = stackTrace[1].getClassName();
String methodName = stackTrace[1].getMethodName();
int lineNumber = stackTrace[1].getLineNumber();
int hashCode = source.hashCode();
// Builds a key using full class name, method name and line number
String key = new StringBuilder().append(fullClassName).append(' ').append(methodName).append(' ').append(lineNumber).toString();
System.out.println(key);
if (callersByMethods.put(key, source) != null) {
throw new IllegalStateException(String.format("%s#%d.%s() was called the second time.", fullClassName, hashCode, methodName));
}
}
}
Now, since I prefer building applications within DI frameworks it might sound natural to declare Guard as a component, then inject it, and call an instance method requireCalledOnce instead. But due to its universal flavor, static reference yields more sense. Now my code looks like this:
private void init() {
Guard.requireCalledOnce(this);
...
}
and here is an exception upon the second invocation of init of the same object:
Exception in thread "main" java.lang.IllegalStateException: my.package.MyComponent#4121506.init() was called the second time.
at my.package.Guard.requireCalledOnce(Guard.java:20)
at my.package.MyComponent.init(MyComponent.java:232)
at my.package.MyComponent.launch(MyComponent.java:238)
at my.package.MyComponent.main(MyComponent.java:48)

Is it a good or bad practice to call instance methods from a java constructor?

There are several different ways I can initialize complex objects (with injected dependencies and required set-up of injected members), are all seem reasonable, but have various advantages and disadvantages. I'll give a concrete example:
final class MyClass {
private final Dependency dependency;
#Inject public MyClass(Dependency dependency) {
this.dependency = dependency;
dependency.addHandler(new Handler() {
#Override void handle(int foo) { MyClass.this.doSomething(foo); }
});
doSomething(0);
}
private void doSomething(int foo) { dependency.doSomethingElse(foo+1); }
}
As you can see, the constructor does 3 things, including calling an instance method. I've been told that calling instance methods from a constructor is unsafe because it circumvents the compiler's checks for uninitialized members. I.e. I could have called doSomething(0) before setting this.dependency, which would have compiled but not worked. What is the best way to refactor this?
Make doSomething static and pass in the dependency explicitly? In my actual case I have three instance methods and three member fields that all depend on one another, so this seems like a lot of extra boilerplate to make all three of these static.
Move the addHandler and doSomething into an #Inject public void init() method. While use with Guice will be transparent, it requires any manual construction to be sure to call init() or else the object won't be fully-functional if someone forgets. Also, this exposes more of the API, both of which seem like bad ideas.
Wrap a nested class to keep the dependency to make sure it behaves properly without exposing additional API:class DependencyManager {
private final Dependency dependency;
public DependecyManager(Dependency dependency) { ... }
public doSomething(int foo) { ... }
}
#Inject public MyClass(Dependency dependency) {
DependencyManager manager = new DependencyManager(dependency);
manager.doSomething(0);
}
This pulls instance methods out of all constructors, but generates an extra layer of classes, and when I already had inner and anonymous classes (e.g. that handler) it can become confusing - when I tried this I was told to move the DependencyManager to a separate file, which is also distasteful because it's now multiple files to do a single thing.
So what is the preferred way to deal with this sort of situation?
Josh Bloch in Effective Java recommends using a static factory method, although I can't find any argument for cases like this. There is, however, a similar case in Java Concurrency in Practice, specifically meant to prevent leaking out a reference to this from the constructor. Applied to this case, it would look like:
final class MyClass {
private final Dependency dependency;
private MyClass(Dependency dependency) {
this.dependency = dependency;
}
public static createInstance(Dependency dependency) {
MyClass instance = new MyClass(dependency);
dependency.addHandler(new Handler() {
#Override void handle(int foo) { instance.doSomething(foo); }
});
instance.doSomething(0);
return instance;
}
...
}
However, this may not work well with the DI annotation you use.
It also messes badly with inheritance. If your constructor is being called in the chain to instantiate a subclass of your class, you may call a method which is overridden in the subclass and relies on an invariant that is not established until the subclass constructor has been run.
You'd want to be careful about using instance methods from within the constructor, as the class has not been fully constructed yet. If a called method uses a member that has not yet been initialized, well, bad things will happen.
You could use a static method that takes the dependency and constructs and return a new instance, and mark the constructor Friend. I'm not sure Friend exists in java though (is it package protected.) This might not be the best way though. You could also use another class that is a Factory for creating MyClass.
Edit: Wow another posted just suggested this same exact thing. Looks like you can make constructors private in Java. You can't do that in VB.NET (not sure about C#)... very cool...
Yeah, it's actually illegal, It really shouldn't even compile (but I believe it does)
Consider the builder pattern instead (and lean towards immutable which in builder pattern terms means that you can't call any setter twice and can't call any setter after the object has been "used"--calling a setter at that point should probably throw a runtime exception).
You can find the slides by Joshua Bloch on the (new) Builder pattern in a slide presentation called "Effective Java Reloaded: This Time It's for Real", for example here:
http://docs.huihoo.com/javaone/2007/java-se/

When to use getInstanceOf instead of constructor

Back couple of months ago I attended a presentation hosted by two representative of an independent software development company. It was mainly about good software design and practices.
The two guys were talking mainly about Java and I remember them saying, that in some circumstances it is very good practice to use getInstanceOf() instead of the constructor. It had something to do with making always calling getInstanceOf() from different classes rather than constructor and how it was it is much better approach on larger scale projects.
As you can see I cannot remember much from it now :/ but I remember that the arguments that they used were really convincing. I wonder if any of you ever came across such a design and when, would you say, is it useful? Or do you think it isn't at all?
Consider static factory methods instead of constructors—Joshua Bloch
They were probably talking about the static factory method pattern (and not the reflection API method for dynamically creating objects).
There at several advantages of a method such as getInstanceOf() over a constructor and using new. The static factory method can...
Choose to create a different sub-class of the main class if that is desirable in certain cases (based on environmental conditions, such as properties and other objects/singletons, or method parameters).
Choose to return an existing object instead of creating one. For an example of this, see Boolean.valueOf(boolean) in the Java API.
Do the same thing as the constructor - just return a new instance of the class itself.
Provide many different kinds of ways to construct a new object and name those methods so they are less confusing (e.g. try this with constructors and you soon have many different overloads). Sometimes this is not even possible with constructors if you need to be able to create an instance two different ways but only need the same type of parameters. Example:
// This class will not compile!
public class MyClass {
public MyClass(String name, int max) {
//init here
}
public MyClass(String name, int age) {
// init here
}
}
// This class will compile.
public class MyClass2 {
private MyClass2() {
}
public static MyClass2 getInstanceOfMax(String name, int max) {
MyClass2 m2 = new MyClass2();
// init here
return m2;
}
public static MyClass2 getInstanceOfAge(String name, int age) {
MyClass2 m2 = new MyClass2();
// init here
return m2;
}
}
Do any combination of the above.
And, on top of all that it hides the detail of instantiating an instance from other classes and so can be varied in the future (construction encapsulation).
A constructor can only ever create a new instance of an object of the exact type requested. It cannot be varied later.
Some disadvantages of this pattern are:
The factory methods are static so cannot be inherited in sub-classes; a parent constructor is easily accessible to sub-classes.
The factory method names can vary widely and this could be confusing for some (new) developers.
You also asked for personal experience. Yes, I frequently use both patterns. For most classes constructor but when there are much more advanced needs then I use the static factory. I also work on projects in other languages (proprietary, but similar to Java) where this form of construction is mandated.
I suspect you mean the newInstance method on the Class class. You would invoke it like this: MyClass foo = MyClass.newInstance();
This form of object instantiation is popular in creational patterns; it's useful when you want to specify the concrete, runtime type of an object externally, such as in a properties or XML file.
If Drew is right, newInstance() is part of the Java Reflection API. So it is not as natural as using a constructor.
Why it would be recommended to use it on a large project may come with the fact that it leads to Java Bean programming style and clearly makes the creation of the object something particular. On large project, creating object shouldn't be a cross-cutting concern but rather a clearly identified responsibility, often from one source / factory. But IMHO, you get all of those advantages and many more with IoC pattern.

Constructor overloading in Java - best practice

There are a few topics similar to this, but I couldn't find one with a sufficient answer.
I would like to know what is the best practice for constructor overloading in Java. I already have my own thoughts on the subject, but I'd like to hear more advice.
I'm referring to both constructor overloading in a simple class and constructor overloading while inheriting an already overloaded class (meaning the base class has overloaded constructors).
Thanks :)
While there are no "official guidelines" I follow the principle of KISS and DRY. Make the overloaded constructors as simple as possible, and the simplest way is that they only call this(...). That way you only need to check and handle the parameters once and only once.
public class Simple {
public Simple() {
this(null);
}
public Simple(Resource r) {
this(r, null);
}
public Simple(Resource r1, Resource r2) {
// Guard statements, initialize resources or throw exceptions if
// the resources are wrong
if (r1 == null) {
r1 = new Resource();
}
if (r2 == null) {
r2 = new Resource();
}
// do whatever with resources
}
}
From a unit testing standpoint, it'll become easy to test the class since you can put in the resources into it. If the class has many resources (or collaborators as some OO-geeks call it), consider one of these two things:
Make a parameter class
public class SimpleParams {
Resource r1;
Resource r2;
// Imagine there are setters and getters here but I'm too lazy
// to write it out. you can make it the parameter class
// "immutable" if you don't have setters and only set the
// resources through the SimpleParams constructor
}
The constructor in Simple only either needs to split the SimpleParams parameter:
public Simple(SimpleParams params) {
this(params.getR1(), params.getR2());
}
…or make SimpleParams an attribute:
public Simple(Resource r1, Resource r2) {
this(new SimpleParams(r1, r2));
}
public Simple(SimpleParams params) {
this.params = params;
}
Make a factory class
Make a factory class that initializes the resources for you, which is favorable if initializing the resources is a bit difficult:
public interface ResourceFactory {
public Resource createR1();
public Resource createR2();
}
The constructor is then done in the same manner as with the parameter class:
public Simple(ResourceFactory factory) {
this(factory.createR1(), factory.createR2());
}
Make a combination of both
Yeah... you can mix and match both ways depending on what is easier for you at the time. Parameter classes and simple factory classes are pretty much the same thing considering the Simple class that they're used the same way.
I think the best practice is to have single primary constructor to which the overloaded constructors refer to by calling this() with the relevant parameter defaults. The reason for this is that it makes it much clearer what is the constructed state of the object is - really you can think of the primary constructor as the only real constructor, the others just delegate to it
One example of this might be JTable - the primary constructor takes a TableModel (plus column and selection models) and the other constructors call this primary constructor.
For subclasses where the superclass already has overloaded constructors, I would tend to assume that it is reasonable to treat any of the parent class's constructors as primary and think it is perfectly legitimate not to have a single primary constructor. For example,when extending Exception, I often provide 3 constructors, one taking just a String message, one taking a Throwable cause and the other taking both. Each of these constructors calls super directly.
If you have a very complex class with a lot of options of which only some combinations are valid, consider using a Builder. Works very well both codewise but also logically.
The Builder is a nested class with methods only designed to set fields, and then the ComplexClass constructor only takes such a Builder as an argument.
Edit: The ComplexClass constructor can ensure that the state in the Builder is valid. This is very hard to do if you just use setters on ComplexClass.
It really depends on the kind of classes as not all classes are created equal.
As general guideline I would suggest 2 options:
For value & immutable classes (Exception, Integer, DTOs and such) use single primary constructor as suggested in above answer
For everything else (session beans, services, mutable objects, JPA & JAXB entities and so on) use default constructor only with sensible defaults on all the properties so it can be used without additional configuration
Constructor overloading is like method overloading. Constructors can be overloaded to create objects in different ways.
The compiler differentiates constructors based on how many arguments are present in the constructor and other parameters like the order in which the arguments are passed.
For further details about java constructor, please visit https://tecloger.com/constructor-in-java/

Why might one also use a blank constructor?

I was reading some Java recently and came across something (an idiom?) new to me: in the program, classes with multiple constructors would also always include a blank constructor. For example:
public class Genotype {
private boolean bits[];
private int rating;
private int length;
private Random random;
public Genotype() { // <= THIS is the bandit, this one right here
random = new Random();
}
/* creates a Random genetoype */
public Genotype(int length, Random r) {
random = r;
this.length = length;
bits = new boolean[length];
for(int i=0;i<length;i++) {
bits[i] =random.nextBoolean();
}
}
/* copy constructor */
public Genotype(Genotype g,Random r) {
random = r;
bits = new boolean[g.length];
rating = g.rating;
length = g.length;
for(int i=0;i<length;i++) {
bits[i] = g.bits[i];
}
}
}
The first constructor doesn't seem to be a "real" constructor, it seems as though in every case one of the other constructors will be used. So why is that constructor defined at all?
I am not sure that the code you were reading was high quality (I've reviewed some bioinformatics code in the past and it is unfortunately often not written by professional developers). For example, that third constructor is not a copy constructor and generally there are problems in this code, so I wouldn't "read too much into it".
The first constructor is a default constructor. It only initializes the bare minimum and lets users set the rest with getters and setters. Other constructors are often "convenience constructors" that help create objects with less calls. However, this can often lead to inconsistencies between constructors. In fact, there is recent research that shows that a default constructor with subsequent calls to setters is preferable.
There are also certain cases where a default constructor is critical. For example, certain frameworks like digester (used to create objects directly from XML) use default constructors. JavaBeans in general use default constructors, etc.
Also, some classes inherit from other classes. you may see a default constructor when the initialization of the parent object is "good enough".
In this specific case, if that constructor was not defined, one would have to know all the details in advance. That is not always preferable.
And finally, some IDEs automatically generate a default constructor, it is possible that whoever wrote the class was afraid to eliminate it.
Is the object Serializable?
To allow subtypes of non-serializable classes to be serialized, the subtype may assume responsibility for saving and restoring the state of the supertype's public, protected, and (if accessible) package fields. The subtype may assume this responsibility only if the class it extends has an accessible no-arg constructor to initialize the class's state. It is an error to declare a class Serializable if this is not the case. The error will be detected at runtime.
During deserialization, the fields of non-serializable classes will be initialized using the public or protected no-arg constructor of the class. A no-arg constructor must be accessible to the subclass that is serializable. The fields of serializable subclasses will be restored from the stream
Yes, I agree the "blank" constructor should not always exist (in my experience beginners often make this mistake), although there are cases when blank constructor would suffice. However if the blank constructor violates the invariant that all the members are properly instantiated after construction, blank constructor should not be used. If the constructor is complicated, it is better to divide the construction into several protected/private methods. Then use a static method or another Factory class to call the protected methods for construction, as needed.
What I wrote above is the ideal scenario. However, frameworks like spring remove the constructor logic out of the code and into some xml configuration files. You may have getter and setter functions, but probably may be avoided from the interface, as described here.
Default constructor is NOT mandatory.
If no constructors defined in the class then default (empty) constructor will be created automatically. If you've provided any parametrized constructor(s) then default constructor will not be created automatically and it's better to create it by yourself. Frameworks that use dependency injection and dynamic proxy creation at runtime usually require default constructor. So, it depends on use cases of class that you write.
The default constructor is'nt a good pratice for the functional view.
The default constructor is used if the object have a global visibility into a method: for example, you want log the actual state of a object in a try/catch
you can code
MyObejct myObject=null
try{...
}catch(Exception e){
log.error(myObject);//maybe print null. information?
}
or do you prefer
MyObejct myObject=new Object();
try{...
}catch(Exception e){
log.error(myObject);//sure print myobject.toString, never null. More information
}
?
Anotherway the create a EMPTY object have'nt a lot of logic, but instatiate a NULL object is harmuful in my opinion.
You can read this post
That is NOT a copy constructor. Basically you want empty constructors when working with some framework. Shall there always be an empty constructor, of course, public or private, but at least it allows you to keep control of how the class is being (or not) instantiated.
I usually write one constructor that fully initializes the object; if there are others, they all call this(...) with appropriate defaults.
An object should be 100% initialized and ready for use when it's created.
Some frameworks, for example Hibernate, demand a no-arg constructor. The way they clash with best practices makes me uneasy sometimes.
Having a default and empty (blank) constructor prevents you from having any final fields. This leads to a lot of mutability where there it is often not needed.
The builder pattern allows you to mix these two styles and allow more flexible initialization while still having immutability by hiding a many-arg constructor behind the factory.
For some POJO classes or simple class, default constructor is useful when you sometimes want to do unit testing on the class using them. You don't need to mock them, you can new an object with default constructor and test the value set and get from them or pass them as an argument.
You want to create a blank constructor for the classes that extended this
class and since it has been extended the class... the child now has super which references the class above it it's parent. In the event the child did not specify super(stuff)... the stuff inside to reference the other constructors to use it will now attempt to reference the empty constructor.
I'm not sure what the error will be I am coding my first parent object relationship now and was looking up things here ha cheers.
I guess I should add the moment you make a constructor that isn't the empty one you lose the default empty one so now super() which is default in the extended class won't have something to point to. Of course if you created the extended classes to take care of super by specifying on which gets rid of the default super() then you sidestep this but what if someone wants to use your class and extend from it and didn't realize there isn't an empty set when you could have
just created one.
This is my first post but wanted to take a crack from how I understand it.

Categories