MVC. Implement Model Layout. My final solution. Success? - java

Before start work on implementation Model layout, I ask few question on this site:
Correct design for entity classes. Need recommendations
Java Generics. What benefit in my case?
and
Two classes with almost duplicate code inside
Users give me many good and perfect recommendations.
In result, I create next implementation for my Model Layout:
Can you please look on my screenshot. And tell me,
I correct understang all?
And my implementation success?
P.S. link on lange image: http://www.dropmocks.com/mBf62w

Your solution lacks of one more thing, which is Service Layer. This is important, since you will use DAOs within the service layer to perform some business logic. Usually Database Transactions are also defined on the service layer, so keep that in mind.
I would also get rid of Persistent interface, since I don't see how it helps in anything, and instead - I would use abstract class for PersistentImpl. AbstractEntity would be more appropriate name then.
Other than that - your solution is neat and clean - I'm using it across several project of mine and I'm very happy with it :)

I don't bother with a dao when I use hibernate, seems unnecessary/superfluous and just have entities and a service layer (and a controller and view).
There are however differing views on this.

Related

In modern application design, how do you implement / between TransferOject and BusinessObject

With organizations which are slow to adapt to modern technology finally junking EJBs and getting ready to transform to SpringBoot, Microservices, REST, Angular, there are some some questions application design. One being about TransferObjects and Business Objects
When the call comes to the REST Controller, is it still popular to populate a TO (POJO) and then make Service call, which in turn populates a BusinessObject and then calls a Repository service?
OR
At the REST Controller layer do we directly populate the BO and send it to the Service (This does not make any sense to me, because a BO is populated only during the execution business logic).
If nowadays its still Option 1, then how do we avoid writing to exactly similar POJO classes in most cases (in order to use BeanUtils.copyProperties()), with the BO decorated with #Id, #Column etc.
To elaborate on #Turing85's comments...
Option 1 usually (see the end of my answer) makes infinitely more sense. It's a question of responsibility (purpose) and change; the two logical components you refer to, a REST API and a repository / system service:
Responsibility: a REST service cares about working with its callers, so ideally when designing a REST API you should be involving someone from the client-side (client as in caller), because if the API doesn't work for them it's not going to be an effective API. On the other hand, repositories are somewhat self-centered, and may need to consider things that are or no interest to API callers (and vis-versa).
Change: if you pay attention to design principles, like SOLID, you'll know that part of a system should do one job - as a way of limiting the reasons why it needs to change (see: SRP). Trying to use one object across both outward-facing API's, and inward-facing repositories, is asking for trouble because it's trying to do too much - its trying to help solve problems in two very different parts of the wider solution, and thee both have very different change drivers working against them. Turning85's comment about the persistence layer stems from the same idea.
"Option 1 usually makes infinitely more sense":
One case where the REST API's objects will / can bear a very close resemblance to those that hit the actual repository (or even be reused, I guess) is when the REST API is a System API - i.e. a dedicated façade / proxy to the repository. In this case, the System API is largely driven by the repository i.e. the main change driver is just the repository.
After researching a bit I agree, keeping things simple will result in simpler code. I found a nice simple way to take care of this manual work.
https://www.baeldung.com/entity-to-and-from-dto-for-a-java-spring-application

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.

Design Web application with spring-mvc, how to choose data, model objects & ui objects?

I built a web application using spring-boot, spring-mvc and hibernate. I used the DAO in UI directly by just wrapping them in another objects. It makes my DAL and Presentation layer quite tightly coupled.
As per my understanding, mvc architecture reduces coupling by separating out each component and i worked against that. :(
Is it okay to do what i did? As it saves presentation layer object conversion to DAO to persist them in DB.
What is recommended and best way to design? what will the pay-off with current design (quite tightly coupled)?
I'm not able to figure out, could anyone please help me to understand it.
Thanks in advance!!
I used to do it like that:
I create several layers: the UI layer, the BLL layer and the DAL layer. Then I create the models for each of them. For example: MyUser_UI.java, MyUser_Bll.java and MyUser_Dal.java. This models are so-called POJO, they are used to carry data between layers. As you can see, MyUser_xxx.java(s) have similar property, so I use a automatic object mapper named DozerBeanMapper to help me to transmit data from one to another. That's what I have done.
I promise that is a practical method, however, obviously, it is far from the best. Too many classes I must maintain. Think about that: one day I want to add a new property for MyUser_xxx.java, I must change three places. I often miss something and get errors. So I changed to another way.
I extract the POJO to a separate package. All the three layers can access this package. In doing so, I feel better. But it also brings some other problems. POJOs requirement for each layer is often a bit different. So I have to create the base class MyUser.java, and the MyUserEx.java derived from the base.
It is a bit disappointing that I don't think there is a best design. But we can combine many methods to make our code better. Witch do you prefer? It's up to you.
Martin Fowler has a fairly seminal article on layering from his P of EAA book:
http://martinfowler.com/eaaCatalog/serviceLayer.html

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.

Model - persistence and service layers? True?

I am trying to confirm whether this statement is true:
Model includes both:
persistence layer: essentially DAOs + classes representing tables + DTOs
service layer: Combinations of DAOS + some logic
Could you also please reference/support your answer? I believed I've seen in Spring Framework good diagram, but no matter how searched this time I can't find it.
And the other point: I was always wondering why we abstract stuff so heavily that at some point people just stop understanding, is it done to increase our own value? :\
For example analysing Spring MVC I can say that central piece is controller no matter how you name other layers it is Controller who decides where to go what to extract , how to validate it and which view/controller to pass it on. Yet this simple statement is never found in formal articles keep confusing people.
So Controller is our god. Controller asking for some method within a class that call methods of another class. On top of it all is wired with dependency injection as we only need a single instance for objects of singleton nature. Controller>Service>DAO that's it .I would really appreciate book written by pragmatics.
If people would write books based on how things really are and not how to make look them beautifully drawn in diagrams or written the endless questions as such would never raise in a first place. And I thank stackoverflow for people that always show me the path. ;-)
MVC and the DAO/Service architecture are less concepts which are contained within each other than which sit next to each other.
In MVC, your controller takes care of fetching all the data, placing it in a model in some way, and passing the model to the view to be rendered. If you are also using DAO/Service architecture, your DAOs/Services might return an entity which contains all the information you will be displaying on a given page, and people often use these as the model for the view if things are relatively simple.
The problem with this tactic is you end up having dependencies between your views and the specific implementation of your model. Also, if you later decide you need some extra information which is not included in your model, you'll have to rewrite your view to account for this. This is why it is often suggested you do as much preparation of your data in your controller before passing a very simple model (a Map) to the view.
Here's a diagram showing the separation of layers:

Categories