Class library for design patterns in Java? [closed] - java

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 4 years ago.
Improve this question
I find my self writing again and again the same programming patterns in many new projects.
I have been thinking about creating my own reusable library of typical implementations of such patterns -not trying to cover all possible design patterns, but only them that experience has shown that it makes sense to put such typical implementations in a library (e.g., adapter, factory, etc ...)- but before I would like to know if there is not an existing library for this purpose already available for Java?.
I know that it is very difficult to completely generalize programming patterns in a way that they could be reused across different implementations with complex requirements (e.g., composition of patterns, classes participating in more than one pattern, etc ...). However, most of the time the pattern instantiations I need are quite simple and standard, and in many situations the implementation work could be sped up a bit with the use of such a library.
Thanks for your feedback.!

Design pattern are just... patterns. They aren't classes ready to use for anyone, but common concepts found across several projects. That's why you won't find a Design Pattern API.

This is precisely the reason why I created PerfectJPattern. Just make sure to check out and understand the code examples. They are available for download as well as in the site documentation pages for each of the Pattern implementations. If you read the GoF book, then you will understand the examples more easily.
For instance, if you want to use the Composite Pattern in your code, and if you use PerfectJPattern you only need to specify which interface (generic parameter and class instance) you would like to use as Composite and the rest is provided to you, see PerfectJPattern Composite. At the bottom of that page, a working example is provided that shows how to accomplish that.
Another aspect you should also take into account, is that in PerfectJPattern you do not necessarily need to reuse the generic Pattern implementations (e.g. perfectjpattern-core Maven submodule), you also do have the choice to only reuse the pure abstract level (perfectjpattern-api Maven submodule) and provide the implementation yourself. In PerfectJPattern you have the flexibility of reuse at different levels of abstraction since there is a fine-grained layered design reflected also in the Maven project structure. Reusing the perfectjpattern-api gives you an abstract template guideline if you wish, that will help you speed up your own Design Pattern implementations. However, ideally you should reuse as much as possible.
Update: following up on a comment below, it is worth noting that not all Patterns can be fully compotentized see From Patterns to Components. Some Patterns can be only partially componentized and some others not at all like the case of the Singleton. The Singleton depends too much on the context and that's why you can only find an interface in PerfectJPattern. However in PerfectJPattern the following Patterns are fully componentized e.g. Observer, Command, Adapter, Decorator, Composite, Proxy, Visitor, DAO, etc.

I disagree with the other answers that no reuseable implementations can be created for design patterns. However, it might not always be straightforward, and involves a lot of abstract programming.
Coming from C# I was missing the simplicity of the observer pattern in Java. (events in C#) After finishing a reusable generic observer for Java I came across the PerfectJPattern library.
It might be worthwhile to check it out.
A componentized pattern is in essence a context-independent, reusable
and type-safe variation of the original pattern that covers at least
as many use-cases as the original pattern and that does not require
developers to re-implement the same boilerplate code in every
different context. Design Patterns are reusable in terms of design,
componentized patterns are reusable in terms of design and code.
Kudos for wanting to reduce any form of duplication possible. "Don't repeat yourself" is one of the most important principles in programming.
As some extra arguments design patterns can be centralized in a library I give you some further examples:
Lazy initialization in C#.
Entire LINQ is based on IEnumerable.
Java's attempt at a reusable Observer pattern. (I didn't say all are good.)
Several patterns integrated in the Spring framework.
As in Pangea's answer: Java JT framework.

What you are looking for is PerfectJPattern.
Checkout dp4j. It allows you to implement the Singleton pattern with #Singleton and lazy initialize it with #Singleton(lazy=true). It is a "collection of reusable componentized Design Patterns implemented in Java".
For the Singleton recommend dp4j. To implement a Singleton you annotate your class with #Singleton and to lazy initialize it you annotate with #Singleton(lazy=true).

If you find yourself repeating similar code in multiple projects, it might be a good idea to extract the portions that are repeated into a library of reusable code in hopes of avoiding repeating yourself in the future.
This is unlikely to lead to fully general reusable implementations of design patterns.

JT Design Pattern Framework for Java/j2EE

A lot of the patterns are built into the Java SE - you may not notice.
Decorator is all over the java.io package.
The java.sql package is AbstractFactory.
All the wrapper classes are Flyweights.
I stand with those who say don't look for a pattern library. They should be discovered as you write your code.

It is possible in a languange which offers higher order functions and some other stuff. Here are some slides which references a paper which discusses 'the origami pattern' library. It shows 'library code' for the following patterns: Composite, Iterator, Visitor, Builder. So if you want to try that out on the jvm you can today, just use scala. http://www.slideshare.net/remeniuk/algebraic-data-types-and-origami-patterns

Do you see a forest or trees?
Design patterns should become apparent rather than be selected up front. By the time they become apparent, you don't need the pattern because the code exists. Then you marvel at how the solution solved itself and your brain subconciously selected the right approach. It gives you that warm fuzzy "i trust that code" feeling.
If you build a design pattern library, you have built yourself a big hammer (or hammer factory, or hammer factory factory [1]) and everything becomes a convenient nail (including screws) resulting in lots of sore thumbs and bowls of spaghetti in your development team.
[1] http://discuss.joelonsoftware.com/default.asp?joel.3.219431.12

Related

Classes and packages encapsulation in an hexagonal architecture

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.

What is the pros and cons of centralizing applications logs? [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 2 years ago.
Improve this question
I am looking to understand the pros and cons of centralizing all applications logs into separate files with AOP (e.g. with AspectJ).
Logging is know for being a cross-cutting concern. However, I have never met anyone that centralized all logs into a single or bunch of files. Therefore, I'm left wondering why.
What would be some of the pros and cons of doing it?
I am looking to understand the pros and cons of centralizing all
applications logs into separate files with AOP (e.g. with AspectJ).
I will be using the terms AOP and AspectJ interchangeably. Notwithstanding, AOP is the paradigm and AspectJ implements it, just like OOP and Java.
The benefits of centralizing cross-cutting concerns (CCC) into their own modules (e.g., aspect) using AOP are similar to those of modularization concerns with OOP. Those benefits are described in the literature in papers and books such as:
Aspect-Oriented Programming
Towards a Common Reference Architecture for Aspect-Oriented Modeling
Impact of aspect-oriented programming on software development efficiency and design quality: an empirical study.
AspectJ in Action: Enterprise AOP with Spring
and many others. One can summarize some of those benefits as follows:
reduces code duplication; Instead of having a functionality (e.g., logging) duplicated in several different places, one has it in a single aspect. That functionality can then be applied to those several places using the concept of pointcut;
reduces the coupling between domain-related and crosscutting-related concerns (i.e., separation of concerns); For instance, removing the logging from the domain code follows the single-responsibility principle;
the enhancing of code reusability; Because of the aforementioned separation of concerns, one (for instance) increases the reusability of the modules encapsulating the based code and the modules encapsulating the logging;
dealing with code tangling and scattering issues; as illustrated in the image below
Instead of having logging 1 and 2 tangled directly with the domain-code, duplicated and scattered across separate modules (i.e., Class A and Class B), we have those logging-related functionality encapsulated into one aspect.
There are in the literature some papers about the benefit of AOP regarding the modularization of cross-cutting concerns such as logging namely:
S. Canditt and M. Gunter. Aspect oriented logging in a real-world
system. In First AOSD Workshop on Aspects, Components, and Patterns
for Infrastructure Software (AOSD-2002), March 2002.
The downsides of AOP that one can read in the literature are those typical of a learning/integrating a new technology, namely:
Hiring skilled programmers
Following an adoption path to ensure that you don’t risk the project by overextending yourself
Modifying the build and other development processes
Dealing with the availability of tools
Other downsides reported by papers such as:
An exploratory study of the effect of aspect-oriented programming on maintainability
Using aspect-orientation in industrial projects: appreciated or damned?
Using and reusing aspects in aspectj.
A Case Study Implementing Features Using AspectJ (this one is particularly good a show-casing some of issues with using AOP
can be summarize to:
having to learn a new paradigm;
lack of tool support;
the performance of the weaving;
making it harder to reason about the code, since the CCC related code was moved elsewhere. The same argument can be applied to subclassing or the use of the decorated pattern for instance. However, IDEs mitigates those problems, in the case of AspectJ by showing the joinpoints that are being intercepted. Another solution is for instance to use annotations and intercept those annotations:
#Logging
public void some_method(){...}
When the programmer looks at the annotation immediately knows that that method is being intercepted by a pointcut. The downside of this approach is that you kind mixing again the CCCs with the domain code, albeit just in a form of an annotation.
On the other hand one can argue that since the domain-related concerns and CCCs are now encapsulated in different modules it is easier to reason about them in isolation.
Pointcut fragility; This problem is similar to the fragile base class problem. From source one can read:
changes to the base-code can lead to join points incorrectly falling
in or out of the scope of pointcuts.
For instance, adding new methods, or changing their signature might cause pointcuts to intercept them or stop intercepting them. There are techniques to mitigate such problems. However, in my option the solution is tooling. When one renames a method in Java one expects the IDE to safely apply those changes.
the granularity of the joinpoint module. With AspectJ (even worse with Spring AOP) it might be difficult to get local context necessary for the logging, for instance local variables, which might force you to refactor your code so that you can expose the desired joinpoints -- known in requirements engineering as scaffolding. On the other side, refactoring your code might actually improve it. From: "21. Why can't AspectJ pick out local variables (or array elements or ...)?" one can read:
Users have sometimes wanted AspectJ to pick out many more join points,
including method-local field access, array-element access, loop iteration, method parameter evaluation
Most of these have turned out not to make sense, for a variety of
reasons: it is not a commonly-understood unit for Java programmers
there are very few use-cases for advice on the join point
a seemingly-insignificant change to the underlying program causes a
change in the join point
pointcuts can't really distinguish the join point in question
the join point would differ too much for different implementations of
AspectJ, or would only be implementable in one way
We prefer to be very conservative in the join point model for the
language, so a new join point would have to be useful, sensible, and
implementable. The most promising of the new join points proposed are
for exception throws clauses and for synchronized blocks.
You need to evaluate if in your context it pay-off adding an extra layer (i.e., transversal modularization) into your code base; and also evaluate against alternative approaches such as code-generators, frameworks or design patterns.
In the case of the logging some of the aforementioned issues are not as problematic because if things go wrong... well you just lose or add some logging.
Opinion base part
Logging is know for being a cross-cutting concern. However, I have never met anyone that centralized all logs into a single or bunch of files. Therefore, I'm left wondering why.
Is separation of concerns a bad practice?! (unless you take it to the extreme no). I would definitely say that is not a bad practice, is it worth?! well that is more complex and context depended.
I personally hate to see a beautiful snippet of code mixed with logging functionality. IMO given that software has to deal with so many other variables than just the code per si, such as tight deadlines, not having logging mixed with base code seems to not have a higher priority.

when and why do we need to divide a class into many classes?

I am an android beginner developer. Currently, I am developing an application. However, my class is quite large because there are many UI components (to handle onClick, onProgressBarChanged, etc.).
Most of my components are dynamic. So, I have method to create those components.
Now I split some methods for initializing UI components into another class.
At this point, I am trying to think/search for a good reason to split my class into several classes.
Advantage: maintainability, testability, reusability
Disadvantage: reduce runtime performance
I am not sure that there is any advantage or disadvantage that I have missed?
Furthermore, I will divide a class when I find an overlap method
I am not sure that there is another situation when a class must be divided.
First, if you've never looked into refactoring, then I would strongly encourage you to do so. Martin Fowler has some excellent resources to get you started. But, I'm getting slightly ahead of myself.
To begin with, you split out classes to maintain a clear delineation of responsibilities. You can think of the SOLID principle here - each class does one thing, and one thing very clearly.
If you notice that a method, let alone a class, is doing more than one thing, then that is a good time to stop and refactor - that is, take the code you have, and apply a particular, focused refactoring to it to improve readability and flow, while maintaining the same functionality. You're essentially looking for code smells - parts of the code that are suspect, not following a specific contract or methodology, or are legitimate anti-patterns - which are, themselves, practices that developers strive to avoid.
Programs that deal with UI (especially in Java) tend to be pretty verbose. What you should avoid doing is placing any conditional business logic in the UI layer, for ease of separability, testing and clarity. Make use of the Model-View-Controller pattern to understand and abstract away the necessary separations between the UI (Views), and the actual work that's needed to be done (Controllers), while maintaining some semblance of state (Models).
We use OOPs Concept in Android(core java) Application Development. If we split our one class in many class it gives a good sense of maintainability, re-usability, Security and Easy change in Coding during Development.
As for example:- Util class for Database handling, Network Class for Internet connection , Dialog class for different type dialog and so...
This way we can categories our coding and change or re use it any time. So it is good practice to follow the OOPS concept during Development.
Thanks

Are Java2D and Swing examples of Good Use of OOP?

Overusing Inheritance ?
Java Swing and Java2D rely a lot on inheritance. Most people have told me I should avoid inheritance as much as possible and only use it when necessary. So is the extensive use of Inheritance in Java2D and Java Swing justified?
Adapter Pattern
I have heard a lot of praise for the adapter pattern, and I've heard a lot of criticism. What I gathered from all that, though, is that the adapter pattern is only considered good design if used at the right place. Irrelevant use of the adapter pattern causes people reading your code to scowl. Is the adapter pattern correctly and relevantly used in the two Java APIs?
Singletons
Both APIs also tend to use a considerable number of Singletons. Is this good?
The Question
So, Is The Java2D Api and Java Swing a good example of an Object Oriented Programming Interface? Should I use their techniques in my code?
I have no certainty on this, but I can offer some thought:
inheritance: suppose you preffered to use interfaces and composition instead of reuse-by-inheritance in Swing, then you would need to do an awful lot of forwarding (Component and JComponent have dozens of methods)
adapter pattern: see above
singletons: they are appropriate to model parts of a system which are genuinely unique (I would agree that java.awt.Desktop could be implemented as a singleton -- even though it uses a factory method)
overall design: you might opt to judge things by results -- Swing is robust, extensible, and widely used.
A friend of mine who works with Swing complains constantly that it is an abstract morass. Determining the behavior of an object at run-time involves piecing together a bizarre collage of inherited functionality. From what I've seen of it I'm inclined to agree.
Inheritance is a useful programming concept, but it is easy to use
inappropriately.
Inheritance is a good choice when:
Your inheritance hierarchy represents an "is-a" relationship and not a "has-a" relationship.
You can reuse code from the base classes.
You need to apply the same class and methods to different data
types.
The class hierarchy is reasonably shallow, and other developers are
not likely to add many more levels.
You want to make global changes to derived classes by changing a
base class.
A microsoft article here and another good one here

Design patterns that every developer must know?

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

Categories