Sobes.tech
Junior

What is a Value Object and where is it used? Provide a practical example.

sobes.tech AI

Answer from AI

Value Object (value object) is an object characterized by its values rather than its identity. Unlike entities, a Value Object does not have a unique identifier, and two objects are considered equal if their fields match.

Value Objects are used to model concepts where data is important, such as coordinates, money, date and time, address, etc. This helps make the code more expressive and avoid errors related to state changes.

Example in Go: defining a Value Object to represent the coordinates of a point on a plane.

package main
import (
    "fmt"
)

type Point struct {
    X, Y float64
}

// Method to compare two points
func (p Point) Equals(other Point) bool {
    return p.X == other.X && p.Y == other.Y
}

func main() {
    p1 := Point{X: 10, Y: 20}
    p2 := Point{X: 10, Y: 20}
    p3 := Point{X: 5, Y: 15}

    fmt.Println(p1.Equals(p2)) // true
    fmt.Println(p1.Equals(p3)) // false
}

Here, Point is a Value Object that has no identifier and is compared by its field values.