Applying the Boundary-Control-Entity (BCE) pattern in Java EE:
#Stateless //1st boundary
public class A {}
#Stateless //2nd boundary
public class B {}
Until now, all it's ok, now, let's supose that for some reason I need use some services exposed by B on A. So, A now looks like:
#Stateless
public class A {
#Inject
B b;
//... call some B's methods
}
But, according to the BCE pattern stands for
Control elements can communicate with each of the other two kinds, but
entities and boundary elements should not communicate directly.
Obviously for JPA Entities they need to communicate each other (otherwise, "JOINs" won't be possible). Then, I end with some questions related:
1) Why communication between boundaries is forbidden?
2) Under Java EE, we can use #Remote interfaces, Will this still violates the statement?:
#Stateless
public class A {
#Inject
RemoteB b; //now uses a remote dependency
}
#Stateless
#Remote(RemoteB.class)//implements a remote interface
public class B {}
3) How Java EE solves the pattern.
First of all, my advice is to use architecture as a guideline on how to structure your application, but never as a law - so always adapt it to your needs and do what is sensible, easy and fits to your situation.
The idea behind the boundary is, that it serves as the only externally visible contract to your business logic behind it, which may change and whose details are hidden. And it's reasonable to keep the dependence on other boundaries as low as possible - yet controls can make use of and can be called by many boundaries as it is needed.
Adam Bien, one of the Java EE gurus, emphasizes in his workshops and talks one this pattern, as he explains in this example. Another good article is this one.
If some boundaries needs intercommunication is a bad smell that maybe your design needs a refactor, for example, extract common behavior in a control and use it in both. In the case of using #Remote the boundaries are highly coupled not just with the Interface but also by the DTOs used (and DTOs always duplicate state). In a SOA/microservices oriented architecture if you need this intercommunication you should prefer low coupling, that means, using json/xml messages.
Java EE lets you use jax-rs to achieve low coupling
5th AirHacks session
Related
I want to start incorporating the practice of writing invariants for my classes. For my POJOs, is it a good practice to validate its state by validating it against business rules. Say I have
this class for instance:
#Data
public class Pick {
List<Substitution> substitutions = new ArrayList<>();
}
Now, my invariant says that every substitution object in the list needs to have a substitution reason. Is it a good practice to do such business checks inside POJOs that are meant to be simple data carriers?
Note that I already use #NonNull which is also an invariant, although a very basic one. Is it a good practice to write invariants that test for complex business relationships b/w your fields?
JSR 380 is a specification of the Java API for bean validation, part of Jakarta EE and JavaSE, which ensures that the properties of a bean meet specific criteria, using annotations such as #NotNull, #Min, and #Max.
We can see this approach used in Java ecosystem heavily, as far as it doesn't touch your business logic and also data object and keeps them clean it is goof
more here
I have two service beans called PowerUserManager and SimpleUserManager. Both #Service annotated classes have about 20% of the code in common.
I've built an inheritance tree with a common abstract class (BaseUserManager) to reduce redundancy between the two classes.
BaseUserManager
|
---------------
| |
PowerUserManager SimpleUserManager
Then in my #Controller or whatever client class, I use the #Autowired annotation to inject both PowerUserManager and SimpleUserManager and I use one of them depending on the instance of the User I'm dealing with.
I'm not comfortable using inheritance to factorize code especially in the service layer. Do you Spring fellows see a better way to do this ?
You should ask yourself some fundamental questions before considering inheritance over composition in this case, and in general:
Are all user managers a BaseUserManager? Is this a IS-A relationship in any possible case?
Does it make sense to expose BaseUserManager public API everywhere where a user manager is invloved?
Does BaseUserManager have a single responsibility?
If the answer is yes, then inheritance is the right way to go. Otherwise, you should probably redesign into several smaller components and treat PowerUserManager and SimpleUserManager as service facades.
It seems to be the standard so I have been going along with it so far, but now I am building a new class from scratch instead of modifying the old ones and feel I should understand why I should follow the projects convention.
Almost every class has an interface to it which is called classnameable. In the code database.class would never appear even once but in place where I would want to use that class I see databaseable.class.
To my understanding an interface was a class that was never implemented but was inhereted from to keep standards. So why are the interfaces being used as if they were real classes?
To my understanding an interface was a class that was never
implemented but was inhereted from to keep standards. So why are the
interfaces being used as if they were real classes.
This is a bit confused. An interface defines an API, so that pieces of code from different authors, modules or projects can interact. For example, java.util.Collections.sort() can sort anything that implements the List interface and contains objects that implement the Comparable interface - even though the implementation classes may not have existed yet when the sorting code was written!
Now the situation in your project seems to reflect an unfortunately rather common antipattern: having an interface for everything, mostly with a single implementation class, even for internal classes.
This used to be strongly promoted by proponents of Test-Driven-Development (TDD) who see it as vital to be able to test every class in isolation with all its dependencies replaced by mock objects. Older mocking frameworks could only mock interfaces, so to be able to test every class in isolation, all inter-class dependencies had to be through interfaces.
Fortunately, newer mocking frameworks can mock concrete classes and don't require you to pollute your project with unnecessary interfaces. Some people will probably still argue that it should be done anyway to "reduce coupling", but IMO they're just rationalizing their desire not to change their practices.
And of course, if you don't do fundamentalist TDD, there never was a good reason to have an interface for everything - but very good reasons to have interfaces for some things.
If you've got an interface for pretty much every single class in your project even though there's no reason for it, that's not a good thing and in this day and age there's no great reason for it. It may be a legacy from days gone by when it was required by some external testing toolkit for instance - but these days that's not a requirement.
It may be of course that someone's heard that loose coupling is a good thing, that you should always couple to interfaces and not concrete classes, and taken this idea to an extreme.
On the other hand, it is good practice to define interfaces for some classes even if there's only one of them (at the moment.) When I'm writing a class I try to think along the lines of whether another (potentially useful) implementation could exist, and if so I'll put an interface in. If it's not used it's no problem, but if it is it saves time and hassle and refactoring later.
If you want a class for your interfaces then a common way is to create an AbstractFoo class to go with the Foo interface. You can provide simple implementation of the required methods, allowing derived classes to overwrite them as needed. See AbstractCollection for an example of such a class.
The advantage is that you don't have to implement all the small stuff, it is already done for you. The disadvantage is that you can't inherit from any other class. You pays your money and you takes your choice.
A good indication for bad design is when you have a ISomething or a SomethingImpl. The interface name should state how to use it (i.e. List), the class name should state how it works (i.e. ArrayList).
If you need pre- or suffixes because the names would be the same, this means there is only one way to implement it, and then there is probably no need for a separation. (If you think there will be more sophisticated implementations in the future, name your class DefaultSomething or SimpleSomething)
What does the term Plain Old Java Object (POJO) mean? I couldn't find anything explanatory enough.
POJO's Wikipedia page says that POJO is an ordinary Java Object and not a special object. Now, what makes or what doesn't make and object special in Java?
The above page also says that a POJO should not have to extend prespecified classes, implement prespecified Interfaces or contain prespecified Annotations. Does that also mean that POJOs are not allowed to implement interfaces like Serializable, Comparable or classes like Applets or any other user-written Class/Interfaces?
Also, does the above policy (no extending, no implementing) means that we are not allowed to use any external libraries?
Where exactly are POJOs used?
EDIT: To be more specific, am I allowed to extend/implement classes/interfaces that are part of the Java or any external libraries?
Plain Old Java Object The name is used to emphasize that a given object is an ordinary Java Object, not a special object such as those defined by the EJB 2 framework.
class A {}
class B extends/implements C {}
Note: B is non POJO when C is kind of distributed framework class or ifc.
e.g. javax.servlet.http.HttpServlet, javax.ejb.EntityBean or J2EE extn
and not serializable/comparable. Since serializable/comparable are valid for POJO.
Here A is simple object which is independent.
B is a Special obj since B is extending/implementing C. So B object gets some more meaning from C and B is restrictive to follow the rules from C. and B is tightly coupled with distributed framework. Hence B object is not POJO from its definition.
Code using class A object reference does not have to know anything about the type of it, and It can be used with many frameworks.
So a POJO should not have to 1) extend prespecified classes and 2) Implement prespecified interfaces.
JavaBean is a example of POJO that is serializable, has a no-argument constructor, and allows access to properties using getter and setter methods that follow a simple naming convention.
POJO purely focuses on business logic and has no dependencies on (enterprise) frameworks.
It means it has the code for business logic but how this instance is created, Which service(EJB..) this object belongs to and what are its special characteristics( Stateful/Stateless) it has will be decided by the frameworks by using external xml file.
Example 1: JAXB is the service to represent java object as XML; These java objects are simple and come up with default constructor getters and setters.
Example 2: Hibernate where simple java class will be used to represent a Table. columns will be its instances.
Example 3: REST services. In REST services we will have Service Layer and Dao Layer to perform some operations over DB. So Dao will have vendor specific queries and operations. Service Layer will be responsible to call Which DAO layer to perform DB operations. Create or Update API(methods) of DAO will be take POJOs as arguments, and update that POJOs and insert/update in to DB. These POJOs (Java class) will have only states(instance variables) of each column and its getters and setters.
In practice, some people find annotations elegant, while they see XML as verbose, ugly and hard to maintain, yet others find annotations pollute the POJO model.
Thus, as an alternative to XML, many frameworks (e.g. Spring, EJB and JPA) allow annotations to be used instead or in addition to XML:
Advantages:
Decoupling the application code from the infrastructure frameworks is one of the many benefits of using POJOs. Using POJOs future proofs your application's business logic by decoupling it from volatile, constantly evolving infrastructure frameworks. Upgrading to a new version or switching to a different framework becomes easier and less risky. POJOs also make testing easier, which simplifies and accelerates development. Your business logic will be clearer and simpler because it won't be tangled with the infrastructure code
References : wiki source2
According to Martin Fowler, he and some others came up with it as a way to describe something which was a standard class as opposed to an EJB etc.
Usage of the term implies what it's supposed to tell you. If, for example, a dependency injection framework tells you that you can inject a POJO into any other POJO they want to say that you do not have to do anything special: there is no need to obey any contracts with your object, implement any interfaces or extend special classes. You can just use whatever you've already got.
UPDATE To give another example: while Hibernate can map any POJO (any object you created) to SQL tables, in Core Data (Objective C on the iPhone) your objects have to extend NSManagedObject in order for the system to be able to persist them to a database. In that sense, Core Data cannot work with any POJO (or rather POOCO=PlainOldObjectiveCObject) while Hibernate can. (I might not by 100% correct re Core Data since I just started picking it up. Any hints / corrections are welcome :-) ).
Plain Old Java Object :)
Well, you make it sound like those are all terrible restrictions.
In the usual context where POJO is/are used, it's more like a benefit:
It means that whatever library/API you're working with is perfectly willing to work with Java objects that haven't been doctored or manhandled in any way, i.e. you don't have to do anything special to get them to work.
For example, the XStream XML processor will (I think) happily serialize Java classes that don't implement the Serializable interface. That's a plus! Many products that work with data objects used to force you to implement SomeProprietaryDataObject or even extend an AbstractProprietaryDataObject class. Many libraries will expect bean behavior, i.e. getters and setters.
Usually, whatever works with POJOs will also work with not-so-PO-JO's. So XStream will of course also serialize Serializable classes.
POJO is a Plain Old Java Object - as compared to something needing Enterprise Edition's (J2EE) stuff (beans etc...).
POJO is not really a hard-and-fast definition, and more of a hand-wavy way of describing "normal" non-enterprise Java Objects. Whether using an external library or framework makes an object POJO or not is kind of in the eye of the beholder, largely depending on WHAT library/framework, although I'd venture to guess that a framework would make something less of a POJO
The whole point of a POJO is simplicity and you appear to be assuming its something more complicated than it appears.
If a library supports a POJO, it implies an object of any class is acceptible. It doesn't mean the POJO cannot have annotations/interface or that they won't be used if they are there, but it is not a requirement.
IMHO The wiki-page is fairly clear. It doesn't say a POJO cannot have annotations/interfaces.
What does the term Plain Old Java Object (POJO) mean?
POJO was coined by Martin Fowler, Rebecca Parsons and Josh Mackenzie when they were preparing for a talk at a conference in September 2000. Martin Fowler in Patterns of Enterprise Application Architecture explains how to implement a Domain Model pattern in Java. After enumerating some of disadvantages of using EJB Entity Beans:
There's always a lot of heat generated when people talk about
developing a Domain Model in J2EE. Many of the teaching materials and
introductory J2EE books suggest that you use entity beans to develop a
domain model, but there are some serious problems with this approach,
at least with the current (2.0) specification.
Entity beans are most useful when you use Container Managed
Persistence (CMP)...
Entity beans can't be re-entrant. That is, if you call out from one
entity bean into another object, that other object (or any object it
calls) can't call back into the first entity bean...
...If you have remote objects with fine-grained interfaces you get
terrible performance...
To run with entity beans you need a container and a database
connected. This will increase build times and also increase the time
to do test runs since the tests have to execute against a database.
Entity beans are also tricky to debug.
As an alternative, he proposed to use Regular Java Objects for Domain Model implementation:
The alternative is to use normal Java objects, although this often
causes a surprised reaction—it's amazing how many people think that
you can't run regular Java objects in an EJB container. I've come to
the conclusion that people forget about regular Java objects because
they haven't got a fancy name. That's why, while preparing for a talk
in 2000, Rebecca Parsons, Josh Mackenzie, and I gave them one: POJOs
(plain old Java objects). A POJO domain model is easy to put together,
is quick to build, can run and test outside an EJB container, and is
independent of EJB (maybe that's why EJB vendors don't encourage you
to use them).
There is an abundance of posts that are half correct and half incorrect. The best example of the correct interpretation is given by Rex M in their answer here.
[POJO are classes] that doesn't require any significant "guts" to make
it work. The idea is in contrast with very dependent objects that have
a hard time being (or can't be) instantiated and manipulated on their
own - they require other services, drivers, provider instances, etc.
to also be present.
Unfortunately, these very same answers often come along with the misunderstanding that they are somehow simple or often have a simple structure. This is not necessarily true and the confusion seems to stem from the fact that in the Java (POJO) and C# world (POCO) business logic is relatively easily modeled especially in the web application world.
POJO's can have multiple levels of inheritance, generic types, abstractions, etc. It just so happens that this isn't required in the majority of web applications as business logic doesn't necessitate it - alot of the effort goes into databases, queries, data transfer objects and repositories.
As soon as you step out of line with simple web apps, your POJO's start looking a lot more complex. E.g. Make a web app that assigns taxi's to user schedules. To do this, you need a graph coloring algorithm. To color the graphs, you need a graph object. Each node in the graph is a schedule object. Now what if we want to make it generic so that coloring the graph can be done not only with schedules but other things as well. We can make it generic, abstract and add levels of inheritance - almost to the point of making it a mini library.
At this point though, no matter its complexity, its still a POJO because it doesn't rely on the guts of other frameworks.
A Plain Old Java Object (POJO) that contains all of the business logic for your extension.
Exp. Pojo which contains a single method
public class Extension {
public static void logInfo(String message) {
System.out.println(message);
}
}
I would like to separate the API I'm working on into two sections: 'bare-bones' and 'cushy'. The idea is that all method calls in the 'cushy' section could be expressed in terms of the ones in the 'bare-bones' section, that is, they would only serve as convenience methods for the quick-and-dirty. The reason I would like to do this is that very often when people are beginning to use an API for the first time, they are not interested in details and performance: they just want to get it working.
Anybody tried anything similar before? I'm particularly interested in naming conventions and organizing the code.
One way to provide a discrete separation of 'cushy' vs 'bare-bones' would be using separate interfaces that are implemented by the same class. When writing an API I like to keep it as simple as possible. If you need lots of parameters, consider using a fluent interface.
Yes, I've done something like this before, and I tend to pre-pend a word that indicates what the extra functionality is doing.
For example, a basic Vector class might only perform very basic vector operations (add, dot product), and a Vectors class might have a variety of static helper methods (cross products, projections, etc). Then, a FluentVector incorporates all those helper operations, while mutating the underlying Vector.
However, this isn't the decorator pattern - decorator produces different "decorated" results with the same interface. This is the facade pattern - different interface with the same underlying function.
Also, keep in mind that your extended API may have a variety of different ways of delivering the same function. Back to my Vector example, one might not want to mutate the underlying Vector with each chained-operation and instead introduce a new Vector - this might be an ImmutableFluentVector or some such. The API would be identical, except for the specification of side-effects. Just something to keep in mind.
Since you're asking for nice names, commonly used is simple or basic API and extended API. The simple API uses, as mentioned by Simon Nickerson, the extended API technically by providing an abstraction. See also Facade Pattern
Assuming Barebone provides basic functionality and Cushy provides additional functionality:
public class Skeleton
{
public virtual void Info()
{
}
}
public class Adorner:Skeleton
{
private Skeleton _skeleton;
public Adorner(Skeleton skeleton)
{
_skeleton = skeleton;
}
public override void Info()
{
//apply adorning work
}
}
Skeleton bareBones = new Skeleton();
Adorner cushy = new Adorner(bareBones);
Somebody at work suggested Foo and FooHelper. I like it.