Skip to content

Builder pattern

Quality Score

Overall Score: 9.5/10 ⭐ Outstanding

  • Technical Accuracy: 33/35
  • Code Quality: 25/25
  • Educational Value: 23/25
  • Documentation: 14/15

The builder pattern is a creational pattern that allows to create complex object step-by-step. The default constructor of the object is not used, instead a builder class is used to make new instances of the object. The builder class has methods to set the properties of the object, returning the object itself at the end of each method. Using this pattern, you can construct different representations of the same object. Builder also validates the different properties if the object, ensuring that object is always in a valid state. The main benefits of this pattern are:

  • Encapsulation: The builder pattern encapsulates the construction of an object, allowing for more flexible and maintainable code.
  • Validation: The builder pattern allows for validation of the object's properties, ensuring that the object is always in a valid state.
  • Fluent Interface: The builder pattern allows for a fluent interface, making the code more readable and expressive.

The builder pattern is composed of three main components:

Builder interface

The builder interface represents a abstract class that define the methods that the concrete builder class must implement. It defines the methods to set the properties of the object, returning the object itself at the end of each method.

src.advanced.builder_pattern.TripBuilder

Bases: ABC

Abstract base class for trip builders in the builder pattern.

This interface defines the contract that all concrete trip builders must implement. Different builders can enforce different business rules and validation logic appropriate for their trip type.

Each method should handle setting properties with appropriate validation and default behavior for the specific builder type.

Source code in src/advanced/builder_pattern/builder.py
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
class TripBuilder(ABC):
    """Abstract base class for trip builders in the builder pattern.

    This interface defines the contract that all concrete trip builders must
    implement. Different builders can enforce different business rules and
    validation logic appropriate for their trip type.

    Each method should handle setting properties with appropriate validation
    and default behavior for the specific builder type.
    """

    @abstractmethod
    def set_name(self, name: str) -> "TripBuilder":
        """Set the name of the trip.

        Args:
            name: The name to set for the trip.

        Returns:
            Self for method chaining.
        """
        pass

    @abstractmethod
    def set_destination(self, destination: str) -> "TripBuilder":
        """Set the destination of the trip.

        Args:
            destination: The destination to set for the trip.

        Returns:
            Self for method chaining.
        """
        pass

    @abstractmethod
    def set_passengers(self, passengers: list[str]) -> "TripBuilder":
        """Set the passengers for the trip.

        Args:
            passengers: The list of passengers to set for the trip.

        Returns:
            Self for method chaining.

        Raises:
            ValueError: If passenger list violates builder-specific constraints.
        """
        pass

    @abstractmethod
    def set_budget(
        self,
        minimum_budget: float,
        maximum_budget: float,
    ) -> "TripBuilder":
        """Set the minimum and maximum budget for the trip.

        Args:
            minimum_budget: The minimum budget for the trip.
            maximum_budget: The maximum budget for the trip.

        Returns:
            Self for method chaining.

        Raises:
            ValueError: If budget violates builder-specific constraints.
        """
        pass

    @abstractmethod
    def build(self) -> Trip:
        """Construct and return the final Trip object.

        Returns:
            The constructed Trip instance.
        """
        pass

The builder interface is not strictly necessary, but it is a good practice to define an interface for the builder, allowing for more flexibility and maintainability.

Builder implementation

The builder implementation is responsible for constructing the object, applying business logic. It has implemented the methods to set the properties of the object, returning the object itself at the end of each method. Also, it has a method to return the constructed object.

src.advanced.builder_pattern.EconomyTripBuilder

Bases: TripBuilder

Concrete builder for creating economy trips.

Economy trips are budget-conscious with the following characteristics: - Maximum budget capped at 1000 per person - No passenger limit (group-friendly) - Basic amenities included - Suitable for budget travelers and large groups

Source code in src/advanced/builder_pattern/builder.py
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
class EconomyTripBuilder(TripBuilder):
    """Concrete builder for creating economy trips.

    Economy trips are budget-conscious with the following characteristics:
    - Maximum budget capped at 1000 per person
    - No passenger limit (group-friendly)
    - Basic amenities included
    - Suitable for budget travelers and large groups
    """

    # Class constants for validation
    MAX_BUDGET_PER_PERSON = 1000.0
    DEFAULT_AMENITIES = ["Standard accommodation", "Group transport"]

    def __init__(self) -> None:
        """Initialize a new EconomyTripBuilder with default amenities."""
        self.trip = Trip(
            type=TripType.ECONOMY,
            amenities=self.DEFAULT_AMENITIES.copy(),
        )

    def set_name(self, name: str) -> "EconomyTripBuilder":
        """Set the name of the economy trip.

        Args:
            name: The name to set for the trip.

        Returns:
            Self for method chaining.
        """
        self.trip.name = name
        return self

    def set_destination(self, destination: str) -> "EconomyTripBuilder":
        """Set the destination of the economy trip.

        Args:
            destination: The destination to set for the trip.

        Returns:
            Self for method chaining.
        """
        self.trip.destination = destination
        return self

    def set_passengers(self, passengers: list[str]) -> "EconomyTripBuilder":
        """Set the passengers of the economy trip.

        Economy trips have no passenger limit, making them ideal for groups.

        Args:
            passengers: The list of passengers to set for the trip.

        Returns:
            Self for method chaining.
        """
        self.trip.passengers = passengers
        return self

    def set_budget(
        self,
        minimum_budget: float,
        maximum_budget: float,
    ) -> "EconomyTripBuilder":
        """Set the budget for the economy trip.

        Economy trips enforce a maximum budget cap per person to maintain
        affordability.

        Args:
            minimum_budget: The minimum budget for the trip.
            maximum_budget: The maximum budget for the trip.

        Returns:
            Self for method chaining.

        Raises:
            ValueError: If maximum budget is less than minimum budget or
                       exceeds the per-person cap.
        """
        if maximum_budget < minimum_budget:
            raise ValueError(
                "Maximum budget cannot be less than minimum budget",
            )

        # Enforce economy budget cap per person
        num_passengers = (
            len(self.trip.passengers) if self.trip.passengers else 1
        )
        max_allowed = self.MAX_BUDGET_PER_PERSON * num_passengers
        if maximum_budget > max_allowed:
            raise ValueError(
                f"Economy trip maximum budget cannot exceed "
                f"{self.MAX_BUDGET_PER_PERSON} per person "
                f"({max_allowed} for {num_passengers} passenger(s))",
            )

        self.trip.minimum_budget = minimum_budget
        self.trip.maximum_budget = maximum_budget
        return self

    def build(self) -> Trip:
        """Build and return the economy trip.

        Returns:
            The constructed economy Trip instance.
        """
        return self.trip

src.advanced.builder_pattern.LuxuryTripBuilder

Bases: TripBuilder

Concrete builder for creating luxury trips.

Luxury trips provide premium experiences with the following characteristics: - Minimum budget of 10,000 to ensure quality - Maximum of 4 passengers for exclusivity - Premium amenities included (5-star hotels, private transport, concierge) - Suitable for high-end travelers seeking personalized experiences

Source code in src/advanced/builder_pattern/builder.py
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
class LuxuryTripBuilder(TripBuilder):
    """Concrete builder for creating luxury trips.

    Luxury trips provide premium experiences with the following characteristics:
    - Minimum budget of 10,000 to ensure quality
    - Maximum of 4 passengers for exclusivity
    - Premium amenities included (5-star hotels, private transport, concierge)
    - Suitable for high-end travelers seeking personalized experiences
    """

    # Class constants for validation
    MIN_LUXURY_BUDGET = 10000.0
    MAX_PASSENGERS = 4
    DEFAULT_AMENITIES = [
        "5-star accommodation",
        "Private transport",
        "24/7 Concierge service",
        "Premium insurance",
    ]

    def __init__(self) -> None:
        """Initialize a new LuxuryTripBuilder with premium amenities."""
        self.trip = Trip(
            type=TripType.LUXURY,
            amenities=self.DEFAULT_AMENITIES.copy(),
        )

    def set_name(self, name: str) -> "LuxuryTripBuilder":
        """Set the name of the luxury trip.

        Args:
            name: The name to set for the trip.

        Returns:
            Self for method chaining.
        """
        self.trip.name = name
        return self

    def set_destination(self, destination: str) -> "LuxuryTripBuilder":
        """Set the destination of the luxury trip.

        Args:
            destination: The destination to set for the trip.

        Returns:
            Self for method chaining.
        """
        self.trip.destination = destination
        return self

    def set_passengers(self, passengers: list[str]) -> "LuxuryTripBuilder":
        """Set the passengers of the luxury trip.

        Luxury trips are limited to 4 passengers to maintain exclusivity
        and personalized service.

        Args:
            passengers: The list of passengers to set for the trip.

        Returns:
            Self for method chaining.

        Raises:
            ValueError: If passenger count exceeds maximum limit.
        """
        if len(passengers) > self.MAX_PASSENGERS:
            raise ValueError(
                f"Luxury trips are limited to {self.MAX_PASSENGERS} passengers "
                f"for exclusivity (got {len(passengers)})",
            )
        self.trip.passengers = passengers
        return self

    def set_budget(
        self,
        minimum_budget: float,
        maximum_budget: float,
    ) -> "LuxuryTripBuilder":
        """Set the budget for the luxury trip.

        Luxury trips enforce a minimum budget to ensure premium quality
        experiences and services.

        Args:
            minimum_budget: The minimum budget for the trip.
            maximum_budget: The maximum budget for the trip.

        Returns:
            Self for method chaining.

        Raises:
            ValueError: If budget is below luxury minimum or maximum is less
                       than minimum.
        """
        if maximum_budget < minimum_budget:
            raise ValueError(
                "Maximum budget cannot be less than minimum budget",
            )

        # Enforce luxury minimum budget
        if minimum_budget < self.MIN_LUXURY_BUDGET:
            raise ValueError(
                f"Luxury trips require a minimum budget of "
                f"{self.MIN_LUXURY_BUDGET} (got {minimum_budget})",
            )

        self.trip.minimum_budget = minimum_budget
        self.trip.maximum_budget = maximum_budget
        return self

    def build(self) -> Trip:
        """Build and return the luxury trip.

        Returns:
            The constructed luxury Trip instance.
        """
        return self.trip

Entity

The entity represents the object that is being constructed. It has all the properties that can be set by the builder, and it is responsible for maintaining the state of the object. No business logic is applied in the entity, it is only a data structure. Only consider to introduce any business logic when it is clearly related to the state of the object, and not to the construction process.

src.advanced.builder_pattern.Trip dataclass

Class representing a trip with customizable attributes and amenities.

This class serves as the product in the Builder pattern, constructed step-by-step by different builder implementations.

Attributes:

Name Type Description
name str

The name/title of the trip.

destination str

The destination location.

passengers list[str]

List of passenger names.

minimum_budget float

Minimum budget for the trip.

maximum_budget float

Maximum budget for the trip.

type str

Type of trip (Economy or Luxury).

amenities list[str]

List of included amenities/services.

Source code in src/advanced/builder_pattern/builder.py
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
@dataclass
class Trip:
    """Class representing a trip with customizable attributes and amenities.

    This class serves as the product in the Builder pattern, constructed
    step-by-step by different builder implementations.

    Attributes:
        name: The name/title of the trip.
        destination: The destination location.
        passengers: List of passenger names.
        minimum_budget: Minimum budget for the trip.
        maximum_budget: Maximum budget for the trip.
        type: Type of trip (Economy or Luxury).
        amenities: List of included amenities/services.
    """

    name: str = ""
    destination: str = ""
    passengers: list[str] = field(default_factory=list)
    minimum_budget: float = 0.0
    maximum_budget: float = 0.0
    type: str = TripType.ECONOMY
    amenities: list[str] = field(default_factory=list)

    def __str__(self) -> str:
        """Return a string representation of the trip."""
        return (
            f"{self.type} trip: {self.name}, "
            f"destination: {self.destination}, "
            f"passengers: {len(self.passengers)}, "
            f"budget: {self.minimum_budget}-{self.maximum_budget}, "
            f"amenities: {', '.join(self.amenities) if self.amenities else '-'}"
        )

Some real world applications of the builder pattern are: complex object creation and multiple object constructions.

Common pitfalls

A common pitfall of the builder pattern is to introduce business logic in the entity, instead of the builder. The entity should only be a data structure, and the builder should be responsible for applying business logic to construct the object.

Another common pitfall is to not validate the properties of the object in the builder, allowing for the object to be in an invalid state. The builder should always validate the properties before constructing the object.