Frankly, this is pure logic. It can easily be a static method attached to anything. The only criteria for where it should go is entirely dependent on what you find more readable.
That being said, there is overhead and hypothetical downsides to some of the approaches.
- DatabaseRecord Class
If you were to make it an instance method on the DatabaseRecord class, the only downside is that maybe you want the DatabaseRecord "layer" to not have any code related to a "higher layer".
public final class DatabaseRecord {
public MyCustomRecord toMyCustomRecord() {
return ...;
}
}
- Same hypothetical issue as (1), but thats always going to be a "hypothetical issue" no matter where you put it because every layer might not want to know about other ones. In my opinion this is the place where it makes the most sense, but I have nothing but feelings to back that up.
public final class MyCustomRecord {
public static MyCustomRecord fromDatabaseRecord(DatabaseRecord databaseRecord) {
}
}
You could also just call the method from
if you feel like that doesn't lose an important amount of readability.
- Class which is doing this transformation, maybe private.
No issue placing a small helper in whatever class you feel like, but as boring as it is - this is code that is easy to test and could potentially have stupid bugs in it, so it is important that it is public enough that you can test the method. That is, if you do TDD.
- Adapter class
I mean no reason why not, but it has dubious value. Lets say you created your adapter class.
public final class DatabaseRecordAdapter {
public MyCustomRecord adapt(DatabaseRecord) {
}
}
One, this doesn't really add much other than indirection on just calling a static method or an associated instance method. Two, you need to make instances every the time unless you make it a singleton. Making instances is cheap, but it isn't totally free. So to make it a singleton you would.
public enum DatabaseRecordAdapter {
INSTANCE;
public MyCustomRecord adapt(DatabaseRecord) {
}
}
and prior to java 8, this might have had some concrete uses, as a custom adapter class can implement interfaces and be used in a generic way.
public enum DatabaseRecordAdapter implements Adapter<DatabaseRecord, MyCustomRecord> {
INSTANCE;
public MyCustomRecord adapt(DatabaseRecord) {
}
}
And you could give it to anything expecting an Adapter
by passing DatabaseRecordAdapter.INSTANCE
. Nowadays this isn't a real benefit since you can use method references to pass the static method in case 2 like MyCustomRecord:::fromDatabaseRecord
. That being said, its not a bad approach - just make sure it makes sense in the context of your program and isn't just pure overhead.
DatabaseRecord
calledtoMyCustomRecord
which is simply:return new toMyCustomRecord(this);