Marcos
Marcos

Reputation: 4643

Anemic domain object?

In my system, an user can publish any number of trips. Mi User class (domain object) is like this

public class User {
    private String name;
    private String id;
    /* More private fields */

    /* getters and setters */
}

So if I want to get all the trips of the user with id = 1:

/* Domain Layer */
public class UserManager {
    ...
    public Trip[] getAllTrips(int userId) {
        dao.getAllTrips(userId);
    }
    ...
 }

/* DAL Layer */
public class UserDaoImpl implements IUserDao {
    public Trip[] getAllTrips(int userId) {
        /* jdbc here */
    }
}

It works, but I think my User class suffers the 'anemic domain problem' (or the anemic POJO problem,does it exists?): only has private fields and 'getters' and 'setters' (and all my POJO's the same).

I've thought another approach:

public class User {
    /* More private fields */
    private Trip[] trips;

    /* getters and setters */
    public Trip[] getTrips() {
        return trips;
    }
    ...
    public void addTrip(Trip trip) {
        // add the trip
    }
}

And

public class UserManager {
    public Trip[] getAllTrips(int userId) {
        User user = dao.getUser(userId);
        return user.getTrips();
    }
 }

With this second approach the User class has more functionality but the trips are not stored in the database.

I am missing something? I'm newbie with DAO and I don't know if I'm taking the correct approach.

Thanks (yeah, my English sucks).

Upvotes: 3

Views: 379

Answers (1)

Andrzej Bobak
Andrzej Bobak

Reputation: 2112

Why not also add the getAllTrips function to User class? As long as your function works on one user object, add functions to the User class.

UserManager class would make sense if you performed action on multiple users e.g.

cancelTrip(int tripId) 
{ 
    // remove trip from all users 
} 

Upvotes: 1

Related Questions