where to instantiate simple values /entity objects? DDD - java

Using domain driven design, where are simple value objects/entities instantiated?
For example, if i needed to create a simple value object in a service class, would I just call the new operator on the value object's class, coupling this to the service class?
Can the new operator be called in a service class according to domain driven design?
These value objects can't be injected through a DI container and they don't warrant the use of a factory because of their simplicity.

What's wrong with instantiating them directly from their constructor?
Usually you only want factories when the instantiation process is complex or when you want to relieve the client from choosing a concrete class.
However, since the ubiquitous language is crucial in DDD it's quite common that an aggregate will have factory methods to create other aggregates to which they relates.
For example, rather than spawning project tasks out of thin air like below:
var task = new Task(projectId, ...);
You could do:
var task = project.addTask(...);
That would express the "tasks can be added to projects" use case better at the cost of having to load a Project aggregate.

Related

Spring : Singleton VS Prototype

i'm new to Spring starting to learn new concepts , and i found topic speaking about bean Scopes :
- Singleton : returns the same instance every time.
- Prototype : returns new instance of the object per every request.
my question is : how is this helpful for me what is the difference between the same instance , and new instance of the object , or why the prototype scope exists !
Same instance would mean any call (from anywhere) to getBean() from ApplicationContext or BeanFactory will land you with the same instance, i.e. constructor is called just once when Spring is being initialized (per Spring container).
However, there are scenarios when you would want different object instances to work with.
For example, if you have a Point object as a member variable in a Triangle class, in case of Singleton, when the Triangle class is being instantiated, the Point object also is instantiated as it is dependent.
If you require a different instance of Point to work with elsewhere, then you will need to define the Point as a prototype, else it carries the same state.
Googling would surely help you find answers and examples demonstrating the use case.
Hope this helps.
In case if the same instance is injected everywhere as Singleton, you can use it's shared state for containing any kind of data. In case if new instance is created any time bean is being injected - it's state is not shared. By default all beans are Singletons. Prototype scope stands for cases when bean's inner data should be unique for each place you inject bean into.
Example: you have the bean which represents REST client. Different parts of application use different REST services, each requires some specific request headers - for security purposes, for example. You can inject the same REST client in all these beans to have it's own REST client bean with some specific headers. At the same time you can configure client's politics in common for the whole application - request timeouts, etc.
See also: When to use Spring prototype scope?
It helps in designing a software, refer java design patterns you fill find much useful information, In case of singleton you will be able to create only object, it will helps cases like 1.saving time in creating a very complex object (we can reuse the same object) 2.Some times we need to use the same object throughout the application E.g if you want count the total number of active users in the application, you can use singleton object to store it, because there will be only one object so you can easily update and retrieve data. In case of Prototype it will always give you different object, it is necessary in some cases like some access token, you should always get the new /valid token to proceed further, so prototype pattern /Bean is useful.
My understanding for Singleton is more likely used in the situation like return single Utility instance.
//SomeUtil is Singleton
var util = SomeUtil.getInstance();
print(util.doTask1());
print(util.doTask2());
If another thread goes into these code, SomeUtil.getInstance() just return the SomeUtil instance other than creating a new one (which might cost much to create a new one).
As to Prototype, I just found this situation using Prototype:
Lets understand this pattern using an example. I am creating an entertainment application that will require instances of Movie,
Album and Show classes very frequently. I do not want to create their instances everytime as it is costly.
So, I will create their prototype instances, and everytime when i will need a new instance,
I will just clone the prototype.
Example code locates https://github.com/keenkit/DesignPattern/tree/master/src/PrototypePattern

How to add java custom or string object to DAO model object at runtime?

I need to add new String object to Array of custom type object, ServiceOrderEntity in this case. I know that this kind of breaks ServiceOrderEntity integrity but I have to access this field from jsp. What is the best way to do it?
DAO class:
...
SQLQuery localSQLQuery = localSession.createSQLQuery(query).addEntity(ServiceOrderEntity.class);
localList = localSQLQuery.list();
Iterator itr = localList.iterator();
while (itr.hasNext()){
String field = "some value";
itr.next().append( field ); // something like that maybe....
}
return to Service class
...
Service class
...
List list = perform DAO request
model.addAttribute("serviceOrderList", localList);
....
UPDATE
I have all models generated by Hibernate and I don't want to touch them. I need to add to custom object, in this case ServiceOrderEntity or find workaround. I think I can make copy of it and append new field to it (using Dozer)? New fields is result of other complex subqueries.
List of ServiceOrderEntity objects at runtime:
-list
--[0]model.ServiceOrderEntity#d826d3c7
---createdBy = {....}
---serviceRequestFK{java.Lang.Integer} // << this one
--[1]
....
etc
I need to get name using serviceRequestFK in ServiceOrderEntity. As long as java doesn't allow hot fix (to add custom filed to already created object) I need to find a way to pass to JSP the name field as well. What is the right way?
I really don't want to include DAO mathod requests from jsp...
Create separate list of names?...
Since Java does not allow mix-ins (aka monkey-patching) you'll have to:
Add the field to the base entity.
Return a sub-class that includes this field.
If you'd like to add the field so that the Service class can do its job, then fair enough. However, if the new field is part of the payload in/out then consider instead for that particular service then consider:
Making use-case specific payloads for each service call.
Map the results of these onto your reusable object model. (You can use something like Dozer for this).
The rationale behind this suggestion is to follow the principles of contract-first development.
Your model will be more general purpose, and thus reusable. You can add reusable behaviors to your model classes. Your services will use these behaviors to orchestrate process. (As opposed to having 'anaemic' entitites).
Your service payloads can remain relatively stable over time. So changes to your model won't effect all of your service subscribers. (aka "don't spill your guts").

When to use Spring prototype scope?

I want to know when should I exactly use the prototype scope in Spring? I have understood that singleton returns the same object instance if the bean is requested for.
Then why should we consider prototype?
Explanations with examples would help a lot to understand the need for it.
To be clear simple definitions:
Prototype scope = A new object is created each time it is injected/looked up. It will use new SomeBean() each time.
Singleton scope = The same object is returned each time it is injected/looked up. Here it will instantiate one instance of SomeBean and then return it each time.
Prototype bean is created at the time of usage. So when you would like to have stateful beans there is a strong need sometimes to have prototypes scope or when you don't want to cache any values in beans. Prototype bean can be associated with one session or some call.
Example:
A data access object (DAO) is not typically configured as a prototype, because a typical DAO does not hold any conversational state; it was just easier for this author to reuse the core of the singleton diagram.
There are some interesting use cases by using scope prototype you will build a better and reliable application design/architecture, for example, a real-time system.
Imagine that you must build a real-time system for vehicle tracking, and you will have 2.000.000 cars sharing information every 5 seconds,
In the server side, you will work with two or more distinct group of configurations, one for Cars and another one for Trucks.
Based on this simple example, if you design your application to work with distinct configuration groups in memory through the prototype pattern you will achieve a better performance.
So, in this case, whenever the server receives a new message from a Truck, for example, the server will get the instance of the configuration in memory from a hashmap of instances of VehicleGrupConfiguration and then apply the configuration behavior that this message must have, e.g: like time-out, retry... and etc.
I would like to highlight that there are many ways to implement this situation, but this example shows that a prototype pattern is very powerful in matters of performance and design patterns.
As the documentation says, creating a bean Foo with prototype scope is same as calling:
Foo foo = new Foo(dependency1, dependency2, ...);
foo.initialize(dependency7, dependency8...);
The only good reason to use a prototype scope bean instead of new that is when the dependencies used for creation and initialization of the instance should be kept outside the code that needs a new instance.
As an example:
// need to explicitly mention dependencies here
public void createdWithNew(Dependency dependency1, Dependency dependency2) {
Foo foo = new Foo(dependency1, dependency2, ...);
foo.doSomething();
}
// Dependencies managed in class Foo by Spring
public void createdWithSpring(Foo foo) {
foo.doSomething();
}
An example is if you wanted to write persistence code similar to EJB2 Java Entity beans, such as
Person p = ...
p.setName("John Doe");
p.save(); // write to DB
Instead of using the JPA way
Person p = new Person();
p.setName("John Doe");
personService.save(p); // write to DB
In the entity bean code style, the person instance needs to know how it should be persisted, so it needs to be injected with persistence details that the code writing a person should not be aware about.
Another example:
If you want to use the non-threadsafe SimpleDateFormat Java class in many places of your application, with a format pattern from a configuration file(maybe using different formats depending on other conditions). Instead of creating a new format instance in all those places loading also the formatting string from a file (or spring property), you could use the prototype scope to get a fresh instance every time, with the details of setting the common format being in one place.

Custom Constructor : Apache Cayenne 3.2M

I'm new to the API. It appears to me that you have to construct objects via the 'context' object like this:
ServerRuntime cayenneRuntime = new ServerRuntime("cayenne-project.xml");
context = cayenneRuntime.newContext()
...
MyEntity entity=context.newObject(MyEntity.class);
Rather than just creating Java Objects in the usual new() way:
MyEntity entity=new MyEntity();
But I want to create a constructor for my 'MyEntity' class that would do something like:
public MyEntity(String inputFile) {
...
do setters based on information derived from inputFile (size, time created etc).
...
How can I achieve this - ideally I want to keep the logic on the class MyEntity itself, rather than having a 'wrapper' class somewhere else to instantiate the object and perform the setting.... I guess I could have a 'helper' method which just the settings on a previously instantiated instance...but is there an idiom I'm missing here...?
You got it right about creating the object via 'context.newObject(..)' - this is the best way to do it and will keep you out of trouble. Still you can actually have your own constructor (provided you also maintain a default constructor for the framework to use):
public MyEntity(String inputFile) {
...
}
public MyEntity() {
}
Then you can create your object first, and add it to the context after that:
MyEntity e = new MyEntity(inputFile);
context.registerNewObject(e);
As far as idioms go, a very common one is to avoid business logic in persistent objects. ORM models are often reused in more than one application, and behavior you add to the entities doesn't uniformly apply everywhere. The other side of this argument is that anything but simplest methods depend on the knowledge of the surrounding environment - something you don't want your entities to be aware of.
Instead one would write a custom service layer that sits on top of the entities and contains all the business logic (often used with a dependency injection container). Services are not wrappers of entities (in fact services are often singletons). You can think of them as configurable strategy objects. In the Java world such layered design and this type of separation of concerns is very common and is probably the most flexible approach.
But if you want to hack something quickly, and don't envision it to grow into a complex multi-module system, then using a custom constructor or a static factory method in the entity is just fine of course.

Play Framework 2 / Redundant object validations

Suppose a Car model object (as case class), immutable and created using builder pattern. (Builder pattern by Joshua Bloch).
Its build method calls a CarValidator object in order to allow creation or not of the concerned Car. Otherwise, it throws an IllegalStateException with unexpected fields precised.
Thus, no one could create a stale or invalid Car at any time at Runtime, great!
Suppose now a web form to create a Car. Play's controller would contain this form mapping:
val carForm = Form( //this is a conceptual sample
mapping(
"brand" -> nonEmptyText,
"description" -> nonEmptyText,
"maxSpeed" -> number
"complexElement" -> number.verifying(........) //redundant validation here
)(Car.apply)(Car.unapply)
)
In this example, there are some basics fields, but imagine more complex fields demanding complex business validations like the complexeElement here.
I really have the feeling that I would easily break the DRY(Don't Repeat Yourself).
Indeed, whatever the form validation would bring, this would be already provided by my Car builder's validator, since validation on model is THE most important validation place and shouldn't depend on anything else.
I imagine a solution with a Helper class near my Controller dealing with the same validator object that my builder uses. However, it forces me to get all validation methods public in order to be called independently at any validation step of my web form (like in the code snippet above).
What would be a good practice to keep this builder principle while avoiding breaking DRY?
If you want to keep the builder pattern, you should not have Form create instances. The form should just make sure the information that comes in is of the correct type. The form can not create the final Car because it does not know the rules to make a Car, the builder does.
So I would say you let the form put stuff into an intermediary object (a tuple or PossibleCar case class) and build your Car (using the builder) with that object.
There is another route available, but that means that you must create (possibly complex) structures that let's you adapt the different types of validation. Both the builder and form can then use these validations (with the help of adapters) to create valid cars. I don't know enough about the situation you're in to give you advise on which route to take.

Categories