Reputation: 2731
I have a class that only contains data, but depends on a connection object from which the data is fetched. The connection object manages a low level socket connection to a much bigger API (old single header C API). Currently i have this:
public class MyData {
private int data1;
public MyData(Connection connection) {
data1 = connection.getLowLevelConnection().someDataFetchCall();
}
// getters, setters
}
It works, but feels wrong. Intuitively i would say, that the data should be acquired in a function, which returns my initialized data object:
public class DataFetcher {
public static MyData getMyDataFromConnection(Connection connection) { ... }
// ... more data fetching functions
}
Is there a named pattern for this kind of task? That would make naming these classes easier.
Upvotes: 0
Views: 94
Reputation: 755
You tied the data itself to its loading mechanism. Without proposing any pattern, you should decouple it. I guess there is no real pattern that you can apply. It's a matter of design principles especially the single responsibility principle and dependency inversion. The single responsibility principle says you should not separate things that belong together and you should not tie things that don't belong together. The dependency inversion principle says do not depend on concretes, depend on abstracts.
The design should finally come up with
one class to load the data to satisfy the single responsibility principle.
If you want to be independent of the loading mechanism introduce abstraction (e.g. interface), applying dependency inversion.
It's true that the repository "pattern" defines such a structure.
A side note: I personally do not accept the label "pattern" on it. It's only a label for a benifical stucture that you will reach anyway if you apply the SOLID principles. In contrary the 23 design patterns from the GoF. They were not made up, they were identified. They have intrinsic meaning. The "pattern" label suggest that the repository "pattern" falls in the same category but it doesn't. It is lacking naturalness and atomicity.
Upvotes: 2
Reputation: 949
It works, but feels wrong.
It does.
Sticking to DDD, I'd create a repository if MyData
was an aggregate or a service if MyData
was an entity. Anyway I'd put classes to infrastructure layer and interfaces with MyData
to domain layer. For example,
MyData entity:
package myapp.domain.model;
public class MyData {
private int data1;
// other fields
public MyData(int data1) {
this.data1 = data1;
}
// other methods
}
Service interface:
package myapp.domain.service;
import myapp.domain.model.MyData;
public interface MyService {
MyData GetMyData();
}
Service implementation:
package myapp.infrastructure.oldapi;
import myapp.domain.model.MyData;
import myapp.domain.service.MyService;
public class MyServiceImpl implements MyService {
@Override
public MyData GetMyData() {
MyData myData = connection.getLowLevelConnection().someDataFetchCall();
return myData;
}
}
Upvotes: 1