Java - Good Practices and Recommendations - Design Patterns PDF
Java - Good Practices and Recommendations - Design Patterns PDF
S OFT WARE P ROJECT MANAGEMENT MARKET ING S INGULAR LOOP GROW WIT H US
Some of the design patterns can actually be used as guidelines during the
design of the architecture like it’s the case with the DAO design pattern.
Software architectures usually have three layers: the endpoints for the Top highlight
app, the service layer i.e. the business logic and the data layer.
The interface for the DAO itself defines only the operations that need to
be specified in the implementation. The implementation itself uses
generic types with provided entity manager. The entity manager is a class
that takes care of all the persistence operations in the app and can be
obtained using the application context.
@PersistenceContext
private EntityManager entityManager;
@Entity
@Table(name="person")
@NamedQueries
(
{
@NamedQuery(name=Person.GET_PERSON_BY_AGE,query="Select * from
User u where u.age>:age")
}
)
public class Person{
@Id
@GeneratedValue( strategy = GenerationType.IDENTITY)
@Column(name="id",unique="true")
public int id;
@Column(name="name")
public String name;
The DAO class which will be used for the entity extends the generic DAO
in which are implemented the basic CRUD operations, so we only need to
add the specific queries that will be used.
Pros:
offers both logical and physical separation of the code from the
business logic, which is easy to implement;
the DAO classes can be expanded easily with cache strategies, that can
be implemented in the methodsi;
If the DAO class is declared as an EJB, each method can specify the
transactional attribute in order to control the scope of the underlying
transaction;
Cons:
DAO pattern should not be used in small apps, because its advantages
would be minor and the code will become more complex;
Design patterns are often used to simplify big chunks of code or even to
hide specific implementations from the application flow. The perfect
example for these kind of problems is the factory design pattern, which is
a creational design pattern that offers object creation without having to
specify the exact class of the objects. It proposes using a super class and
multiple sub-classes, which inherit from the super class. During
execution only the super class is used and its value varies depending on
the factory class.
public Car(){
}
public Jeep(){
}
public Truck(){
}
Abstract factory design pattern works in the same way but instead of a
regular class, the parent class is an abstract class. Abstract classes are
generally faster and easier to instantiate, because they are basically
empty. The implementation is the same only the parent class is declared
as abstract with all its methods and the sub-classes need to implement
the behaviour of the methods declared in the abstract class.
The example for the Abstract factory is created using interfaces. The
same can be done by simply replacing the interface with an abstract class
and instead of implementing the interface, the sub-classes will extend
the abstract class.
public Jeep() {}
public Truck() {}
public CarFactory(){}
The only difference is that the methods declared in the abstract class
must be implemented in each of the sub-classes. The factory and the
main method stay the same in both cases.
System.out.println(car.getType());
}
}
Pros:
the factory class can be reused after creating new classes lower in the
hierarchy and the code will still work, by simply adding the
appropriate instantiation logic;
Cons:
the factory design pattern must maintain its context i.e. only classes
that inherit from the same parent class or implement the same
interface can be applicable for the factory design pattern.
Also, whenever the application needs to read a file from the server it is
convenient to use a Singleton class, because in that case only one object
of the application will be able to access the files stored on the server.
Besides the logger implementation, the config files are another example
where the use of a singleton class is efficient.
import java.nio.file.Files;
import java.nio.file.Paths;
private Logger(){
fw = new FileWriter(logFileLocation, true);
bw = new BufferedWriter(fw)
this.pw = new PrintWriter(bw);
}
Because the log file will be accessed frequently. the print writer using a
buffered writer makes sure that the file won’t be opened and closed
multiple times.
private Logger(){
// init
}
The singleton class then can be used from any other class inside the app:
Logger log=Logger.getInstance();
log.write("something");
Pros:
the singleton class is instantiated only once in the life cycle of the app
and it can be used as many times needed;
Cons:
the singleton class also hides some of the dependencies in the code
i.e. creates dependencies that are not explicitly created;
In real cases, the list of arguments will be longer and some of the
arguments for the class can be calculated based on other input. The
builder class has the same fields as the class itself and it must be declared
static in order to be accessed without having to instantiate an object of
the holder class (in this case Example.java). The implementation given
above is thread safe and can be used in the following way:
Pros:
the code is more neat and reusable if the number of arguments in the
class is bigger than 6 or 7;
the object is created after setting all the needed fields and only fully
created objects are available;
the builder pattern hides some of the complex calculations inside the
builder class and separates it from the application flow;
Cons:
the builder class must contain all the fields from the original class, so
that can take a little more time to develop compared to using the class
alone;
674 claps
WRIT T EN BY
A short summary of Java Practical Guide to Java Framework-less REST Hibernate : Mistakes to
coding best practices Stream API API in Java avoid
Ra ullah Hamedy Praveer Gupta in Praveer’s marcin piczkowski in Marcin Manika Singh
Musings Piczkowski
Design Patterns —Zero A Study List for Java 4 T hings T hat are most How to Write Better
to Hero —Singleton Developers confusing for Java Code with Java 8’s
Pattern Jim Developer Optional
Parathan T hiyagalingam Himanshu Verma in T he Code Somnath Musib in T he Startup
Monster