Obvious flaws in my EJB3 design - java

I have a domain object called VehicleRecord which is a hibernate entity. CRUD operations on these VehicleRecords are handled through an entity access object implemented as a stateless session bean interface
#Local
interface VehicleRecordEao {
void add(VehicleRecord record);
List<VehicleRecord> findAll();
...
}
#Stateless
class HibernateVehicleRecordEaoBean implements VehicleRecordEao { ... }
From a business layer perspective removing and adding these records is more than just a CRUD operation. There may be logging and security requirements for example. To provide these operations to clients sessions beans are created in a business layer.
#Local
interface VehicleRecordManager {
void createVehicleRecord(VehicleRecord record);
List<VehicleRecord> findAll(String make, String model);
...
}
#Stateless
class VehicleRecordManagerBean {
public void createVehicleRecordManager(VehicleRecord record) {
//business rules such as logging, security,
// perhaps a required web service interaction
//add the new record with the Eao bean
}
...
}
Controllers work between the presentation layer and the above business layer to get work done, converting between presentation objects (like forms) and entities as necessary.
Something here is not right (smells). I have a class called Manager which has got to be a red flag, but several examples in EJB books actually suggest this kind of high level class and tend to use the name manager themselves. I am new to EJB design but in OO design making high level classes called Manager or Handler or Utility screams of procedural and requires one to rethink their design.
Are these procedural-utility-class session beans the normal pattern, or is bad to organize your session by a bunch of methods related only to the entity they operate on? Are there any naming conventions for session beans? Should the Eao's and business session beans work at the same layer?
If there is a less smelly alternative to this pattern I would love to know, thanks.

Your approach is more-or-less standard. Yes, at a fundamental level this is a procedural approach and goes hand-in-hand with what has been dubbed the Anemic Domain Model "anti-pattern". The alternative is to incorporate your business logic into your domain model so as to create a more OO design where your operations are coupled with your DO's. If you were to go down this route you should be aware of the inherent pros and cons. If you feel that your approach makes the most sense, is easy to understand, test, scale, etc... Then role with it. I have worked on several n-tier projects where this exact "procedural" style is used -- rest assured it is quite standard in EE applications to do things this way.

It's an age old discussion. Should a bread bake itself, or does an oven bake it? Does a message sends itself, or does the postoffice do it? Do I send a message to my friend Pete by asking him to send a message to himself?
According to those who came up with the term ADM, it's more "natural" and more "OO" to let each object do all those things itself. Taken to the extreme (which no one advocates of course, but just as an example) class User would contain all logic for the entire application, since ultimately the user does everything.
If you use slim entities (entities containing only data) and service or DAO objects to work with them, then you're not necessarily not doing OO. There is still a lot of OO going around. Services implement interfaces, inherit from base classes, have encapsulated state (e.g. the EntityManager in JPA), have transparent interceptors via dynamic proxies (e.g. to check security and start/commit a transaction), etc etc.
The term "Anemic" has a definite negative association, but calling the same thing "Slim" actually sounds good. This isn't just a case of using different names to hide code smells, but represents a different thinking among different groups of people.

I think it's up to your taste, and depending on the complexity of your application - these things matter less / more. I think in design, you need to simply thing around the line of:
"If someone new came in without any prior knowledge of the system in question - is it intuitive enough for that person to follow and trace the codes, and straight forward to find where things are"
In your case - naming the EJB related to the Entity Object makes it straight forward and simple - what I dont get is why did you separate it to 2 classes EAO and Manager. Why dont you just combine them into one, so if the EJB/Bean class deals with VehicleRecord Entity, then it will be the "VehicleRecordEAO" or "VehicleRecordManager" or "VehicleRecordAccess" or anything really.
I think EAO / DAO / Access sounds more like getter / setter - or any other simple operations. I dont see anything wrong with "Manager" and make it consistent across the board that all business layer will be called "Manager".
Or if you feel better, think of it as the Facade Pattern - so you can call your business layer (the Manager) as VehicleRecordFacade and VehicleRecordFacadeBean.
That way you basically follow the name and concept of Facade pattern, where it becomes intermediary between application layer and the data layer.

Something here is not right (smells).
I have a class called Manager which
has got to be a red flag
My answer here is towards this concern of yours.
Yes. It is a red flag. Naming a class like "VehicleRecordManager" would be a code smell suggesting that Single responsibility principle would be violated sooner or later.
To elaborate, let me take a few use cases to deal with VehicleRecord
Buy a vehicle
Rent a vehicle
Search for a vehicle
Sell a vehicle
Find Dealers
In most Java applications when we write up a "VehicleService" ( or "VehicleManager") all the above operations would be placed in this class ! Well, this one is easy to do, but hard to maintain. And certainly this class has a lot of responsibilities, hence many reasons to change. (violating Single responsibility principle )

Would calling it VehicleDao eliminate some of the smelliness? A simple change, but indicates clearly it's concerned with data access concerns.

Related

Unit Testable convention for Service "Helper Classes" in DDD pattern

I'm fairly new to Java and joining a project that leverages the DDD pattern (supposedly). I come from a strong python background and am fairly anal about unit test driven design. That said, one of the challenges of moving to Java is the testability of Service layers.
Our REST-like project stack is laid out as follows:
ServiceHandlers which handles request/response, etc and calls specific implementations of IService (eg. DocumentService)
DocumentService - handles auditing, permission checking, etc with methods such as makeOwner(session, user, doc)
Currently, something like DocumentService has repository dependencies injected via guice. In a public method like DocumentService.makeOwner, we want to ensure the session user is an admin as well as check if the target user is already an owner (leveraging the injected repositories). This results in some dupe code - one for both users involved to resolve the user and ensure membership, permissions, etc etc. To eliminate this redundant code, I want make a sort of super simpleisOwner(user, doc) call that I can concisely mock out for various test scenarios (such as throwing the exception when the user can't be resolved, etc). Here is where my googling fails me.
If I put this in the same class as DocumentService, I can't mock it while testing makeOwner in the same class (due to Mockito limitations) even though it somewhat feels like it should go here (option1).
If I put it in a lower class like DocumentHelpers, it feels slightly funny but I can easily mock it out. Also, DocumentHelpers needs the injected repository as well, which is fine with guice. (option 2)
I should add that there are numerous spots of this nature in our infant code base that are untestable currently because methods are non-statically calling helper-like methods in the same *Service class not used by the upper ServiceHandler class. However, at this stage, I can't tell if this is poor design or just fine.
So I ask more experienced Java developers:
Does introducing "Service Helpers" seem like a valid solution?
Is this counter to DDD principals?
If not, is there are more DDD-friendly naming convention for this aside from "Helpers"?
3 bits to add:
My googling has mostly come up with debates over "helpers" as static utility methods for stateless operations like date formatting, which doesn't fit my issue.
I don't want to use PowerMock since it breaks code coverage and is pretty ugly to use.
In python I'd probably call the "Service Helper" layer described above as internal_api, but that seems to have a different meaning in Java, especially since I need the classes to be public to unit test them.
Any guidance is appreciated.
That the user who initiates the action must be an admin looks like an application-level access control concern. DDD doesn't have much of an opinion about how you should do that. For testability and separation of concerns purposes, it might be a better idea to have some kind of separate non-static class than a method in the same service or a static helper though.
Checking that the future owner is already an owner (if I understand correctly) might be a different animal. It could be an invariant in your domain. If so, the preferred way is to rely on an Aggregate to enforce that rule. However, it's not clear from your description whether Document is an aggregate and if it or another aggregate contains the data needed to tell if a user is owner.
Alternatively, you could verify the rule at the Application layer level but it means that your domain model could go inconsistent if the state change is triggered by something else than that Application layer.
As I learn more about DDD, my question doesn't seem to be all that DDD related and more just about general hierarchy of the code structure and interactions of the layers. We ended up going with a separate DocumentServiceHelpers class that could be mocked out. This contains methods like isOwner that we can mock to return true or false as needed to test our DocumentService handling more easily. Thanks to everyone for playing along.

"Container" classes, good or bad practice, why?

I'm curious as to which is the better practice and the reasoning behind it, for this example I'm going to be using a social application which contains a 'friends' and a 'ignore' list with some custom logic based on them, (For sending messages directly, etc)
Which would be the better practice, and why?
Scenario 1:
class user {
List<> friends;
List<> ignores;
...
logical methods here
}
Scenario 2:
class User {
Social social;
...
}
class Social {
List<> friends;
List<> ignores;
...
logical methods here
}
I've seen both scenarios used throughout numerous applications and I'm curious as to which is the "Correct" way to lay it out in java, these will have methods such as
#addFriend(User user)
check ignore
check valid user
check other info
add to list
end
#getFriend(int id)
find friend by id
check online status
return friend
It seems like while have a 'Social' class may be a cleaner approach, does it really follow good practices? Seems like it'd use more memory/user just for cleaner code.
The reason why you have such constructs as your Social, most of the time, is that they represent a logical set of data and operations which is needed for different entities in your application.
If nothing other than User has those properties and actions, then there is no point in doing it separately from User. But you may design it separately anyway, for future uses (for example, if you want to be able to expand it later and you believe there will be other entities which will need Social functionality).
Looking at this from an object-oriented viewpoint, it means that the Social is a type. And then you have to ask yourself, is whether your User is_a Social or whether your User has_a Social. Does it make sense to say that the user has a "social subsystem" or is the user a "social object"? If the correct relation is is_a, then User should extend Social. If not, it should have a Social member, such as you described.
However, in Java, since you can't have multiple inheritance of implementation, sometimes your type may inherit from several types, and you have to decide which of them to extend. Many times, you simulate multiple inheritance of implementation, by having a member of what should have been the "second parent class", declare all the methods in your class, and delegate them to that member.
So the general guidelines are, more or less:
If in your application's domain, the only class where it will make sense to have friends and ignores and their operations is User, and no other conceivable entity would ever need them, then implement them directly in User.
If other entities may need similar functionality, and not all of them extend User anyway, you may consider this functionality to be an entity or class in its own right, and then you should have every class which has an is_a relationship to this entity extend it.
If Java's limitations of multiple inheritance don't allow extending directly, as it makes more sense for the class to extend some other class, you should embed an object and delegate the operations.
There may be other practical reasons to separate the Social entity from User, despite User being the only class to use them. For example, if you have several different possible implementations of "social" behavior, you may want to be able to use various Social subclasses as "plug-ins" inside User, rather than subclassing User.
Don't worry about memory so early. Go for readable/cleaner code. Premature optimization is root of all evil.
This is really based on the logic of your program. But consider that increasing the number of classes unnecessarily, is not good practice.
In your example, if the User class only contains a Social field, and you will just delegate all the method calls to the Social class, then go with scenario one.
On the other hand, if the User class has many more fields, like name, date of joining ... then it would be even better to create a separate class for such fields such as UserInfo in order to better structure your program and enhance code readability.
Now the main concerns are not the memory or performance costs of class structure.
Way more important are readability and clean code, AND the possibility to persist domain classes in a DB in the most simple and efficient way.
The later include composition or aggregation concern which is specific for different DB's.
You should care about the design aspects becoz with this you will have maintainable,scalable and readable code.
Now going by your example , i find second scenario as good case as it follows the SRP(Single Responsibilty Principle)
Don't worry about memory here as it wont make iota of difference here.
So do you want to do something like:
for(Connection connection : userSocialConnections ){
sendMessageTo(connection);
}
If so, then the method sendMessageTo would need to accept a connection (friend or ignored, basically a user) and probably if the runtype connection is ignored (or has blocked the user) then the sendMessageTo will return without sending a message polymorphically. This would require that in java that the IgnoredPeople And Friends are subtypes of something called as Connection(or people or anything you like; in fact, a connection is also a user - current or potential, isn't it?). This approach seems (to me) more like thinking in problem domain. Storing as two list inside user or inside social inside user does not matter much as long as they both (ignored and friends) have a common interface.
I would ask, what all other scenarios can be there for user's friends or ignored list. Do they need to be loaded lazily or stored separately.

How many GWT services

Starting a new GWT application and wondering if I can get some advice from someones experience.
I have a need for a lot of server-side functionality through RPC services...but I am wondering where to draw the line.
I can make a service for every little call or I can make fewer services which handle more operations.
Let's say I have Customer, Vendor and Administration services. I could make 3 services or a service for each function in each category.
I noticed that much of the service implementation does not provide compile-time help and at times troublesome to get going, but it provides good modularity. When I have a larger service, I don't have the modularity as I described, but I don't have to the service creation issues and reduce the entries in my web.xml file.
Is there a resource issue with using a lot of services? What is the best practice to determine what level of granularity to use?
in my opinion, you should make a rpc service for "logical" things.
in your example:
one for customer, another for vendors and a third one for admin
in that way, you keep several services grouped by meaning, and you will have a few lines to maintain in the web.xml file ( and this is a good news :-)
More seriously, rpc services are usually wrappers to call database stuff, so, you even could make a single 'MagicBlackBoxRpc' with a single web.xml entry and thousands of operations !
but making a separate rpc for admin operations, like you suggest, seems a good thing.
Read general advice on "how big should a class be?", which is available in any decent software engineering book.
In my opinion:
One class = One Subject (ie. group of functions or behaviours that are related)
A class should not deal with more than one subject. For example:
Class PersonDao -> Subject: interface between the DB and Java code.
It WILL NOT:
- cache Person instances
- update fields automatically (for example, update the field 'lastModified')
- find the database
Why?
Because for all these other things, there will be other classes doing it! Respectively:
- a cache around the PersonDao is concerned with the efficient storage of information to avoid hitting the DB more often than necessary
- the Service class which uses the DAO is responsible for modifying anything that needs to be modified automagically.
- To find the database is responsibility of the DataSource (usually part of a framework like Spring) and your Dao should NOT be worried about that. It's not part of its subject.
TDD is the answer
The need for this kind of separation becomes really clear when you do TDD (Test-Driven Development). Try to do TDD on bad code where a single class does all sorts of things! You can't even get started with one unit test! So this is my final hint: use TDD and that will tell you how big a class should be.
I think the thing to optimize for is that you can accomplish a result in one round trip to the server. I have an ad-hoc collection of methods on my service object, one for each situation the client finds itself in when it has to get something done. You do not want the client to RPC to the server several times in a row while the user is sitting there waiting.
REST makes things orthogonal, but orthogonality has a cost: there is a reason that the frequently used verbs in languages are irregular. In terms of maintaing clean orthogonal structure to your app, make sure your schema is well-designed. That is where each class should have semantics orthogonal to that of the other classes. When the semantics of each RPC call can be stated cleanly in the schema there will be no confusion as to what they mean, even if they aren't REST-fully ideal.

Is it deemed bad practice to inject the DAO into the constructor? and if so, why?

I have a (DAL) Data Access Layer (but this question is relevant for DAOs as well) which is communicating with a restful web service in android (which is less relevant other than the fact that I am not wanting to include heavy restful libraries as the interaction isn't so complex).
I have a object which wraps a list which is populated by information from this data access layer, as the user scans down and reaches the bottom of this list, this object retrieves another set of information from the DAL.
I would like the calling class of this list wrapping object to only have to make calls to the the list wrapping object and not the DAL (or a DAO). I could then construct a single DAL and pass it to the constructors of these list wrapping objects, then the calling class can just keep making calls to this list wrapping object and that object can handle the retreival of new information.
So, does this sound like bad practice or just a really bad explanation?
Is it a bad idea to inject DALs and DAOs in the constructor of the domain object?
The answer depends on whether you feel strongly about "anemic domain models" and mixing object-oriented with functional programming.
One problem is that you'll create a cyclic dependency that way: model and persistence packages have to know about each other. If you use a more functional style, and don't give a DAO reference to a model object, then it's a one-way relationship.
I wouldn't like your design much. I fear that it's too coupled. I'm not bothered by mixing a functional style in.
Domain Objects are typically data carriers without any real logic. I would hence consider it bad design to tightly couple it with your DAO logic. The general logic might go something like:
public class DataService {
private DAO dao;
}
public class UserService {
private DataService svc;
public DomainObject createDomainObject() {
return new DomainObject(dao.getData());
}
}
You are introducing a circular dependency there, so it's not the best design.
If you are developing an android app, and you are scrolling a list, then SlowAdapter and EfficientAdapter are probably what you are looking for.
If I understood you correctly what you are implementing is pagination. And your solution for it is how I would (and have) implemented it myself.
Passing the DAL to the constructor is not bad per se. Best practise would be using a Dependency Injection framework (Spring is a prominent example) in-order to avoid "hard coded" dependencies between layers.
But since you mentioned Android I doubt that using such a framework is a good idea or even possible. (Maybe Android has some sort of DI build-in?)
To summarize you seem to have given some thought about your application architecture. I wouldn't worry about passing arguments to a constructor.

How to avoid having very large objects with Domain Driven Design

We are following Domain Driven Design for the implementation of a large website.
However by putting the behaviour on the domain objects we are ending up with some very large classes.
For example on our WebsiteUser object, we have many many methods - e.g. dealing with passwords, order history, refunds, customer segmentation. All of these methods are directly related to the user. Many of these methods delegate internally to other child object but
this still results in some very large classes.
I'm keen to avoid exposing lots of child objects
e.g. user.getOrderHistory().getLatestOrder().
What other strategies can be used to avoid this problems?
The issues you are seeing aren't caused by Domain Driven Design, but rather by a lack of separation of concerns. Domain Driven Design isn't just about placing data and behavior together.
The first thing I would recommend is taking a day or so and reading Domain Driven Design Quickly available as a free download from Info-Q. This will provide an overview of the different types of domain objects: entities, value objects, services, repositories, and factories.
The second thing I would recommend is to go read up on the Single Responsibility Principle.
The third thing I would recommend is that you begin to immerse yourself in Test Driven Development. While learning to design by writing tests first won't necessarily make you designs great, they tend to guide you toward loosely coupled designs and reveal design issues earlier.
In the example you provided, WebsiteUser definitely has way too many responsibilities. In fact, you may not have a need for WebsiteUser at all as users are generally represented by an ISecurityPrincipal.
It's a bit hard to suggest exactly how you should approach your design given the lack of business context, but I would first recommend doing some brain-storming by creating some index cards representing each of the major nouns you have in your system (e.g. Customer, Order, Receipt, Product, etc.). Write down candidate class names at the top, what responsibilities you feel are inherent to the class off to the left, and the classes it will collaborate with to the right. If some behavior doesn't feel like it belongs on any of the objects, it's probably a good service candidate (i.e. AuthenticationService). Spread the cards out on the table with your colleges and discuss. Don't make too much of this though, as this is really only intended as a brainstorming design exercise. It can be a little easier to do this at times than using a whiteboard because you can move things around.
Long term, you should really pick up the book Domain Driven Design by Eric Evans. It's a big read, but well worth your time. I'd also recommend you pick up either
Agile Software Development, Principles, Patterns, and Practices or Agile Principles, Patterns, and Practices in C# depending on your language preference.
Although real humans have lots of responsibilities, you're heading towards the God object anti-pattern.
As others have hinted, you should extract those responsibilities into separate Repositories and/or Domain Services. E.g.:
SecurityService.Authenticate(credentials, customer)
OrderRepository.GetOrderHistoryFor(Customer)
RefundsService.StartRefundProcess(order)
Be specific with naming conventions (i.e. use OrderRepository or OrderService, instead of OrderManager)
You've run into this problem because of convenience. i.e. it's convenient to treat a WebsiteUser as an aggregate root, and to access everything through it.
If you place more emphasis on clarity instead of convenience, it should help separate these concerns. Unfortunately, it does mean that team members must now be aware of the new Services.
Another way to think of it: just as Entities shouldn't perform their own persistence (which is why we use Repositories), your WebsiteUser should not handle Refunds/Segmentation/etc.
Hope that helps!
A very simple rule of thumb to follow is "most of the methods in your class HAVE to use most of the instance variables in your class" - if you follow this rule the classes will be automatically of the right size.
I ran into the same problem, and I found that using child "manager" objects was the best solution in our case.
For example, in your case, you might have:
User u = ...;
OrderHistoryManager histMan = user.getOrderHistoryManager();
Then you can use the histMan for anything you want. Obviously you thought of this, but I don't know why you want to avoid it. It seperates concerns when you have objects which seem to do too much.
Think about it this way. If you had a "Human" object, and you had to implement the chew() method. Would you put it on the Human object or the Mouth child object.
You may want to consider inversing some things. For example, a Customer doesn't need to have an Order property (or a history of orders) - you can leave those out of the Customer class. So instead of
public void doSomethingWithOrders(Customer customer, Calendar from, Calendar to) {
List = customer.getOrders(from, to);
for (Order order : orders) {
order.doSomething();
}
}
you could instead do:
public void doSomethingWithOrders(Customer customer, Calendar from, Calendar to) {
List = orderService.getOrders(customer, from, to);
for (Order order : orders) {
order.doSomething();
}
}
This is 'looser' coupling, but still you can get all the orders belonging to a customer. I'm sure there's smarter people than me that have the right names and links referring to the above.
I believe that your problem is actually related to Bounded Contexts. For what I see, "dealing with passwords, order history, refunds, customer segmentation", each one of these can be a bounded context. Therefore, you might consider splitting your WebsiteUser into multiple entities, each one corresponding to a context. There may arise some duplication, but you gain focus on your domain and get rid off very large classes with multiple responsibilities.

Categories