How to apply decoupling on these two coupled classes - java

I have two classes:
public class CourseModule {
// attributes...
List<Course> courses;
public void addCourse() { ... }
}
public class Course {
// attributes...
CourseModule module;
}
The attributes of Course do not suffice to identify an object uniquely, the course module is always required, also for addition information. A CourseModule consists of difference Courses.
What I don't like here is the circular dependency, it feels wrong. Now I was thinking about the following, instead of adding courses per method and setting the CourseModule reference by hand I could automate this procedure with the constructor:
public Course(...,...,...., CourseModule module) {
this.module = module;
module.courses.add(this);
}
But again, here is another huge problem: In Brian Goetz Java Concurrency in Practice it is said: Do not let the this reference escape the constructor
So what would be best practice here? I think its a really simple example, which might bear yield a sample solution.

Funnily enough, I had to do something similar. See my question here.
I found this post on the internet that is almost an exact duplicate of what you are trying to do, also with courses! I found that the solution specified there is not 100% right, the answers on my question need to be considered.

You're right, I would say that your current setup is an example of Code Smell.
Could you not make another object CourseInfo that manages the additional course information that you say cannot be contained within Course?
public class CourseModule {
List<Course> courses;
public void addCourse(Course course) { ... }
}
public class Course {
CourseInfo info;
}
public class CourseInfo {
CourseInfo info;
}

Related

Passing reference to instance into another object when new object is part of original object?

Could be there any flaw (from design perspective) when passing this instance of parent class into another object's constructor when new instance will be part of the original instance?
public class Order extends AbstractOrder {
private final OrderExecutionStrategy executionStrategy;
private Order() {
this.executionStrategy = new OrderExecutionStrategy(this);
}
// the implementation omitted for brevity...
}
I need to access data from parent instance in OrderExecutionStrategy class.
public class OrderExecutionStrategy extends AbstractOrderExecutionStrategy {
public OrderExecutionStrategy(final Order order) {
super(order);
}
#Override
public Optional<OrderPortion> executePortion(final BigDecimal newPrice, final TradeOrders orders) {
AssertUtils.notNull(orders, "orders");
AssertUtils.isGtZero(newPrice, "newPrice");
if (ComparisonUtils.equals(getOrder().getPrice(), newPrice)) {
final BigDecimal reaminingAmount = this.getOrder().summary().getRemainToFill();
if (ValidationUtils.isGtZero(reaminingAmount)) {
return Optional.of(new OrderPortion(this.getOrder().getId(), reaminingAmount));
}
}
return Optional.empty();
}
}
I can't see any design flaws in this.
However, there are a couple of caveats:
I am talking about design flaws, not implementation flaws.
"I am thinking that these two instances could negatively affect each other, an endless loop or something in that sense."
Those would be implementation flaws (aka bugs), not design flaws. A lot more context is required to check for that kind of thing.
You have only shown us a tiny part of the design, with few clues as to how this fits into the "bigger picture".

OOP Class Responsibility

I'm developing a hobby project to properly understand encapsulation, what classes can be responsible for, and rules. I asked for a code review and assistance in another forum, but I don't agree with the approach given.
I have the following requirements:
An international student requires documents to complete the registration process, but domestic students don't.
StudentStatus Interface:
public interface StudentStatus {
Collection<String> retrieveDocuments();
StudentType retrieveStatus();
}
public final class Domestic implements StudentStatus {
private final StudentType type;
private final Collection<String> documents;
public Domestic() {
this.type = StudentType.Domestic;
this.documents = Collections.emptyList();
}
#Override
public Collection<String> retrieveDocuments() {
return this.documents;
}
#Override
public StudentType retrieveStatus() {
return type;
}
}
public final class International implements StudentStatus {
private final StudentType type;
private Collection<String> documents;
public International(Collection<String> documents) {
this.type = StudentType.International;
this.documents = Collections.unmodifiableCollection(documents);
}
#Override
public Collection<String> retrieveDocuments() {
return Collections.unmodifiableCollection(documents);
}
#Override
public StudentType retrieveStatus() {
return type;
}
}
Student class:
public final class Student {
//left out constructor and getters for other attributes.
public Collection<String> retrieveDocuments() {
return status.retrieveDocuments();
}
public StudentType retrieveStatus() {
return status.retrieveStatus();
}
public boolean isVerified(StudentType type) {
return this.retrieveStatus() == type;
}
}
University class:
public class University {
private final Map<Student,Collection<String>> registeredStudents;
private final StudentType type;
public University()
{
registeredStudents = new HashMap<Student,Collection<String>>();
type = StudentType.International;
}
public void add(Student student){
if (student.isVerified(type)){
registeredStudents.put(student, student.retrieveDocuments());
}else {
//throw an exception or handle error accordingly
}
}
}
Before I continue, I understand that this is a really over simplified application process. In the real world, a lot more has to happen before a Student can register. The student may have to go through entrance exams, and payment before registration begins. Also, in a realistic environment, this information would probably be stored in a database that the campus employees can access.
In the other forum, the conversation went into what information is being given out, and approaches were given.
Have a rule class, that takes the Student object and verifies that it
is in fact international and has documents.
The problem I have with this, is you're still going to have to ask the Student his/her status either with the retriveStatus() or isVerified(), I don't really see how to do it any other way.
Pass the Student and collection of documents separately to be added to the Map.
In the real world, the University set the rule as stated above and it's responsibility is to check if International students have documentation.
When I suggested the approach above with the add(Student student) they stated it wasn't a good idea because the rules can change, and you'll have to change the Student class as well as the University class.
However, in the real world, a student is well aware of his/her status and if he/she is domestic/international and in possession of documents that can be given to the school.
Given the above approach, is writing the add method this way a good idea? Is there a better approach than the add method?
tl;dr - If a Student has to follow the rules set by the University, how then would the Student object communicate with the University to get the data so that the University can ensure the student object is complying with the rules without breaking encapsulation?
The conversation in previous post was probably leading you in a generally good direction. The principle that applies most is the Open / Closed principle. https://en.wikipedia.org/wiki/Open/closed_principle.
Don't set yourself up to have to constantly modify a particular class or set of classes (in OO world at least) in an area you know is going to be a frequent vector of change. The principle applies equally in the functional world, but your example is using an OOPL.
Little hand-built rules engine is a pretty good solution for your stated problem. Particularly if you know the rule flows on pretty fixed inputs - like the University and the Student. DocumentsRequiredForInternationalStudents is a rule class in that architecture - only needs to change if something about that rule itself changes. New rule, which is going to happen a lot = add new class, not modify existing one.
Sometimes you don't know vector of change, harder to make decisions, but if it's obvious, don't architect a system where you'll have to violate open/closed constantly due to an known change vector.
There are different ways to implement little rules engines. One option (this is crappy pseudo-code so it takes less space)
interface RegistrationRule
boolean isRegistrationValid(Student student) //might need university too for some rules.
class DocumentsNeededForInternationalStudents implements RegistrationRule
boolean isRegistrationValid(Student student)
// return student.status is international and student has documents, or student status is domestic
// (this rule passes through as valid any domestic students).
class RegistrationRules
// (holds all the rules you will use - kind of a factory)
constructor -> add to static list of rules an instance of all your rules
boolean runRulesForStudent(Student)
//iterate through all rules, call isRegistrationValid, short circuit and return false if one of them false
class University
addStudent(Student student)
if (RegistrationRules.runRules(student).... else
That's just one way to throw it together, but you can see it's not really a lot of code. You have an interface, an implementation class for each rule, and a little rules engine class that applies each rule for you. New rule = new class, modify your constructor in the rules engine to add an instance of that class, done.
This pattern begins to struggle a bit when the properties and behavior that are needed in the rules are very diverse and not concentrated in the same small set of classes.
You said:
In the real world, the University set the rule as stated above and
it's responsibility is to check if International students have
documentation.
This means that the verification responsibility lies on University (and can be different for each University) and not the Student. All student can do is provide necessary information for University to verify.
The add method should get documents from retrieveDocuments and run through its rules to determine is student is allowed to be accepted.

Java calling a subclass method

When i try to create an instance of a class and add this to my arraylist i can't call methods defined in the child.
How do i make this work?
List class:
import java.util.*;
public class List {
private ArrayList<Person> persons;
public List(){
persons = new ArrayList<Person>();
}
public void addAssistant(){
Person person = new Assistant();
persons.add(person);
if(person instanceof Assistant){
person.assist();
}
}
}
Person class:
public class Person {
public Person(){}
}
Assistant class:
public class Assistant extends Person {
public Assistant(){}
public void assist(){
System.out.println("I am assisting!");
}
}
Compiler:
line: person.assist(); within the addAssistant() method in the List class.
Compiler error:
The compiler cannot find symbol - method assist().
You need an explicit cast:
if(person instanceof Assistant){
((Assistant)person).assist();
}
However, I think this type of logic should generally be discouraged.
You need to make a cast for use a subclass method
if(person instanceof Assistant){
((Assistant)person).assist();
}
Person class does not have assist method defined so you must explicitly cast to Assistant class e.g.
if(person instanceof Assistant){
((Assistant)person).assist();
}
You have to cast your Person into an Assistant like this:
if(person instanceof Assistant){
((Assistant)person).assist();
}
This type of casting howerver is an indication of flawed application design I think.
Just a sidenote:
You should use interfaces instead of concrete implementations. So you should replace this:
private ArrayList<Person> persons;
with this:
private List<Person> persons;
If you want your Persons to do their specific work and an Assistants work is assisting than you can work around this by creating an abstract method in Person
public abstract void doYourWork();
and you can implement that in Assistant:
#Override
public void doYourWork(){
// doing something
}
In this case you don't have to explicitly cast your Person objects.
If Person ain't going to have any concrete implementations you can make it an interface instead.
I would code it this way
public void addAssistant(){
Assistant assistant = new Assistant();
assistant.add(person);
assistant.assist();
}
There is no point in abstracting yourself from the knowledge that your recently created object is in fact an Assistant.
Abstracting yourself from the concrete type is a good way of reduce coupling between two pieces of code and it is necessary for doing nice things like polymorphism... but in this particular example you are showing us you are already tightly coupled to an Assistant (in fact you are instantiating it just two lines above).
Another possible way to implement this is to use polymorphism, you can do that by adding the assist() method to the interface of your Person.
public class Person {
public Person(){}
public void assist() {
//I'm a just a person who doesn't assist anywhere
}
}
By doing so you are going to be able to do what you were trying:
public void addAssistant(){
Person person = new Assistant();
persons.add(person);
person.assist();
}
However I wouldn't recommend that, mostly because you will start filling your Person interface with responsibilities that are not correctly placed there. It's all matter of design, you need to choose the better (and of course, the most confortable) solution for your particular problem.
Good Luck
Claudio
The way Java language has been designed, this doesn't compile (as you've figured it out as well). Think of it this way, all assistants are persons, but not all persons are assistants. If you use an explicit cast, you can do what you want to achieve (as NPE mentioned in his answer).

Is my DAO strategy ok?

I'm using Hibernate. The question is at the bottom.
The current strategy
It's simple.
First of all, I have a basic Dao<T>.
public class Dao<T> {
private Class<T> persistentClass;
private Session session;
public Dao(Class<T> persistentClass) {
this.persistenClass = persistentClass;
this.session = HibernateUtil.getCurrentSession();
}
It's nice as a base class and it passes the most common methods up to its Session.
public T get(Serializable id) {
#SuppressWarnings("unchecked")
T t = (T) this.session.get(this.persistentClass, id);
return t;
}
protected Criteria getCriteria() {
return this.session.createCriteria(this.persistentClass);
}
When there's need to use queries on the model, it goes into a specific DAO for that piece of model, which inherits from Dao<T>.
public class DaoTask extends Dao<Task> {
public DaoTask() {
super(Task.class);
}
public List<Task> searchActiveTasks() {
#SuppressWarnings("unchecked")
List<Task> list = (List<Task>) this.getCriteria()
.add(Restrictions.eq("active", true))
.list();
return list;
}
}
This approach has always worked well.
However...
However, today I found that many times an instance needs reattachment to the Session and a line similar to the following ends up happening:
new Dao<Book>(Book.class).update(book);
... which I find to be bad, because
I don't like specifying the redundant Book.class
If ever a DaoBook arises, this construct will become obsolete.
So I turned Dao<T> into an abstract class, and went on to refactor the old code.
Question
In order to remove the Dao<T> references from the codebase, I thought of two approaches:
Create specific DAOs for every class that ever needs attachment, which would generate many almost empty DaoBooks and the sort.
Create a class that owns a Dao<Object> and exposes only the attachment methods (i.e. save(), update() etc).
I'm tending to go with #2, but I thought this "AttacherDao" pattern might be bad, so I'd like your opinion.
Any cons for #2? Also, do you find anything wrong with "the current strategy"?
Our approach is to have a DAO object (derived from a commonDao) for each persistent class. In fact we define interface for this DAO class and each DAO decides which interfaces are opened up.
Using the following code, user cannot delete the PersistentClass.
interface PersistentClassDao {
void save(PersistentClass persistentObject);
}
Class PersistentClassDaoImpl extends CommonDao implements PersistentClassDao {
void save(persistentObject) {
persist(persistentObject);
}
Even though it has some additional overhead, this approach helps in unit testing appropriate code before exposing an interface.
We've chosen an approach similar to lud0h's, with the following twist:
abstract class<T extends IModelObject> JdbcCrudDao<T>{
void create(T dbo){}
T findByFoo(String foo){}
void update(T dbo){}
void delete(T dbo){}
}
class BarDao extends JdbcCrudDao<Bar>{
}
But, the twist is that we selectively expose methods on the Dao through a facade and forward only those we absolutely must.
class BarController implements IController{
private static final BarDao dao;
// ...
void update( IBar bar ){
dao.update(bar);
}
}
The only short-coming in all this is it requires some casting about if you wish to hide your database keys behind an interface type (which we do), but it's a pretty minor inconvenience versus the alternative (database code outside of the Daos).
Couple of questions
Are you frequently creating your DAO to do a single task or are these long lived?
What about using a static function? Clearly your Book object can be bind the DAO function to without the Book.class reference...
Otherwise, I'm a little worried about keeping the session object around instead of fetching whatever the current session is - isn't it considered "bad" to have long lived session objects? I'm not a master of DAO, so maybe I'm missing something here.

Does the code-to-interface principle apply to entity classes?

I'm trying to follow code-to-interface on a project. Should I be creating an interface first then implementing that interface for entity classes? I'm thinking this might be taking the interface first approach too far and entities should be ignored. This is what I mean...
public interface Address {
public String getStreet();
public void setStreet(String street);
}
#Entity
public class AddressImpl implements Address {
private String street;
public String getStreet(){
return this.street;
}
public void setStreet(String street){
this.street = street;
}
}
#Entity
public class OfficeImpl /* implements Office */ {
private Address location;
public Address getLocation(){
return this.location;
}
public void setLocation(Address location){
this.location = location;
}
}
public class Driver {
public static void main(String[] args) {
Office work = new OfficeImpl();
Address workAddress = new AddressImpl();
workAddress.setStreet("Main St.");
work.setLocation(workAddress);
}
}
I think creating Interfaces for Entities is probably not necessary.
The purpose of creating Interfaces (or at least, one of the purposes) is to make it easier to swap out one concrete implementation in favour of another. This is obviously a good thing for your DAOs, Business Logic etc.
But unless you have plans for the implementation of your entities to change as well, I would avoid it!
In your example, you are probably taking it too far, but once you add methods, write test cases and possibly use dependency injection, it will make more sense.
For simple projects like this, it is overkill, but once you get into a 'real' application, then it is often a good idea. Just be careful not to overdo it, everything doesn't need to implement an interface, just where it makes sense.
the interface for Entities should be the behaviors and properties that are common to all Entities!
public interface IEntity
{
int EntityId { get; set; }
bool FindById(int id);
bool Create(object [] values);
bool Delete(int id);
//etc.
}
sorry for the C# example, but the language doesn't matter. Interfaces are for 'plug compatability'.
I think when you're talking about entities, it's probably overkill.
Interfaces are useful when you're working with entities that have a common usage, but aren't necessarily the same. Can't think of a good way to explain it, but here's an example:
interface IFlaggable {
bool IsFlagged ...
string Reason ...
}
class ForumPost implements IFlaggable { }
class PrivateMessage implements IFlaggable { }
Hope that helps!
I generally don't make interfaces for data holding beans, that is I don't make interfaces for classes with primitive type values and getters/setters for them. Haven't really ever hit a moment where I would've needed interfaces for anything I usually use them for (polymorphism and mocking, mostly) so I haven't bothered doing that.
I guess I should point out that most of the time when I use databeans I also reflect the values from those same objects with custom classes which work like this:
Reflector r = new Reflector(new DataBean( [ values given through constructor ] ));
long someNumber = r.get("method", Long.class);

Categories