Difference between a Value object template and a data transfer template

In what scenario can I use these design patterns in n-tier architecture?

+7
source share
8 answers

DTO is an object that can be used within the system. For example, if you have a SOAP web service and want to return a response, you should use DTO. It’s easier to handle than the actual XML that needs to be returned by cable. DTOs are often generated by tools based, for example, on WSDL. DTOs often adapt to customer service needs and may be affected by performance requirements.

Value objects, on the other hand, live in the core of the system. It captures parts of business logic and possibly formatting rules. This makes your code more secure and expressive. It also solves the problem of "primitive obsession." A good example is to use the SocialSecurityNumber class instead of a string. Or money instead of decimal. These objects must be immutable so that they are more like primitives and can be easily shared between different threads.

For example, in a hypothetical order-to-order system:

CustomerAndLastFiveOrders is a DTO (optimized to avoid multiple network calls)

Customer is Entity

Money and SKU - Value Objects

+13
source

Comparing DTO objects with object values ​​is similar to comparing oranges and apples.

They serve completely different situations. DTO defines the structure of an object / class of how data will be transferred between layers, and value objects determine the logic of equality when comparing values.

enter image description here

Let me explain the examples to you, let's first try to understand the objects of value: -

A Value object is an object whose equality is based on value, rather than identity.

Consider the code below, we created two objects of money: one rupee and the other one rupee currency.

Money OneRupeeCoin = new Money(); OneRupeeCoin.Value = 1; OneRupeeCoin.CurrencyType = "INR"; OneRupeeNote.Material = "Coin"; Money OneRupeeNote = new Money(); OneRupeeNote.Value = 1; OneRupeeCoin.CurrencyType = "INR"; OneRupeeNote.Material = "Paper"; 

Now, when you compare the above objects, the comparison below should be evaluated as true, because 1 rupee note is equal to 1 rupee in the real world.

Thus, either you use the "==" operator, or you use the Equals method, the comparison should be true. By default, "==" or "equals" will not evaluate to true, so you need to use operator overrides and override the method to get the desired behavior. You can see the link explaining how to achieve the same.

 if (OneRupeeCoin==OneRupeeNote) { Console.WriteLine("They should be equal"); } if (OneRupeeCoin.Equals(OneRupeeNote)) { Console.WriteLine("They should be equal "); } 

Objects with a normal value are good candidates for immutability; You can read about it from here . You can see this video that describes how you can create immutable objects.

Now let's try to understand DTO: -

DTO (Data Transfer Objects) is a data container to facilitate the transfer of data between layers.

They are also called transmission entities. DTO is used only for data transfer and does not contain business logic. They have only simple setters and getters.

For example, consider the call below, which we make with two calls to get customer data, and the other to get product data.

 DataAccessLayer dal = new DataAccessLayer(); //Call 1:- get Customer data CustomerBO cust = dal.getCustomer(1001); //Call 2:- get Products for the customer ProductsBO prod = dal.getProduct(100); 

Thus, we can combine the class Customer and Product in one class, as shown below.

 class CustomerProductDTO { // Customer properties public string CustomerName { get; set; } // Product properties public string ProductName { get; set; } public double ProductCost { get; set; } } 

Now with one call we can get both customer and product data. Data transfer objects are used in two scenarios to improve remote calls, and secondly, to align the hierarchy of objects; you can read this article , which explains more about data transfer objects.

 //Only one call CustomerProductDTO cust = dal.getCustomer(1001); 

Below is a complete comparison sheet.

enter image description here

+8
source

There are some good answers here, but I'll add one to catch a key difference:

Significant objects do not have an identity. That is, any comparison between two instances of the value object that contain should indicate that they are equal. Data transfer objects, although they are used only for storing values, have an identity. A comparison of two DTO instances that have the same values ​​but were created independently will not show that they are equal.

Example:

 DTO dto1 = new DTO(10); DTO dto2 = new DTO(10); dto1.equals(dto2); //False (if equals is not overridden) dto1 == dto2; //False VO vo1 = VO.getInstance(10); VO vo2 = VO.getInstance(10); vo1.equals(vo2); //True vo1 == vo2; //True 

It's a little tricky to implement a Value Object template in Java, because the == operator always compares the identity of an object. One way to do this is to implement an object cache that returns the same object for each value.

 public class VO { Map<Integer, WeakReference<VO>> cache = new LinkedHashMap<Integer, WeakReference<VO>>(); public static VO getInstance(int value) { VO cached = cache.get(value); if(cached == null) { cached = new VO(value); cache.put(value, new WeakReference<VO>(cached)); } return cached.get(); } private int value; private VO(int value) { this.value = value; } } 
+3
source

I would advise passing the data transfer object. This anti-EJB 1.0 template, in my opinion, attaches importance to those who insist on a clean layer.

Useful object is useful. This is usually an immutable object, like Money. They must be thread safe.

+2
source

A value object is something that is useful for encapsulation as an object, but it does not have an identifier. Compare it with an entity that has an identity. Thus, in the order processing system, the Client or Order or Linear object are concepts that indicate specific people or things or events, therefore they are entities where the value object is a kind of monetary amount that does not have an independent existence of its own. For example, for a system in which part of the application included calculating how to split the payment between different accounts, I created an immutable Money object that had a division method that returned an array of Money objects, evenly dividing the original amount of the object into them, since the code for dividing the sums was in a place where it was convenient when the person writing jsp could use it, and they did not have to ruin the jsp with code that was not related to the presentation.

A Data Transfer Object is a wrapper for combining things to be sent across application tiers or tiers. The idea is that you want to minimize the amount of network traffic in the opposite direction by developing methods for sending large packets of information.

+2
source

The Data Transfer Object is used to set property values ​​that come from the database at the data access level (DAO), while using the VO template we can set the values ​​at the MVC level that are already set at the DAO level. A client can have access to VO objects, not DTOs, which he / she can iterate over on the jsp page. You can say that there is a separation of problems for both layers.

+1
source

DTO is a class that represents some data without any logic. DTOs are typically used to transfer data between different applications or at different levels within a single application. You can think of them as stupid packets of information whose sole purpose is simply to pass this information to the recipient.

On the other hand, Value Object is a full member of your domain model. It follows the same rules as the entity. The only difference between Value Object and Entity is that Value Object does not have its own identity. This means that two objects of value with the same set of properties should be considered the same, while two objects are different, even if their properties coincide.

Value objects contain logic and, as a rule, they are not used to transfer data between application boundaries. Find out more here.

+1
source

A value object and a data transfer object are a design pattern.

  • Value Object : Use when you need to measure the equality of objects based on the value of objects.

A real world example is java.time.LocalDate

 public class HeroStat { // Stats for a hero private final int strength; private final int intelligence; private final int luck; // All constructors must be private. private HeroStat(int strength, int intelligence, int luck) { this.strength = strength; this.intelligence = intelligence; this.luck = luck; } // Static factory method to create new instances. public static HeroStat valueOf(int strength, int intelligence, int luck) { return new HeroStat(strength, intelligence, luck); } public int getStrength() { return strength; } public int getIntelligence() { return intelligence; } public int getLuck() { return luck; } /* * Recommended to provide a static factory method capable of creating an instance from the formal * string representation declared like this. public static HeroStat parse(String string) {} */ // toString, hashCode, equals @Override public String toString() { return "HeroStat [strength=" + strength + ", intelligence=" + intelligence + ", luck=" + luck + "]"; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + intelligence; result = prime * result + luck; result = prime * result + strength; return result; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } HeroStat other = (HeroStat) obj; if (intelligence != other.intelligence) { return false; } if (luck != other.luck) { return false; } if (strength != other.strength) { return false; } return true; } // The clone() method should not be public. Just don't override it. } 

- Data Transfer Object : transferring data with several attributes in one frame from the client to the server to avoid multiple calls to the remote server.

  public class CustomerDto { private final String id; private final String firstName; private final String lastName; /** * @param id customer id * @param firstName customer first name * @param lastName customer last name */ public CustomerDto(String id, String firstName, String lastName) { this.id = id; this.firstName = firstName; this.lastName = lastName; } public String getId() { return id; } public String getFirstName() { return firstName; } public String getLastName() { return lastName; } } 
0
source

Source: https://habr.com/ru/post/894566/


All Articles