DAO class methods naming - java

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.

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

Standard Naming Convention for DAO Methods

Is there a standard naming convention for DAO methods, similar to JavaBeans?
For example, one naming convention I've seen is to use get() to return a single entity and find() to return a List of entities.
If there isn't one, what's the one your team is using and why?
I am aware of conventions like the following:
methods starting with find perform select operations, and method names containing the search criteria, like findById, findByUsername, findByFirstNameAndLastName, etc.
modification methods start with create, update, delete.
Check out the conventions used by Spring Data JPA. This is part of the Spring framework that writes the DAOs automatically based on among other things inspection of the method name based on naming conventions.
get() for single entities does not seem to be a good option, as get is associated by Java developers to a Java-bean getter.
Usually I name the methods in such way that the name hints the type of the CRUD operation that will be applied by the method, like add*, save* or find*.
add* can be applied on INSERT operations, like addPhoneNumber(Long userId).
get* can be applied for SELECT operations, like getEmailAddress(Long userId).
set* can be applied on method that performs an UPDATE operation.
delete* can be applied on DELETE operations, like deleteUser(Long userId). Althought I'm not pretty sure how useful is the physical delete. Personally, I would set a flag that denotes that the row is not gonna be used, rather than performing a physical delete.
is* can be applied on a method that check something, for example isUsernameAvailable(String username).

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.

Object Oriented CRUD program - What is the reason for the OO design?

First of all, I really don't want anyone to do my assignment. I just can't understand the point of the design that I've been asked to implement. One of the methods seems redundant to me and I wonder if someone could shed some light on it.
I have to make a Student class (and subclasses) that has 4 methods: add, delete, update and query. I have to be able to use those methods to update a database. For example the spec for the add() method says:
When this method is called, the database entry for the student is created.
I can understand that we need to have a class here because if the information entered into the GUI is incorrect, then I can have some setter methods in the Student class that will throw an exception that can be caught by the GUI and these can be displayed. So the class is useful to validate the information. Likewise for the update and delete methods.
The thing that is really annoying me is the query() method:
When this method is called, a query is made to the database to retrieve the information and is then printed to the screen.
The Student class is meant to have a query() method (and it has subclasses that inherit this as well). But in order to query the database, we already need to have the instance created, so we'll already have queried the database in order to get the info to create the class, so I could just as well call the toString() method that I've overridden to display the class's data.
I don't see the point of each Student instance having a query() method when it will be redundant for them to use it. Can anyone tell me why this might be useful?
Thanks
Update
Thanks to everyone who answered. I take on board the fact that there should normally be a separation of concerns between the object that holds data and an object that uses or acts upon that data.
My assignment states that the query method should query the database and then display that info to screen. I'm thinking now that if I made this a static method and gave it an argument of the student name or something, then it could actually query the database and then create a Student instance with that info and display it. At least that makes sense to me in that it's only called once, so there's no redundancy.
First off: I'd consider it a very bad design if the Student class is both the value holder and the class that handles loading/storing. It violates the single responsibility principle. I'll assume that this is homework and thus overlook this part for now. The same problem exists with the query() method: it seems to have two responsibilities for no apparent reason.
When writing an object-relational mapper (which you are kind-of doing here), it is often the case that you have "half-restored" objects: Objects which you know should exist in the database and you know their primary key (for example because you have a reference to that object in another object).
In that case it could easily be the case that a query() method that loads the actual data could be useful.
It is not useful and no one would (or should) do it like that. A Student is a persistable entity, but some other component will be responsible for creating, reading, updating or deleting those entities.
Often we see designs that consist of data transfer objects (a value holder, the *entity bean, your Student) and factories that do the CRUD business.
Ask yourself (or the teacher), what do you expect from a query method on Student? I'd expect some sort of query, where a student executes to get more informations for his/her studies.
The purpose for this is that the Student object should not be inextricably tied to a Student record. I should be able to create a new Student object that is empty, and does not have a unique ID yet.
Perhaps I want to create a new Student that doesn't exist yet in the system, I can provide the necessary data, call my add() or insert() method and then this will be persisted. Likewise if I create a Student object and call query() I imagine that the object values will all be replaced with the result of the fetched Student record.
As others here have noted, it is not considered a popular practice for the Value Holder, the entity itself to have the CRUD functionality built within. This doesn't necessarily mean that this is inherently wrong. In OOP, the object should have all functionality associated with itself and it would be more similar to an EJB EntityBean than your typical ORM/Persistence Framewok Bean that is more popular today.
The ORM/Persistence Framework that other answers have stated is known as an Anemic Data Model which certain OOP evangelists like Martin Fowler decry. http://martinfowler.com/bliki/AnemicDomainModel.html

Best Practice: String converting batch in instantiating class or capsulated in every instantiated class

One class Customers instantiates many other classes (e.g. CustomersFromMysql, CustomersFromPostgeSQL) that all query databases which give back customer names. Now these customer names come back as for example name = "John Doe", what my Customers class needs though is more than name, it also needs nameNoSpace = "JohnDoe" and nameInvertedComma = "Doe, John" for example.
I would programm a helper class Converter which has methods like invertName(name) and removeComma(name). Would I instantiate the converter in every class that queries the database (CustomersFromMysql, CustomersFromPostgeSQL) to give back all required variables or would I instantiate the Converter in the instantiating class Customers so when I get back results I iterate through my list and batch convert them?
Of course both works, but what is the way to go?
You should remember separation of duties in such cases. The database related classes should handle only the database specific aspects. Performing operations (calculations) on the retrieved data should be treated as business logic. So, if your Customers class already has some logic in it, it would be the perfect place for putting in the conversion routines. Neverthess, it really depends on where you think your logic belongs to.
It may also make sense to apply some naming conventions. In general you can distinguish between at least the different kinds of classes in case like the one you desribed in your question:
Data Access Objects (DAO); perform database opertions (your SQL classes)
Data Transfer Objects (DTO) or entities; represent the structure of your business objects
Business Logic; retrieve the DTO by using DAOs, perform some logic according to your requirements, push the DTO back into the database by using the DAOs again

Categories