This is a sample code which haven't followed the single responsibility principle,
public class EmailSender
{
public void SendEmail(string customerID,
string emailNotificationType)
{
//STEP1: load customer details
//STEP2: get email content
//STEP3: send email (using SmtpClient class)
}
public string GetEmailContent(Customer customer,
string emailNotificationType)
{
// Build the email notification content
}
}
I agree, It will create the issue in case If I need to do following,
-> Changes in the way, you are loading customer details.
-> Changes to the email content because of requirement enhancements / changes.
-> If there any change in the way you are sending the email instead of using SmtpClient class or something like that.
so we need to apply Single Responsibility Principle to separate the classes. I totally agree on this principle. Say I need to create three classes like
EmailSender - which only focus on sending email
CustomerRepository - which only focus on fetching customer data
EmailContentBuilder - which parse the email content
But say If I have a Dao like CustomerDao, As of now I have all the CRUD operations related to CustomerDao in the same class like below
CustomerDao class
- add()
- update()
- get()
- getAll()
- update()
Do we need to apply SingleResponsibilityPrinciple here? If so How to apply for CustomerDao class?
Thanks,
Harry
You do not want to apply to DAO because it only do one thing.
good example
sourse
Patterns and principles are great things, but used incorrectly they can make a simple problem just as complex as not having them.
SRP shouldn't be understood in a strict manner. One object should have very few responsibilities, not "one".
Here CustomerDao is only responsible for Customer persistence, so it has only one responsibility.
Despite its name SRP is expressed as "A class should have only one reason to change". DAO is changed for the single reason: when mapping between database table and business object changes so DAO does not violate SRP.
Think of an example: business logic changes so that we need to add some more data to our object: we add fields to our business object, columns to database table and of course we need to change the mapping. We are likely to change get/add/update methods of our single DAO class then.
For clear understanding of the principle I would recommend reading the original source of SOLID principles: Robert Matin's book Agile Software Development, Principles, Patterns, and Practices.
Related
Where should I keep logic for derived fields (derived from attributes of the same model class) - in model layer or in service layer?
Example:
In the code below, age is derived from dateOfBirth (do not ask why you need to persist age when it can be derived from dateOfBirth in the model class - this is a hypothetical example). Where should I keep calculateAge() method - in PersonModel or PersonService?
import java.util.Date;
models/Person.java
#Entity
public class Person {
private Date dateOfBirth;
private String age;
}
service/PersonService.java
public interface PersonService {
}
Not sure what you mean by "where to keep it", but this usually depends if you want to treat your entity model as domain or persistence model. Lots of people don't need to distinguish between these two models(because the differences are minimal) and just put everything into the entity class. As soon as the domain logic becomes more important, people usually introduce some sort of domain model on top of the entity model, within which the entity state is encapsulated, and translation between the models happens in the service layer implementation.
This is an open ended question, so you won't get a definitive answer. This is just what I observed from other projects and how I understand this is usually done or supposed to be. Do what works best for you and always ask yourself if the abstraction brings value to your project before applying a design pattern like this.
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
I have inherited an application written in Java that uses JPA to access a database. The application uses an design pattern that I haven't come across before and I would really appricate some guidance on why this pattern is used. Like many applications, we have a front end, middleware, and back end database. The database is accessed via DAOs. Each method on the DAO loads a entity-DTO which is just a POJO with nothing but getters and setters and that entity-DTO is then passed into a entity-proper that has other methods that change the entity state. An example [class names changed to protect the inocent]
enum Gender
{
Male,
Female
}
class PersonDTO
{
private String mFirstName;
private String mLastName;
private Gender mGender;
...
String getFirstName() { return this.mFirstName; }
String setFirstName(String name) { this.mFirstName = name; }
// etc
}
class Person
{
PersonDTO mDTO;
Person(PersonDTO dto)
{
mDTO = dto;
}
String getFirstName() { return mDTO.getFirstName() }
String setFirstName(String name) { mDTO.setFirstName(name); }
// and so on
void marry( Person aNotherPerson )
{
if( this.getGender()==Gender.Female &&
aNotherPerson.getGender()==Gender.Male)
{
this.setLastName( aNotherPerson.getLastName() );
}
aNotherPerson.marry( this );
}
}
This is repeated across 30 or so entity classes, doubled to 60 with the DTOs, and I just cant get my head around why. I understand (bits) about seperation of converns and I also understand (bits) about the difference between an EAO based design to say an active record based design.
But does it really have to go this far? Should there always be at least one "DB" object that contains nothing but getters and setters that map to the DB fields?
Disclaimer: there are varying opinions on this subject and depending on your system's architecture you might not have a choice.
With that said... I've seen this pattern implemented before, not a huge fan of it, in my opinion is duplicates large amounts of code without adding any real value. It seems to be particularly popular in systems with XML APIs like SOAP where it might be difficult to map XML structure directly to your object structure. In your particular case it seems to be even worse because on top of duplicate getFirstName()/getLastName() methods, there is business logic (which belongs in the service layer) coded right into a pojo (which should be a simple data transfer object like the DTO). Why should the pojo know that only people of opposite sex can get married?
To help better understand why, can you explain where these DTOs come from? Is there a front-end submitting data to a controller which then converts it to a DTO, which is then used to populate your entity-proper with data?
It could also be that they are using this just to separate the JPA annotations from the rich domain object.
So I'm guessing that somebody didn't like having JPA annotations and the rich domain object behaviour in one class. Somebody could have also argued that the JPA annotation and the rich domain object should not be in the same layer (because the annotations mixes the concerns) so you would get this kind of separation if you won this argument.
Another place where you'd see this kind of thing happening is when you want to abstract similar annotations away from the rich domain objects (like jaxb annotations in web services for example).
So the intent might be that the DTO serves as sort of the serialization mechanism from code to the database, which is very similar to the intent mentioned here by martin fowler.
This doesn't appear to be a known pattern.
In general
it is common to maintain a separate object to represent the record in the database, referred to as domain object.
the CRUD operations on the object are part of a DAO class and other business operations would be part of a Manager class, but none of these classes store the domain object as a member variable, i.e. neither DAO nor Manager carry state. They are just processing elements working on domain objects passed in as parameters.
a DTO is used for communication between the front-end and back-end to render data from DB or to accept input from end-user
DTOs are transformed to Domain objects by Manager class, where validations and modifications are performed per business rules. Such domain objects are persisted in the DB using DAO class.
I have worked on one project where we have DTOs for the sole purpose of transferring information from front-end controller to some facade layer. Then facade layer is responsible for converting these DTOs to domain objects.
The idea behind this layering is to decouple front-end (view) from domain. Sometimes DTOs can contain multiple domain objects for aggregated view. But domain layer always presents clean, reusable, cacheable(if required) objects.
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.
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