I know this question has been asked and answered many times, but I am still asking the same question again...
I have started working on a travelling application and for which currently I am working on creating on the creation of the underlying DAO so I am planning to create a generic DAO, its implementation and again an interface for each entity class.
My query is what is the best way to organise all these interfaces as well as their Implementation.
Thanks in advance
If I understand the question correctly your looking for suggestions on organising your packages?
I'd split then between. com.yyy.zzzz.dao.interfaces and com.yyy.zzzz.dao.impl
You're the only one who can take decisions on how your application should be organized. You can, of course, follow some recommandations such as the Java Naming Convention for packages, or even try to split your packages for each tier implied in your application; but in the end, you have to choose for yourself.
#Kevin D's solution is correct, you could use the com.company.project.dao.interfaces (I wouldn't use interfaces as it's a plural and I avoid plural in package names, but again it depends on you) and com.company.project.dao.impl or you could use packages to split different implementations. It's as you want. And no one should tell you how to split your own application (except your team).
The only (but still facultative) rule I would tell you to follow is "Have coherent names".
That means choose your project convention, but stick to it, and of course the names you choose for your packages (but it also applies on classes, variables) must represent their content (but I suppose this is common sense).
On another note, I don't know the context of your work, but you should really read Adam bien's Weblog, you'll see some articles on best practices regarding DAO and "default implementation", maybe it will concern your project.
Resources :
DAO's aren't dead - but they either collapsed or disappeared
Service s = new ServiceImpl() - Why are you doing that ? (not really related to DAO but still your "default implementation" made me think of this)
JPA/EJB3 killed the DAO
Related
I would like to know if in Java (JDK 17) there is a way to easily handle classes and packages encapsulation in an hexagonal architure. I would like to make unavailable classes present in an adapter to the domain.
To illustrate my goal, say we have this package organisation:
com.company
|-domain
|-model
|-Customer.java
|-Product.java
|-ports
|-DbPort.java
|-ServiceBusPort.java
|-services
|-CustomerService.java
|-ProductService.java
|-adapters
|-inbound
|-rest
|-CustomerRestAdapter.java
|-ProductRestAdapter.java
|-bus
|-ServiceBusAdapter.java
|-RabbitAdapter.java
|-outbound
|-db
|-entities
|-Customer.java
|-Product.java
|-repositories
|-CustomerRepository.java
|-ProductRepository.java
|-mappers
|-bus
|-dtos
|-CutomerDto.java
|-ProductDto.java
|-mappers
What I want to achieve is: all classes and packages under com.company.adapters should not be visible from the com.company.domain package. The goal is to prevent developers to use for example the class com.company.adapters.outbound.db.entities.Customer in com.company.domain.services.CustomerService. But classes inside com.company.domain should be accessible from everywhere.
To achieve strong encapsulation with Java, you could make use of maven modules per layer, left, right and domain.
I have not tried but I guess Java 9 modules would also help here. Check this link.
Another approach I use for the sake of simplicity and code readability, is to use a single module, without strong encapsulation, but different packages per layers, one for domain, another for infra..
And, to enforce architecture rules within this module, like hexagonal ones, I usually define a unit test which fails in case of any violation, for example when some domain package code directly depends on a technical API client implem defined outside the domain.
So far I have used Archunit framework for that.
Also I prefer this approach because, as a developer or new joiner for example, IMO it is much easier to break some architecture rules / encapsulation patterns, not being aware till the code review, rather than breaking / ignoring a test which would fail the build, and which would also act as a spec for these rules.
What you want to achieve is definitey doable in Java.
There are numerous examples - for example check out the JAXP library:
While you use the DocumentBuilderFactory to instantiate a DocumentBuilder and ultimately parse a Document, everything but the factory are interfaces abstracting away a concise implementation, which is the pattern you are aiming at.
To get more concise: All that you need to do is come up with the right combination of classes, interfaces and packages. Have a look at Design Patterns which describe what you need to do. The book "Design Patterns" by the Gang of Four is very helpful in that respect.
We are creating an android library for use with Android. That means an Eclipse-like IDE and an Ant-like build process.
The nature of the library is that it has two distinct parts, representing different levels of abstraction - let's say 'upper' and 'lower'.
Assume, for the purposes of this question, that we need to call methods in one part from the other, but would like to keep those methods hidden from the library user. I've scoured the usual references but they all stop at the point of explaining package name conventions and scope rules. I've failed to find anything that answers this on SO, though this was useful.
The immediate solution is to simply have everything in one package and for those methods to be package-private. However, for reasons of maintainability, clarity, and not-having-100-files-in-one-folder we'd prefer to split the parts into different folders.
The obvious splitting point is to split the (let's say 'wibble') package into com.me.wibble.upper and com.me.wibble.lower packages/folders, but that makes any interconnecting methods undesirably public. In mitigation they could be hidden from the javadoc with #hide.
Another thought is whether could we split the parts at the top level and instead of the classic /main and /test folders have /upper, /lower and /test and all parts share the same com.me.wibble namespace. I'm unsure if/how Eclipse would cope with that.
Is there a conventional way of doing this, or is it just not done? If there are ways, what are the pro's and con's?
hmmm......Instead of asking for the solution, sometimes it is better to give the question. WHY you want library users to have a restricted view may generate a better answer than the HOWTO. There are a few answers I thought of but didn't give because I don't know the motivation behind the question (I don't want to waste your time with an answer that is not applicable).
/upper,/lower/,/test doesn't make your situation any nicer. It just makes the project more organized. Whether they are all in the same folder or separate it doesn't affect much.
It sounds like you need public 'interfaces' for library users while having private 'interfaces' for your own use. This is possible with hacking but can be painful if this is large pre-existing collection of code.
Not sure if the title captures what I'm trying to say here.
When designing in OO should I be splitting my objects up into their most specific areas - so if I have a factory object that deals with creating objects but later on i come across a way of creating objects for another purpose even though they may be the same objects is it worth creating a seperate fcatory or just add to the exsiting.
My biggest worry is bulking up classes with tons of stuff, or splitting objects and diluting my projects into a sea of classes.
Any help?
EDIT:
I guess on a side note/sub topic part of me wants to find out the level of granularity you should use in a program. Kind of, how low should you go?
My biggest worry is bulking up classes with tons of stuff, or
splitting objects and diluting my
projects into a sea of classes
This is a very valid point and in any even reasonably sized project, extremely difficult to get right up front especially because realistically, requirements themselves evolve over time in most cases.
This is where "Refactoring" come in. You design based on what you know at any given point and try not too make too many leaps of faith as to what you think the system MAY evolve to.
Given that you know what you are building right now, you design your classes trying to make the best possible use of OO concepts - eg encapsulation / polymorphism. This is itself, like others have noted as well, can be notoriously difficult to achieve and thats where experience, both in designing OO systems as well as knowledge of the domain can really come in handy.
Design based on what you know --> Build It --> Review it --> Refactor it --> Re-design --> and it goes on and on..
Finding the correct level of detail and responsibility is what makes OOP design so difficult. We can help you with a specific case but not with anything this general. If there were algorithms or strict methodologies of how to solve this, everyone could be an OOP designer.
A rule of thumb I like for deciding "is this getting too big now?" is "can I explain the purpose of it concisely?" If you start having to introduce caveats and lots of weasel words to explain the functions of a component of your design (be it class, member variable, method or whatever) it might be a good indicator that it's getting too complex and should be split up.
In your specific case, if you already have a factory object then the DRY Principle (Don't Repeat Yourself) would say that it's a bad idea to create another factory that does the same thing.
Is this an actual problem that you face? Or merely a fear about how your code might grow in the future?
If you are using the same type of object to solve drastically different problems then you may need to redesign the class to focus on seperation of concerns. If you need a more specific answer, you will need to provide an example of a type of class that would need this functionality.
I might have worded things badly in
the Q. I guess I wouldnt be repeating
myself its just more of a case of
where to put the code, it could be
added to an exsiting factory that
creates design objects for exporing
data to excel spreadsheets. On the
other hand I could see it could also
have its own factory for importing
excel data. Both factories would
produce the same objects but the inner
workings are completely different. –
If you aren't doing or plan on doing any class abstraction (subclassing or using interfaces) you may not need to use the factory pattern at all. The factory pattern is generally best suited for supplying objects of a base class type or that implement a specific interface.
Both
factories would produce the same
objects but the inner workings are
completely different.
Not sure if I've understood you correctly, but this sounds like a candidate for the AbstractFactory pattern.
Would it be OK to put my public interfaces into their own package (for my organisation only).
for example
com.example.myprogram - contains all normal code
com.example.myprogram.public - contains public accessible interfaces
com.example.myprogram.abstract - contains abstract classes
Is this a good or a bad thing to do, are there any disadvantages?
I wouldn't like this practice at all. You should group classes, both abstract and concrete, and interfaces according to functionality.
Look at the Java API as an example. Did Sun separate the Collections interfaces from implementations? No. Sun's practices aren't always the best guide, but in this case I agree.
Don't do it.
I can suggest you 2 common ways:
If you really think that your interfaces can have more implementations in future (i.e. you're working on API) then move them to a separate module and create there special package with name 'core', for example. (com.example.myprogram.core). Implementations should be in correspondent packages (like com.example.myprogram.firstimpl).
If you have only 1 implementation then let all your interfaces be in com.example.myprogram package and all concrete classes in com.example.myprogram.impl package.
I can't see that as being bad practice, however you might wanna consider as an alternative organizing your stuff per logical functionality rather than syntactic definition, so that all code for a given unit of functionality interfaces/abstract classes/normal code goes in the same package. This is one of the principles of modular programming.
Said so, putting all the interfaces (but only those) in a separated package might be necessary depending on the size of the project, and might eve become almost necessary if you have a pure component based plugin architecture (so that other module know only about interfaces and the actual implementation is somehow dynamically injected).
Public interfaces are a formal contract between system modules or systems. Because of that, it makes sense to isolate them from the remainder of the code, to make them stand out.
For example, in a system I've worked on, all public interfaces between the server and client components of the system have been placed in a special system module (called, no surprise, "api"). This has a number of desirable effects, among which these:
- semantically, you know where to look if you need any kind of information on how communication should take place
- you can version the api module separately, which is especially useful when you don't want a moving target, i.e. you sign a contract to deliver an application which will support "the api v.1.1" rather than constantly playing catch while someone else changes the interface and requires you to adapt your side
That doesn't mean you shouldn't organize them further in sub-packages to distinguish what they are for. :)
In summary, you are doing the right thing by separating the interfaces from the rest of the code base, although depending on your specific needs, you might do well to take it a step further and isolate the interfaces in a separate system module.
What are the design patterns that every developer must know?
I'm interested in the context of Java web developers working with Spring & Hibernate. I have often heard that good knowledge in design patterns is essential for working with those frameworks. Can anyone list the specifics?
For example, I know that understanding abstract factory & factory pattern, singleton pattern etc is absolutely essential. I'm looking for a comprehensive list.
Inversion of Control
If you are ever going to design decoupled systems, you will need to know how to properly link dependencies between classes.
Command Pattern and Variants
In Java in particular, it is essential to learn how to pass a piece of functionality to another method as an object because of the lack of closures and function pointers in the language.
Factory Pattern
Factories are ubiquitous in Java frameworks and it is essential to learn why and when to use the factory pattern.
Singleton (pattern and anti-pattern)
Learning how to use the singleton pattern responsibly is very helpful for understanding the pitfalls in other people's code you may be reading.
Overall, learning the why with regards to patterns is much more important the the how. Knowing when not to apply a pattern is just as important as knowing when to.
Everybody should know about Singleton, but also when not to use it! It's currently the source of much pain for me on a project at work.
Singletons make the code hard to understand and follow, and make writing unit tests much more difficult. I like the blog post Singletons are Pathological Liars.
Most design patterns are pretty obvious--you already know and use them if you've been programming a few years.
The biggest advantage I've found to design patterns is sharing a common set of names. If someone says "Callback" that can mean quite a few things, but if someone says "Listener Pattern" that means a more specific set of calls and implies a higher level relationship between objects.
So in essence, read through a good design patterns book, get an idea of the name of each pattern, spend some time understanding any you don't know, and you're good to go.
I wouldn't completely ignore any of them--they are all good to have seen. You should be able to recognize a situation that might benefit from a specific pattern and know where to look to find out more about it.
Model–view–controller just has to be on the list, Spring has an MVC framework:
http://en.wikipedia.org/wiki/Model–view–controller
I recommend you to read Head First Design Patterns book. This is a well written book about all commons and useful patterns.
I would recommend you get and read the Design Patterns book, since it gives you the vocabulary.
But don't forget the fundamentals :)
Interviewing Java Developers With Tears in My Eyes
http://java.sys-con.com/node/1040135
Hibernate? Then the Unit Of Work is a must http://martinfowler.com/eaaCatalog/unitOfWork.html
Composite, it's present in the JUnit framework. (Test-TestCase-TestSuite)
The Adapter, Builder, Command, Template Method and Strategy patterns are easy and often usable in practice.
The State pattern also helped me to clean up mess in inherited source codes.
This would be a comment to Greg Hewgill's reference to "Singletons Are Pathological Liars", but I can't make comments yet.
That article makes a convincing case, but his ire is misdirected. As several commenters on his blog noted, his problem is really global state. His code fix could still be making use of singletons, and still gain the exact increase in clarity and testability.
Re-read the article. He's not bothered that OfflineQueue needs an initialized Database instance, nor that CreditCardProcessor needs an initialized OfflineQueue. He's bothered that those dependencies aren't visible, which causes issues with maintainability and testability.
His problem is with secret global state (does this make me sound like a conspiracy theorist?).
However, he's (imo) misinterpreting that secret global state as being the fault of singletons.
That doesn't mean I'm in favor of singletons where they're not necessary - certainly, they have drawbacks (including the obvious thread contention bottleneck possibility). But I prefer to be clear about what practices I'm eschewing.
Incidentally, I'd go further in my refactoring - based on the class names, I'd assert in a code review that CreditCardProcessor should, well, process the charges, so instead of his:
card.charge(cardProcessor, 100);
I'd have this, instead:
cardProcessor.chargeCard (card, 100);
(and yes, I replaced his variable names c and ccp with names I considered more readable)
Apart from Abstract factory , Factory Method and Singleton patterns, which you have quoted already, I think below patterns are useful.
Bridge Pattern : Abstraction and implementation can change independently
Decorator Pattern : Change the behaviour of object at run time
Mediator Pattern : Enable central communication medium between different objects
Chain of Responsibility : If you are adding filters to web service request, this is very useful.
Strategy Pattern : If you want to change the algorithm from a family of algorithms at run time by checking a parameter
Facade Pattern : If you have many services in your system and don't want to expose all the services to client, have one Facade class, which will interact with other services.
sourcemaking provides excellent details on each design-pattern : Intent, Strucutre, Checklist and Rules of thumb.
One more SE question would be definitely help you :
Design Patterns web based applications
Singleton - Singletons apparently can and should be used for everything