Removing copy/pasted code without an interface - java

I have two data access objects that are reverse generated and jar'ed up for use by my application. They represent tables that are very similar. One table has a few additional columns than the other. This is out of my control due to business oriented database ownership concerns.
The application currently has two implementations of a repository that operates on these DAOs. The implementations are very similar. One has a few extra operations that correspond to the extra columns on the second DAO. However with only a few exceptions, one implementation is a copy and paste of the other. The implementations are hundreds of lines long.
So I wanted to remove the copy/paste job. Ideally I could just stick an interface in front of the DAOs, and then maybe use an abstract class to hold the shared code (nearly all of it). However, I cannot put an interface in front of the DAOs. Remember they are reverse generated, and without upgrading our ORM software I don't think this is a reasonable choice (Kodo 3.x I believe, changing this is not in scope).
The only thing I can think of that would even work is some nastiness with reflection but that results in something much worse than I have now.
Any clever solutions?
edit: Here is very watered down code example
package one.dao
//reverse generated
class UserDao {
getFirstName(..);
setFirstName(..);
getLastName(..);
.... 50 more just like this
}
package two.dao
//reverse generated
class UserDao {
getFirstName(..);
setFirstName(..);
getLastName(..);
.... the same 50 more as above
getSomethingElse(..); //doesn't exist in one.dao.UserDao
setSomethingElse(..); //doesn't exist in one.dao.UserDao
}
class RepositoryOne(one.dao.UserDao userDao) {
//insert code here. perform operations on nearly all methods, lots of code
}
class RepositoryTwo(two.dao.UserDao userDao) {
//insert code here. same as Repository one
//some extra code that isn't above, maybe 10 lines
}

I am assuming you have some control over the duplicated code. If your code generator is producing all of it, you'll need to search for solutions within its API & configuration, I suspect.
When Inheritance doesn't work, try Composition. Make a third class to hold the shared code (SharedCode). Give each of the two existing classes a private member instance of the SharedCode class and make all routines implemented in SharedCode pass through methods to the member instance.

Related

ECB pattern (Entity,Control,Boundary) implementation

I'm learning about the ECB pattern. I've understood the concept of this pattern but i'm not sure about its implementation. I'm going to write a simple example:
I supposed to need a software which manages the customers of a shop. The customers are stored on a generic database.
Accoding to the ECB pattern i need to have the following classes
1)Customer which represents the entity, with its attributes (name,surname,birthDate etc..)
2)CustomerWindow which represents the boundary, with some labels, textfields, buttons and a table to show customers
3)CustomerController which represents the logic with some methods (insert,delete etc...)
I should add also a CustomerDAO (implementing an interface, but my question is not about DAO) which manages the access to the database.
I would like to know the way this classes interact each other.
For example, supposing the insertion of a new customer, i suppose they interact like this:
1)The CustomerWindow "collects" the data written inside the textFields (name,surname ecc) and calls the method insert(String ....) of the CustomerController.
2)The CustomerController check if all data are ok (for example empty fields or format error). If they are ok, create a new Customer with that data and calls the method insert(Customer c) of the CustomerDAO.
3)The CustomerDao provide to insert the customer into the database
Obviously some of this operations could throw some exceptions but i think it's not important for this example, supposing inserted data are all valid.
Is this the way the ECB pattern works? If not, how it works?
I have a last question:
Some of this classes should be static or i need to declare an instance of each of them? For example i think the CustomerController and the Customer DAO can be static. The CustomeWindows calls the CustomerController.insert(...) method which eventually calls the CustomerDAO.insert(...) method (so i don't need to create a new CustomerController() or a new CustomerDAO(). Is it right?
I hope my english is pretty understandable. Please tell me if i've not been clear about something. Thank you all ;)
P.s. if you prefer i can write a code example

DAO class methods naming

I am building a small Java web application using Spring MVC, Hibernate and I am confused about the DAO classes methods naming.
For example I have an InvoiceDAO.java class which I thought should contain the following methods:
Save(Invoice newInvoice);
Void(Invoice oldInvoice);
getInvoiceByID(Long invoideID);
but my boss says that best practices says that I should have methods names in DAO classes as follows:
add(Invoice newInvoice);
update(Invoice oldInvoice);
which makes no sense for me as I am not sure how I can name voiding an invoice as Update?!!
So can someone please guide me in this and tell me if I am wrong on my methods naming? In other words is it correct that I should only use add, update for naming or can I use any naming and still be considered as best practices.
thanks
Voiding an invoice is a business operation. I would say such logic lives in your service layer. You make updates to the invoice to mark it as void, and then pass it to the data layer to save.
The data layer should contain pure CRUD type methods, that is add/save/find.
Using many modern data frameworks, you don't even need to write the data layer ... e.g. see http://blog.springsource.org/2011/02/10/getting-started-with-spring-data-jpa/
I've found this refeernce some time ago about DAO naming ...
Names according to function
getData* Data Parsing Methods used internally in DAO, do not use this namespace for data accessing.
get* (e.g. getUsersByID) SELECT queries – It is encouraged that you try to use the noun in Singular or Plural according to single or multi-row return.
set* (e.g. setActive) UPDATE Queries
add* (e.g. addUser) INSERT Queries – It is encouraged that you try to use the noun in Singular or Plural according to single or multi-row insert.
delete* (e.g. deleteUser) DELETE queries
is* (e.g. isActive) IF check returns boolean, i.e., if ($user_dao->isUserActive($id)) or if ($post_dao->isPostInStorage($id))
count* (e.g. countUsers) Returns integer with the item count.
Reserved functions
insert – takes an object as argument, and inserts it to the table.
save – takes an object as an argument, and stores the data in it back to data backend
poke – Takes an ID as argument, “pokes” the record (sets “last seen” or whatever to now), returns update count (usually 1)
Other things to remember
As the storage Backend may or may not be a “database”, it would be encouraged not to create methods with names that imply that the backend is using a database.
First of all, in Java, at least, you name your methods with the first letter of each internal word capitalized, camel-case. You can see at the section Methods this: Java Naming Conventions
Regarding the specific naming of your methods inside the dao:
I would go by creating basic crud operations that can be performed to your model classes
Example:
add(Invoice invoice)
update(Invoice invoice)
// or instead
save(Invoice invoice) // which will perform either add or update
delete(Invoice invoice) // or delete(int invoiceId)
findById(int invoiceId)
// and so forth
I would not make use of the term "void" inside the dao, since that is related to the business. Do the dao as simple as possible and after that in your service that will be using the dao, you can name your methods related to the business required (i.e. voice(Invoice invoice))
There is another possibility to create a generic dao with the basic CRUD operations and maybe you can then start naming the methods as you want:
public class InvoiceDAO inherits GenericDao<Invoice> {
// all the above methods would be inherited
// add specific methods to your dao
}
Again, if I were you I would move the naming of specific stuff in the service.
Now it's up to you how you want to approach from what I showed. The idea is to keep the dao as simple as possible.
You might as well go and name your void method (since you can do name it void, since in Java is a keyword -- thanks #Marco Forberg for noticing that) either delete (Void - means that it is deleted.) or performVoid. Or go simple with update if you are not removing the invoice from the database after you void it. update can be applied to any changes you made for your invoice entry.
Save and add have 2 different meanings. As do Void and update. Use the term that accurately describes what the method is doing. Im not aware of any specific best practise here.
Also, I would tend to only pass an ID into a void method if that is enough to perform the action. This is different scenario from an update where you may expect to update multiple attributes on the invoice.

How can I break down some methods in the spring service layer

I'm doing some maintenance/evolution on a multi-layered spring 3.0 project. The client is a heavy RCP application invoking some spring beans methods from the service layer (Managers) on a RMI based server.
I have several huge method in the Managers, some of them are doing more than 250 lines.Here is an example : (I've omitted code for clarity)
#Transactional(readOnly = false, propagation = Propagation.REQUIRED)
public Declaration saveOrUpdateOrDelete(Declaration decla, List<Declaration> toDeleteList ...){
if (decla.isNew()){
// create from scratch and apply business rules for a creation
manager1.compute(decla);
dao1.save(decla);
...
}else if (decla.isCopy() {
// Copy from an other Declaration and apply business rules for a copy
...
}else {
// update Declaration
...
}
if (toDeleteList!=null){
// Delete declarations and apply business rules for a mass delete
...
}
The first 3 branches are mutually exclusive and represent a unit of work. The last branch (delete) can happen simultaneously with other branches.
Isn't it better to divide this method in something more 'CRUDy' for the sake of clarity and maintainability ? I've been thinking of dividing this behemoth into other manager methods like :
public Declaration create(Declaration decla ...){...
public Declaration update(Declaration decla ...){...
public Declaration copyFrom(Declaration decla ...){...
public void delete(List<Declaration> declaList ...){...
But my colleagues say it will transfer complexity and business rules to the client that I will loose the benefit of atomicity etc.. Who is right here ?
The decision what the updateOrCreateOrWhatever really does is made in the client anyway as it has to set the corresponding field in Declaration object.
The client could equally well just call the apropriate method.
That way code is definitely more manageable and testable (less branches to care about).
The only argument for maintaining it as is is the network round-trips mentioned by #Pangea. I think this could be handled by custom dispatcher class. IMO it doesn't form a part of business logic, and as such shouldn't be taken care of in service layer.
Another thing to take into consideration is transaction logic. Do create/update and deletes have to happen in the same transaction? Can both decla and toDelete be not null at the same time?
One of the basic principles to keep in mind when designing remote services is to make it coarse-grained in order to reduce network latency/round-trips. Also, after going through your code, it seems like the method encapsulates a logical unit of work as it is transactional. In this case, I suggest to keep it as it is.
However, you can still refactor it into multiple methods as long as they are not exposed to be invoked remotely thus forcing the client to manage the transactions from client layer. So make them private.
Bad design. If u really have to make the transaction atomic or complete in one trip, create a more specific method instead of having this.
What's the difference of writing:
public Object doIt(Object... obj){
...
}

Is a DAO Only Meant to Access Databases?

I have been brushing up on my design patterns and came across a thought that I could not find a good answer for anywhere. So maybe someone with more experience can help me out.
Is the DAO pattern only meant to be used to access data in a database?
Most the answers I found imply yes; in fact most that talk or write on the DAO pattern tend to automatically assume that you are working with some kind of database.
I disagree though. I could have a DAO like follows:
public interface CountryData {
public List<Country> getByCriteria(Criteria criteria);
}
public final class SQLCountryData implements CountryData {
public List<Country> getByCriteria(Criteria criteria) {
// Get From SQL Database.
}
}
public final class GraphCountryData implements CountryData {
public List<Country> getByCriteria(Criteria criteria) {
// Get From an Injected In-Memory Graph Data Structure.
}
}
Here I have a DAO interface and 2 implementations, one that works with an SQL database and one that works with say an in-memory graph data structure. Is this correct? Or is the graph implementation meant to be created in some other kind of layer?
And if it is correct, what is the best way to abstract implementation specific details that are required by each DAO implementation?
For example, take the Criteria Class I reference above. Suppose it is like this:
public final class Criteria {
private String countryName;
public String getCountryName() {
return this.countryName;
}
public void setCountryName(String countryName) {
this.countryName = countryName;
}
}
For the SQLCountryData, it needs to somehow map the countryName property to an SQL identifier so that it can generate the proper SQL. For the GraphCountryData, perhaps some sort of Predicate Object against the countryName property needs to be created to filter out vertices from the graph that fail.
What's the best way to abstract details like this without coupling client code working against the abstract CountryData with implementation specific details like this?
Any thoughts?
EDIT:
The example I included of the Criteria Class is simple enough, but consider if I want to allow the client to construct complex criterias, where they should not only specify the property to filter on, but also the equality operator, logical operators for compound criterias, and the value.
DAO's are part of the DAL (Data Access Layer) and you can have data backed by any kind of implementation (XML, RDBMS etc.). You just need to ensure that the project instance is injected/used at runtime. DI frameworks like Spring/Guice shine in this case. Also, your Criteria interface/implementation should be generic enough so that only business details are captured (i.e country name criteria) and the actual mapping is again handled by the implementation class.
For SQL, in your case, either you can hand generate SQL, generate it using a helper library like Spring or use a full fledged framework like MyBatis. In our project, Spring XML configuration files were used to decouple the client and the implementation; it might vary in your case.
EDIT: I see that you have raised a similar concern in the previous question. The answer still remains the same. You can add as much flexibility as you want in your interface; you just need to ensure that the implementation is smart enough to make sense of all the arguments it receives and maps them appropriately to the underlying source. In our case, we retrieved the value object from the business layer and converted it to a map in the SQL implementation layer which can be used by MyBatis. Again, this process was pretty much transparent and the only way for the service layer to communicate with DAO was via the interface defined value objects.
No, I don't believe it's tied to only databases. The acronym is for Data Access Object, not "Database Access Object" so it can be usable with any type of data source.
The whole point of it is to separate the application from the backing data store so that the store can be modified at will, provided it still follows the same rules.
That doesn't just mean turfing Oracle and putting in DB2. It could also mean switching to a totally non-DBMS-based solution.
ok this is a bit philosophical question, so I'll tell what I'm thinking about it.
DAO usually stands for Data Access Object. Here the source of data is not always Data Base, although in real world, implementations are usually come to this.
It can be XML, text file, some remote system, or, like you stated in-memory graph of objects.
From what I've seen in real-world project, yes, you right, you should provide different DAO implementations for accessing the data in different ways.
In this case one dao goes to DB, and another dao implementation goes to object graph.
The interface of DAO has to be designed very carefully. Your 'Criteria' has to be generic enough to encapsulate the way you're going to get the data from.
How to achieve this level of decoupling? The answer can vary depending on your system, by in general, I would say, the answer would be "as usual, by adding an another level of indirection" :)
You can also think about your criteria object as a data object where you supply only the data needed for the query. In this case you won't even need to support different Criteria.
Each particular implementation of DAO will take this data and treat it in its own different way: one will construct query for the graph, another will bind this to your SQL.
To minimize hassling with maintenance I would suggest you to use Dependency Management frameworks (like Spring, for example). Usually these frameworks are suited well to instantiate your DAO objects and play good together.
Good Luck!
No, DAO for databases only is a common misconception.
DAO is a "Data Access Object", not a "Database Access Object". Hence anywhere you need to CRUD data to/from ( e.g. file, memory, database, etc.. ), you can use DAO.
In Domain Driven Design there is a Repository pattern. While Repository as a word is far better than three random letters (DAO), the concept is the same.
The purpose of the DAO/Repository pattern is to abstract a backing data store, which can be anything that can hold a state.

Overlaying an existing object graph?

I have a database that contains an object graph. However, during use of the objects contained in the database I need to add additional functionality.
I cannot change the classes of the database, so I figure my only option is to make wrapper classes composed of their database equivalent objects and create forwarding methods along with methods and fields for the additional functionality. For instance:
public class Foo() {
private DBFoo databaseFoo;
// a bunch of forwarding methods to databaseFoo
// some methods for additional functionality
}
I'm struggling with a good pattern to construct my wrapper objects on top of the pre-existing database object graph. In particular how to reconstruct my graph of objects to mirror the graph in the database (with all its various references to other objects). Does anyone have experience with this sort of problem?
I can see two problems here:
a). Given some dbClassA, which references dbClassB, and collections of dbClassC, with dbClassB and dbClassC each themselves being arbitrarily complex: what design of proxy is appropriate? If dbClassA has methos
dbClassB getB() { ... }
we can quite easily see a mapping to
myClassB getB() { return new myClassB( theDbClassB.getB() ); }
or some such. But exactly what do we do with the collections?
List<dbClassC> getAllCs() { }
what does that become?
I figure that this is a solvable problem, just a matter of choosing some rules.
I suspect that you're more concerned about:
b). Creating all those proxy classes. Apply the chosen rule to many, many classes. One possible approach is to use code generator capabilities, for example JET in Eclipse. I've seen very good use of this capability for similar problems.

Categories