Reputation: 482
I have a dilemma regarding the design of my code.
First of all, I am converting a VB to Java system. The VB program has a class module which is like a combination of POJO and access the database for its logic. I created a similar class in JAVA with getters and setters. My dilemma is that since I need to copy the structure of the VB codes (we are forced to), I also need to include the query services in my JAVA class. But in our framework, only service classes have access to the query services.
I am thinking of changing my JAVA class to an abstact class, and use Anonymous class instead.
Sample:
public abstract class MyClass {
private int a;
private int b;
public String calculate1() {
// do processing for variables a and b
String sql = "" // build sql here
List<Map<String, Object>> result = query(sql);
}
public String calculate2() {
// do processing for variables a and b
String anotherSql = "" // build anotherSql
List<Map<String, Object>> result = query(anotherSql);
}
protected abstract List<Map<String, Object>> query(String sql);
// getters and setters for a and b
}
public class MyService {
@Autowired
private QueryService myQueryService;
public void execute() {
MyClass myClass = new MyClass() {
@Override
protected List<Map<String, Object>> query(String sql) {
return myQueryService.executeQuery(sql);
}
};
}
}
A few things to consider:
Also because of this dilemma, I am forced to use string queries and JDBC template. Originally, our framework uses DAO objects and Hibernate. If someone also can solve the code using DAO, that would be better. If I will be using DAO objects, I would have to use different DAO objects with their DAO service classes.
I am not entirely sure if this is a good design. I don't know also if this will work. I was not able to run this in my environment.
I would really appreciate it if someone can enlighten me.
Thanks!
Upvotes: 3
Views: 241
Reputation: 425198
Since an instance of MyClass
can't function without an instance of QueryService
, how about you just pass an reference to the query service into the constructor of MyClass
:
public abstract class MyClass {
private final QueryService queryService;
public MyClass (QueryService queryService) {
this.queryService = queryService;
}
protected List<Map<String, Object>> query(String sql) {
return queryService.executeQuery(sql);
}
}
public class MyService {
@Autowired
private QueryService myQueryService;
public void execute() {
MyClass myClass = new MyClass(myQueryService);
}
}
Making the queryService
instance field final
, and having such a constructor, clearly expresses this dependency in code.
Upvotes: 1