What is the preferred method of the two below, when it comes to object conversion?
Object conversion using an asX() method
public class Foo {
int foo;
public Bar asBar() {
return new Bar(foo);
}
}
class Bar {
int bar;
public Bar(int bar) {
this.bar = bar;
}
}
Object conversion using a constructor
public class Foo {
int foo;
}
class Bar {
int bar;
public Bar(int bar) {
this.bar = bar;
}
public Bar(Foo foo) {
this.bar = foo.foo;
}
}
I'm not sure of the merits of either method (with regards to maintainability, scalability et.c), compared to the other. What is the established standard?
I accepted that the question is quite broad as pointed out by Paul Boddington in the comments, but hope for some useful discussion before this question is closed.
What I've seen used a lot and I personally like is the style used by a lot of the JDK itself, which involves a static factory method in the destination class. The ultimate goal is to make the code easy to read.
For example:
Integer.fromString("42")
Lending from the example in the OP:
public class Foo {
int foo;
}
class Bar {
int bar;
public static Bar fromFoo(Foo foo) {
return new Bar(foo.foo);
}
public Bar(int bar) {
this.bar = bar;
}
}
That way someone can create a Bar
from a Foo
and the code reads well when doing so:
Bar bar = Bar.fromFoo(foo);
It reads almost like English, without being COBOL!