Architecture and packages - java

In a layered architecture, you have a presentation layer, logic layer and data layer.
So far, I've been grouping classes into domain, service and dao packages. This represents the model with POJOs/JPA Entities, the business logic and data access layer.
I suppose the domain and services could be grouped to form the logic layer but that leaves a question mark on the presentation or UI layer. Are there any conventions, even unwritten, in terms of grouping classes into packages by their nature in this layer? Or is this left to the appreciation of whoever is leading a project?
As an extra indication, I'm experimenting with web applications at the moment and using a "servlet" package to group servlets and a "web" package for ResponseHeaderFilters, ServletContextListeners and utility classes. I would be interested to hear how things are done with a desktop application.

I've never heard of package naming conventions with regard to the architecture. The only convention or 'best practise' I know is that your package names should start with a unique pattern, most often formed of a reversed domain name (like com.mycompany) or so. Just to make sure that you do not add classes from different libraries to the same package (namespace) which might lead to unexpected side effects.
But anyway, it's increases readability if you name the packages after the tier or usage. I've seen a scheme like the follwing which I personally liked because it was easy to find and identify the classes, and easy to extend:
com
.company
.product
.module1
.server
.function1
.impl
.client
.function1
.common
.function1
.impl

I've never really seen too much of an issue with this.
If you look at the class diagram for your project, you will almost instantly see logical groupings, and the tree structure of the packages tends to map easily to any grouping you need.
using the reverse domain name system (com.company.product...) you will never find a collision even within your own company.
Using Andreas_D's example, under .server and .client you may actually have an additional 3 or 4 levels of packages with dozens or hundreds of individual packages inside it if your project is large enough to warrant that.. but the structure at that level tends to come out of your product design.
Note: This similar question seems to be getting some good descriptions how to use packages:

Related

How to share entity between REST service between two microservices?

I have created two micro-services using java. I need to make a REST api call from service A to service B. The data sent will be in JSON format. Using jax-rs I need to create entity class in both the service.
Since both the entity class be same in both the projects. Do i
Create an common jar and use is for all my entity/domain objects? Does this make my microservice more tightly coupled?
Do i create the same class in both the microservice projects? This will just mean repeating the work in both the projects?
Is there a better way to communicate between the sevices?
In terms of having your two micro services independent and having them also independent in the future I would also duplicate the code. We had the exact same situation before. Several microservices seem to use some "common" classes that can be put to a seperate jar.
In the end we had following situation:
several (5+) services using the same JAR
turned out that classes that we thought are the same, seemed to have slightly different semantics in different services
a change on one of the classes more or less forced us to have a release on every microservice, when it came to releasing (no independency here anymore)
developers tend to see "common" behavior everywhere, so you most likely end up with some "Helper/Utility" classes there as well which is in the meanwhile considered a code smell in OOP
Long story short, in the meanwhile we switched to having the code duplicated, which gives us the freedom to handle our mircoservices really independently, as we only need to stick to the service contract. What happens internally is fully up to the service and we don't have to release all services in the end of an iteration. I'm not saying that the other option is wrong, but it turned out that it was not suitable for us. If you really see common classes between two services and you are sure you don't mess your common library up with other crap, your save to go.
EDIT
Maybe as follow up, we had the same discussion in regards of tests (unit and integration) having share test code in some common classes. In the end this was hell, as every slight change in code or acceptance criteria made 50% of tests fail. Meanwhile our strategy is to not share anything on test level and have everything right at the tests place. By that you are super fast in eliminating or changing tests. In the end the lesson for us was to keep business code as clean and elegante as suitable and the test code in a way to give us the least headache possible.
Edit2
Meanwhile, we define all our REST interface with open api specifications and create the actual DTO objects that are exchanged via the maven plugin openapi-generator. The spec resides in the project that implements the interface and it is published to artifactory. The project implementing the client pulls it and creates DTOs based on that. By that, you have a single point of truth and no need to write DTO boilerplate code.
I'd say it depends on the situation. If you use a shared package, this will introduce a coupling between the two projects. This makes sense, if both of the project build up on the same data classes and therefore will have the same dto objects to work with. Ideally you would have your own nexus which simplifies the usage of the shared artefact.
Otherwise, if only a few classes are redundant I probably would implement it in each sevice separately, which decouples them too.
I am afraid that you need to decide which one the right solution is for your project.
This is common situation where we as developer gets confused. I would suggest to have a common jar(shared) which can be used in both micro services (A and B). It is nothing but sharing a third resource as we use third-party libraries.
In my current project we were in the same situation and we found the best approach to have separate shared libraries(api-shared as name) and consuming it as jar in different micro-services.
In your second approach you ended up with redundant code and also difficult to maintain. Lets say if you have any changes in entity then you have to change in both the entities which is not quite a good way to synchronize the thing.
All in all I would suggest you to use shared jar for both micro services.
Regards
Techno

Android App Architecture : How should the packages be formed?

I am new to android programming. I often see that programmers create packages as collection of activities, fragments, adapters, etc. To me it seems more intuitive to put all java code required for an activity/screen in one place. For example: For home screen, I will keep the activity, fragments, adapters, custom views, etc all at one place.
Is there is any definite reason the the general practice or is it just a traditional practice ?
This has to do with creating components, reusable objects and code maintenance in a codebase as it grows. Your approach will work for a small application, and there is no rule against it. However, generally creating package/file structures according to the recommended and common approaches makes it easier to make modifications to code and work with others on the same project. Consider the following:
If you have many Activities spread across many packages or folders, then someone tasked with changing the UI will have to traverse those packages. That makes it difficult to identify UI patterns that could be used across Activities and even harder to use those patterns, since you will need to implement them in each package/folder.
This also creates a problem seeing less obvious patterns in non-UI components like data object models, view controllers, etc. For example, if you need a "user" object in two different Activities do you create 2 different objects? This is not reusable code.
So let's say you decide to reuse the "user" object so that you only have 1 class. Then do you sub-class in the other packages that need it in order to follow your pattern? Then if one UI element needs a new method, do you implement it in just that place? Or the base object?
Or do you make the "user" object public and reference it from other packages/folders? If this is your answer then you will begin to create objects in places based on the evolution of the code, instead of based on logic or ease of maintenance. Among other things, this makes it very difficult to train a new person on "where everything is" in your codebase. The "user" object will sit in one place, and then the "user account" object ends up where it is first needed, but not likely to be with the "user" object.
As a project grows to hundreds of classes, I think it is obvious that this approach becomes unmanageable for many applications. Classes will appear in packages based on the UI requirement, not based on the function it performs. Maintaining them becomes challenging.
For example in the case of Lollipop to Marshmallow, Apache http became deprecated. If you had this dependency scattered throughout your project, then you will be looking in a lot of places at how to handle this change. On a small project that might be fine, but on a larger project if you try to do this while other development is taking place, this can become a real mess since you are now modifying across many packages and folders instead of in only a few locations.
If, however, you have a Data Access Layer or Model Layer components that encapsulate the behavior in one or several folders, then the scope of your changes is easier to see to those around you. When you merge your changes into the project, it is easy for the people you work with to know if other components were impacted.
So while it is not necessary to follow these guidelines (especially for small projects), as a project grows and several or many people become involved in the development, you will see variations but the general practice is to group by purpose or function rather than group by UI / visual component. If you start off with some of this in place, you will have less work later to deal with the change. (However, starting with too much structural support early in a project can put the project at risk of never being completed...)
Several answers provides links to the guidelines. I hope this answer helps to explain why those guidelines exist, which I believe is at the heart of your question.
Is there is any definite reason the the general practice or is it just
a traditional practice ?
Yes. In my current application I have over 50 custom UI views and a few activities. At least 10 singleton controller and a lot of database model. So to not lost in the project, I'm using a tidy structure like this:
Activity
Adapter
Controller
Native
Model
-Database
-Rest
Ui
I suggest you to use this structure.
There are no official rules, well maybe best practices which I have not in mind.
I so we get now a opinion based answer:
I use the package names for grouping classes to a logical topic like adapters, activities, etc.
If you want another structure do it like you want, just it could confuse other devs.
Keep in mind that the package name should be unique so you should use a prefix like a domain you own or you are allowed to use (in reversed order of cause).
Check also this link where are some more ideas pointed out: http://www.javapractices.com/topic/TopicAction.do?Id=205
The first question in building an application is "How do I divide it up into packages?". For typical business applications, there seems to be two ways of answering this question.
Package By Feature
Package-by-feature uses packages to reflect the feature set. It tries to place all items related to a single feature (and only that feature) into a single directory/package. This results in packages with high cohesion and high modularity, and with minimal coupling between packages. Items that work closely together are placed next to each other. They aren't spread out all over the application. It's also interesting to note that, in some cases, deleting a feature can reduce to a single operation - deleting a directory. (Deletion operations might be thought of as a good test for maximum modularity: an item has maximum modularity only if it can be deleted in a single operation.)
Normally the activities are places in the main package and fragments, adapters, utils, models in their own packages like fragments in fragments packages and ISODateParser class could go into utils package.
You can find more about it in the Android Best Practices guide which contains best practices for android.
The guidelines about which classes should be placed under which packages are discussed under the Java packages architecture heading in the guide.
Hope it Helps!

Java good practices of which class should go where (packages) [duplicate]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 years ago.
The community reviewed whether to reopen this question last year and left it closed:
Original close reason(s) were not resolved
Improve this question
A little while ago, I saw a question answered here regarding the fine-grained organization of Java packages. For example, my.project.util, my.project.factory, my.project.service, etc.
Are there best practices with regards to the organization of packages in Java and what goes in them?
How do you organize your classes in your Java project?
For instance, a project I'm working on with a few people has a package called beans. It started out being a project containing simple beans, but it has ended up (through poor experience and lack of time) containing everything (almost). I've cleaned them up a little, by putting some factory classes in a factory package (classes with static methods that create beans), but we have other classes that do business logic and others that do simple processing (not with business logic) like retrieving a message for a code from a properties file.
I organize packages by feature, not by patterns or implementation roles. I think packages like:
beans
factories
collections
are wrong.
I prefer, for example:
orders
store
reports
so I can hide implementation details through package visibility. Factory of orders should be in the orders package so details about how to create an order are hidden.
Package organization or package structuring is usually a heated discussion. Below are some simple guidelines for package naming and structuring:
Follow Java package naming conventions
Structure your packages according to their functional role as well as their business role
Break down your packages according to their functionality or modules. e.g. com.company.product.modulea
Further break down could be based on layers in your software. But don't go overboard if you have only few classes in the package, then it makes sense to have everything in the package. e.g. com.company.product.module.web or com.company.product.module.util etc.
Avoid going overboard with structuring, IMO avoid separate packaging for exceptions, factories, etc. unless there's a pressing need.
If your project is small, keep it simple with few packages. e.g. com.company.product.model and com.company.product.util, etc.
Take a look at some of the popular open source projects out there on Apache projects. See how they use structuring, for various sized projects.
Also consider build and distribution when naming (allowing you to distribute your API or SDK in a different package, see the servlet API)
After a few experiments and trials, you should be able to come up with a structuring that you are comfortable with. Don't be fixated on one convention, be open to changes.
Short answer: One package per module/feature, possibly with sub-packages. Put closely related things together in the same package. Avoid circular dependencies between packages.
Long answer: I agree with most of this article
I prefer feature before layers, but I guess it depends on your project. Consider your forces:
Dependencies
Try minimize package dependencies, especially between features.
Extract APIs if necessary.
Team organization
In some organizations teams work on features and in others on layers.
This influence how code is organized, use it to formalize APIs or
encourage cooperation.
Deployment and versioning
Putting everything into a module make deployment and versioning
simpler, but bug fixing harder. Splitting things enable better
control, scalability and availability.
Respond to change
Well organized code is much simpler to change than a big ball of mud.
Size (people and lines of code)
The bigger the more formalized/standardized it needs to be.
Importance/quality
Some code is more important than other. APIs should be more stable then the implementation. Therefore it needs to be clearly separated.
Level of abstraction and entry point
It should be possible for an outsider to know what the code is about, and where to start reading from looking at the package tree.
Example:
com/company/module
+ feature1/
- MainClass // The entry point for exploring
+ api/ // Public interface, used by other features
+ domain/
- AggregateRoot
+ api/ // Internal API, complements the public, used by web
+ impl/
+ persistence/
+ web/ // Presentation layer
+ services/ // Rest or other remote API
+ support/
+ feature2/
+ support/ // Any support or utils used by more than on feature
+ io
+ config
+ persistence
+ web
This is just an example. It is quite formal. For example, it defines two interfaces for feature1. Normally that is not required, but it could be a good idea if used differently by different people. You may let the internal API extend the public.
I do not like the 'impl' or 'support' names, but they help separate the less important stuff from the important (domain and API). When it comes to naming, I like to be as concrete as possible. If you have a package called 'utils' with 20 classes, move StringUtils to support/string, HttpUtil to support/http and so on.
Are there best practices with regards to the organisation of packages in Java and what goes in them?
Not really, no. There are lots of ideas, and lots opinions, but real "best practice" is to use your common sense!
(Please read No best Practices for a perspective on "best practices" and the people who promote them.)
However, there is one principle that probably has broad acceptance. Your package structure should reflect your application's (informal) module structure, and you should aim to minimize (or ideally entirely avoid) any cyclic dependencies between modules.
(Cyclic dependencies between classes in a package / module are just fine, but inter-package cycles tend to make it hard understand your application's architecture, and can be a barrier to code reuse. In particular, if you use Maven you will find that cyclic inter-package / inter-module dependencies mean that the whole interconnected mess has to be one Maven artifact.)
I should also add that there is one widely accepted best practice for package names. And that is that your package names should start with your organization's domain name in reverse order. If you follow this rule, you reduce the likelihood of problems caused by your (full) class names clashing with other peoples'.
I've seen some people promote 'package by feature' over 'package by layer', but I've used quite a few approaches over many years and found 'package by layer' much better than 'package by feature'.
Further to that, I have found that a hybrid: the 'package by module, layer then feature' strategy works extremely well in practice as it has many advantages of 'package by feature':
Promotes creation of reusable frameworks (libraries with both model
and UI aspects)
Allows plug and play layer implementations - virtually impossible with 'package by feature', because it places layer implementations in the same package/directory as the model code.
Many more...
I explain in depth here: Java Package Name Structure and Organization, but my standard package structure is:
revdomain.moduleType.moduleName.layer.[layerImpl].feature.subfeatureN.subfeatureN+1...
Where:
revdomain Reverse domain, e.g., com.mycompany
moduleType [app*|framework|util]
moduleName, e.g., myAppName if module type is an app or 'finance' if it’s an accounting framework
layer [model|ui|persistence|security etc.,]
layerImpl, e.g., wicket, jsp, jpa, jdo, hibernate (Note: not used if layer is model)
feature, e.g., finance
subfeatureN, e.g., accounting
subfeatureN+1, e.g., depreciation
*Sometimes 'app' is left out if moduleType is an application, but putting it in there makes the package structure consistent across all module types.
I'm not aware of standard practices for package organization. I generally create packages that cover some reasonably broad spectrum, but I can differentiate within a project. For example, a personal project I'm currently working on has a package devoted to my customized UI controls (full of classes subclassing swing classes). I've got a package devoted to my database management stuff, I've got a package for a set of listeners/events that I've created, and so on.
On the other hand I've had a coworker create a new package for almost everything he did. Each different MVC he wanted got its own package, and it seemed a MVC set was the only grouping of classes allowed to be in the same package. I recall at one point he had 5 different packages that each had a single class in them. I think his method is a little bit on the extreme (and the team forced him to reduce his package count when we simply couldn't handle it), but for a nontrivial application, so would putting everything in the same package. It's a balance point you and your teammates have to find for yourself.
One thing you can do is try to step back and think: if you were a new member introduced to the project, or your project was released as open source or an API, how easy/difficult would it be to find what you want? Because for me, that's what I really want out of packages: organization. Similar to how I store files in folder on my computer, I expect to be able to find them again without having to search my entire drive. I expect to be able to find the class I want without having to search the list of all classes in the package.

What is a good practice to combine your classes

Not to keep all my classes in a single src -> 'package_name' folder I'm creating different sub-packages in order to separate my classes by groups like - utilities, models, activities themselves, etc. I'm not sure if it is a good practice and people do the same in real projects.
Yes, it's definitely standard practice to separate your classes into packages. It's good to establish a convention for how they are separated, to make it easier to find things later. Two common approaches:
Put things into packages based on what they are: model, service, data access (DAO), etc.
Put things into packages based on what function they support (for example, java.io, java.security, etc.
I've used both and keep coming back to the former because it's less subjective (it's always clear whether a class is a model or a service, but not always clear whether it supports one function or another function).
Doing it by class type the way you describe is one way that I've seen in real projects. I don't care for it as much as I used to because when I need to make a change or add a feature I tend to need to have several packages expanded in my IDE. I prefer (when I have the choice) to group classes by feature instead. That way I know where to look for all classes that support that feature.
The convention I prefer is to group classes first by module, then by functionality. For example, you could have the following structure:
com.example.modulea - modulea specific code that doesn't have any real need of a different package
com.example.modulea.dao - data access for module a
com.example.modulea.print - printing for module a
...
com.example.moduleb - moduleb specific code that doesn't have any real need of a different package
com.example.moduleb.dao - data access for module b
com.example.moduleb.print - printing for module b
In this fashion, code is clearer by package.
In the other style, of grouping by pure functionality, the package size tends to be quite large. If your project contains 15 modules, and each module has one or more elements per package, that's at least 15 classes per package. I much prefer clearly separated packages than packages that simply group things because "oh here are some printing utilities that are used for every module but only one module actually uses one of them from this package" - it just gets confusing.

Are there best practices for (Java) package organization? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 years ago.
The community reviewed whether to reopen this question last year and left it closed:
Original close reason(s) were not resolved
Improve this question
A little while ago, I saw a question answered here regarding the fine-grained organization of Java packages. For example, my.project.util, my.project.factory, my.project.service, etc.
Are there best practices with regards to the organization of packages in Java and what goes in them?
How do you organize your classes in your Java project?
For instance, a project I'm working on with a few people has a package called beans. It started out being a project containing simple beans, but it has ended up (through poor experience and lack of time) containing everything (almost). I've cleaned them up a little, by putting some factory classes in a factory package (classes with static methods that create beans), but we have other classes that do business logic and others that do simple processing (not with business logic) like retrieving a message for a code from a properties file.
I organize packages by feature, not by patterns or implementation roles. I think packages like:
beans
factories
collections
are wrong.
I prefer, for example:
orders
store
reports
so I can hide implementation details through package visibility. Factory of orders should be in the orders package so details about how to create an order are hidden.
Package organization or package structuring is usually a heated discussion. Below are some simple guidelines for package naming and structuring:
Follow Java package naming conventions
Structure your packages according to their functional role as well as their business role
Break down your packages according to their functionality or modules. e.g. com.company.product.modulea
Further break down could be based on layers in your software. But don't go overboard if you have only few classes in the package, then it makes sense to have everything in the package. e.g. com.company.product.module.web or com.company.product.module.util etc.
Avoid going overboard with structuring, IMO avoid separate packaging for exceptions, factories, etc. unless there's a pressing need.
If your project is small, keep it simple with few packages. e.g. com.company.product.model and com.company.product.util, etc.
Take a look at some of the popular open source projects out there on Apache projects. See how they use structuring, for various sized projects.
Also consider build and distribution when naming (allowing you to distribute your API or SDK in a different package, see the servlet API)
After a few experiments and trials, you should be able to come up with a structuring that you are comfortable with. Don't be fixated on one convention, be open to changes.
Short answer: One package per module/feature, possibly with sub-packages. Put closely related things together in the same package. Avoid circular dependencies between packages.
Long answer: I agree with most of this article
I prefer feature before layers, but I guess it depends on your project. Consider your forces:
Dependencies
Try minimize package dependencies, especially between features.
Extract APIs if necessary.
Team organization
In some organizations teams work on features and in others on layers.
This influence how code is organized, use it to formalize APIs or
encourage cooperation.
Deployment and versioning
Putting everything into a module make deployment and versioning
simpler, but bug fixing harder. Splitting things enable better
control, scalability and availability.
Respond to change
Well organized code is much simpler to change than a big ball of mud.
Size (people and lines of code)
The bigger the more formalized/standardized it needs to be.
Importance/quality
Some code is more important than other. APIs should be more stable then the implementation. Therefore it needs to be clearly separated.
Level of abstraction and entry point
It should be possible for an outsider to know what the code is about, and where to start reading from looking at the package tree.
Example:
com/company/module
+ feature1/
- MainClass // The entry point for exploring
+ api/ // Public interface, used by other features
+ domain/
- AggregateRoot
+ api/ // Internal API, complements the public, used by web
+ impl/
+ persistence/
+ web/ // Presentation layer
+ services/ // Rest or other remote API
+ support/
+ feature2/
+ support/ // Any support or utils used by more than on feature
+ io
+ config
+ persistence
+ web
This is just an example. It is quite formal. For example, it defines two interfaces for feature1. Normally that is not required, but it could be a good idea if used differently by different people. You may let the internal API extend the public.
I do not like the 'impl' or 'support' names, but they help separate the less important stuff from the important (domain and API). When it comes to naming, I like to be as concrete as possible. If you have a package called 'utils' with 20 classes, move StringUtils to support/string, HttpUtil to support/http and so on.
Are there best practices with regards to the organisation of packages in Java and what goes in them?
Not really, no. There are lots of ideas, and lots opinions, but real "best practice" is to use your common sense!
(Please read No best Practices for a perspective on "best practices" and the people who promote them.)
However, there is one principle that probably has broad acceptance. Your package structure should reflect your application's (informal) module structure, and you should aim to minimize (or ideally entirely avoid) any cyclic dependencies between modules.
(Cyclic dependencies between classes in a package / module are just fine, but inter-package cycles tend to make it hard understand your application's architecture, and can be a barrier to code reuse. In particular, if you use Maven you will find that cyclic inter-package / inter-module dependencies mean that the whole interconnected mess has to be one Maven artifact.)
I should also add that there is one widely accepted best practice for package names. And that is that your package names should start with your organization's domain name in reverse order. If you follow this rule, you reduce the likelihood of problems caused by your (full) class names clashing with other peoples'.
I've seen some people promote 'package by feature' over 'package by layer', but I've used quite a few approaches over many years and found 'package by layer' much better than 'package by feature'.
Further to that, I have found that a hybrid: the 'package by module, layer then feature' strategy works extremely well in practice as it has many advantages of 'package by feature':
Promotes creation of reusable frameworks (libraries with both model
and UI aspects)
Allows plug and play layer implementations - virtually impossible with 'package by feature', because it places layer implementations in the same package/directory as the model code.
Many more...
I explain in depth here: Java Package Name Structure and Organization, but my standard package structure is:
revdomain.moduleType.moduleName.layer.[layerImpl].feature.subfeatureN.subfeatureN+1...
Where:
revdomain Reverse domain, e.g., com.mycompany
moduleType [app*|framework|util]
moduleName, e.g., myAppName if module type is an app or 'finance' if it’s an accounting framework
layer [model|ui|persistence|security etc.,]
layerImpl, e.g., wicket, jsp, jpa, jdo, hibernate (Note: not used if layer is model)
feature, e.g., finance
subfeatureN, e.g., accounting
subfeatureN+1, e.g., depreciation
*Sometimes 'app' is left out if moduleType is an application, but putting it in there makes the package structure consistent across all module types.
I'm not aware of standard practices for package organization. I generally create packages that cover some reasonably broad spectrum, but I can differentiate within a project. For example, a personal project I'm currently working on has a package devoted to my customized UI controls (full of classes subclassing swing classes). I've got a package devoted to my database management stuff, I've got a package for a set of listeners/events that I've created, and so on.
On the other hand I've had a coworker create a new package for almost everything he did. Each different MVC he wanted got its own package, and it seemed a MVC set was the only grouping of classes allowed to be in the same package. I recall at one point he had 5 different packages that each had a single class in them. I think his method is a little bit on the extreme (and the team forced him to reduce his package count when we simply couldn't handle it), but for a nontrivial application, so would putting everything in the same package. It's a balance point you and your teammates have to find for yourself.
One thing you can do is try to step back and think: if you were a new member introduced to the project, or your project was released as open source or an API, how easy/difficult would it be to find what you want? Because for me, that's what I really want out of packages: organization. Similar to how I store files in folder on my computer, I expect to be able to find them again without having to search my entire drive. I expect to be able to find the class I want without having to search the list of all classes in the package.

Categories

Resources