<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Michał Godkowicz on Medium]]></title>
        <description><![CDATA[Stories by Michał Godkowicz on Medium]]></description>
        <link>https://medium.com/@michalgodkowicz?source=rss-fd6670228960------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*iUOOD2TWFzFkdbuaUlsq7g.png</url>
            <title>Stories by Michał Godkowicz on Medium</title>
            <link>https://medium.com/@michalgodkowicz?source=rss-fd6670228960------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 20 Nov 2026 23:09:05 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@michalgodkowicz/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Reducing Complexity in Django Models With Value Objects]]></title>
            <link>https://medium.com/better-programming/reducing-complexity-in-django-models-with-value-objects-fa8e9b496c20?source=rss-fd6670228960------2</link>
            <guid isPermaLink="false">https://medium.com/p/fa8e9b496c20</guid>
            <category><![CDATA[django]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[ddd]]></category>
            <category><![CDATA[domain-driven-design]]></category>
            <dc:creator><![CDATA[Michał Godkowicz]]></dc:creator>
            <pubDate>Tue, 31 Jan 2023 09:44:41 GMT</pubDate>
            <atom:updated>2023-02-10T10:28:27.484Z</atom:updated>
            <content:encoded><![CDATA[<h4>Implementing the value object pattern</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*wJt3_Wf5_zOraEsK" /><figcaption>Photo by <a href="https://unsplash.com/@elnazasadi?utm_source=medium&amp;utm_medium=referral">elnaz asadi</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><a href="https://martinfowler.com/eaaCatalog/valueObject.html">Martin Fowler</a> defines value objects in the following way:</p><blockquote>A small simple object, like money or a date range, whose equality isn’t based on identity.</blockquote><p>Ok, but what does it mean?</p><p>The important thing about Value Objects is that they are equal to each other if they have the same information, not just if they are the same object in memory. So, two value objects that represent the same date or the same amount of money would be considered equal. Additionally, value objects are declared as immutable, meaning their values cannot be changed after they are created, which further ensures the consistency of data in an application.</p><p>Using value objects helps avoid the issue of “primitive obsession,” which occurs when we use basic data types like integers or strings in place of more meaningful data structures. For instance, using a string to represent an email address. By using value objects, we can create more meaningful, self-contained representations of data.</p><p>The concept of Value Objects originates from Domain-Driven Design (DDD) and is utilized along with entities and aggregates to model domain models. In this article, I will demonstrate the usage of Value Objects with raw Django models. This can serve as a useful first step towards better architecture or simply as a refactoring measure that helps keep models concise and less complex.</p><p>To illustrate the use of value objects in Django models, let’s look at a common scenario: describing the start and end dates of an event. A basic implementation of this might look like the following:</p><pre>class Appointment(models.Model):<br>    start = models.DateTimeField(null=True)<br>    end = models.DateTimeField(null=True)</pre><p>However, as the complexity of the model increases, this simple implementation may become insufficient.</p><p>For example, you may need to check if one appointment overlaps another, or determine if it starts before or after another event.</p><p>To handle these scenarios, we can use a custom value object to describe the date range of an appointment.</p><pre>@dataclass(frozen=True) (1)<br>class DateRange:<br>    start: datetime<br>    end: datetime<br><br>    def __post_init__(self) -&gt; None: (2)<br>        if self.start &gt;= self.end:<br>            raise ValueError(&quot;Can not end before starting.&quot;)<br><br>    def __str__(self) -&gt; str:<br>        return f&quot;DateRange({self.start} - {self.end})&quot;<br><br>    def __add__(self, other: timedelta) -&gt; &quot;DateRange&quot;: (3)<br>        if isinstance(other, timedelta):<br>            return DateRange(self.start + other, self.end + other)<br><br>        raise TypeError()<br><br>    def hour_later(self) -&gt; &quot;DateRange&quot;: (4)<br>        return self + timedelta(hours=1)<br><br>    @property<br>    def duration(self) -&gt; timedelta: (5)<br>        return self.end - self.start<br><br>    def overlaps(self, date_range: &quot;DateRange&quot;) -&gt; bool: (5)<br>        return (self.start &lt;= date_range.end <br>            and self.end &gt;= date_range.start)<br><br>    def starts_before(self, date_range: &quot;DateRange&quot;) -&gt; bool: (5)<br>        return self.start &lt; date_range.start<br><br>    def range(self, step: timedelta) -&gt; Iterator[datetime]: (5)<br>        current_datetime = self.start<br>        while current_datetime &lt;= self.end:<br>            yield current_datetime<br>            current_datetime = current_datetime + step</pre><ol><li>We use the dataclass decorator for convenience, which helps us with type declarations and provides immutability with the frozen=True flag.</li><li>Basic validation to ensure that the model is always in a valid state.</li><li>Adding two date ranges doesn’t make sense, so we override the + operator to allow rescheduling. Since our class is immutable, we must return a new object.</li><li>As a more verbose alternative, we can utilize previously declared methods to create functions that use “business language,” making the code easier to understand.</li><li>Common utilities could be hidden behind a simple interface.</li></ol><p>To integrate the DateRange value object with the Appointment model, we need to add the following code:</p><pre>class Appointment(models.Model):<br>    _start = models.DateTimeField(null=True) (1)<br>    _end = models.DateTimeField(null=True)<br><br>    objects = CustomManager()<br><br>    @property<br>    def date_range(self) -&gt; DateRange: (2)<br>        return DateRange(self._start, self._end)<br><br>    @date_range.setter<br>    def date_range(self, value: DateRange) -&gt; None: (3)<br>        self._start = value.start<br>        self._end = value.end<br><br>    @classmethod<br>    def new_in_date_range(cls, date_range: DateRange): (4)<br>        return cls(_start=date_range.start, _end=date_range.end)</pre><ol><li>We use an underscore prefix (e.g. _start) to indicate that this is a private field, meaning it should not be used directly.</li><li>Getter property returns the DateRange value object.</li><li>Allows assigning a DateRange object to an Appointment.</li><li>The new_in_date_range method is a factory method that creates new Appointment objects with a DateRange value object.</li></ol><p>To support querying for start/end dates, we can use the CustomManager and CustomQuerySet classes:</p><pre>class CustomManager(models.Manager):<br>    def get_queryset(self):<br>        return CustomQuerySet(self.model, using=self._db)<br><br>    def in_range(self, date_range: DateRange):<br>        return self.get_queryset().filter(<br>            _start__gt=date_range.start,<br>            _end__lt=date_range.end<br>         )<br><br><br>class CustomQuerySet(models.QuerySet):<br><br>    def filter(self, *args, **kwargs):<br>        date_range = kwargs.get(&quot;date_range&quot;)<br><br>        if date_range and isinstance(date_range, DateRange):<br>            kwargs[&quot;_start&quot;] = date_range.start<br>            kwargs[&quot;_end&quot;] = date_range.end<br><br>        return super().filter(*args, **kwargs)</pre><p>Value objects can enforce simple rules, such as preventing the creation of a DateRange that ends before it starts.</p><p>Other examples of value objects include:</p><ul><li>Money: Two amounts of different currencies cannot be added together.</li><li>VAT rate: A distinction can be made between a VatRate of &quot;0&quot; and a VatRate of &quot;NOT_APPLIES&quot;, even though they both evaluate to 0.</li><li>Time zone</li><li>Email</li><li>Address.</li></ul><p>In some situations, the value object pattern can be implemented using Django custom model fields (e.g. <a href="https://github.com/django-money/django-money">django-money</a>). However, I believe this approach is more complex and heavily reliant on the framework. If you have a different experience, please let me know!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fa8e9b496c20" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/reducing-complexity-in-django-models-with-value-objects-fa8e9b496c20">Reducing Complexity in Django Models With Value Objects</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Another way to persist DDD Aggregates in Django]]></title>
            <link>https://michalgodkowicz.medium.com/another-way-to-persist-ddd-aggregates-in-django-d148f4cad298?source=rss-fd6670228960------2</link>
            <guid isPermaLink="false">https://medium.com/p/d148f4cad298</guid>
            <category><![CDATA[aggregates]]></category>
            <category><![CDATA[repository-pattern]]></category>
            <category><![CDATA[ddd]]></category>
            <category><![CDATA[domain-driven-design]]></category>
            <category><![CDATA[django]]></category>
            <dc:creator><![CDATA[Michał Godkowicz]]></dc:creator>
            <pubDate>Sat, 16 Jan 2021 16:26:43 GMT</pubDate>
            <atom:updated>2021-01-16T16:39:53.772Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4rDvvxB0INI5hxsIhg0ZKw.png" /></figure><p>Django ORM is powerful but it has its drawbacks. When you deal with more complicated domains, you may have a temptation to use concepts from <a href="https://www.google.com/search?client=firefox-b-d&amp;q=domain+driven+design">DDD</a> methodology. Soon, you will notice that it requires a lot of boring, boilerplate code that maps your Django models into Entities/Aggregates. This may look something like that:</p><pre>class CreditCardORM(models.Model):<br>    id = models.UUIDField(<br>        primary_key=True, default=uuid.uuid4, editable=False<br>    )<br>    balance_amount = models.DecimalField(<br>        max_digits=19, decimal_places=2<br>    )<br>    balance_currency = models.CharField(<br>        max_length=10<br>    )<br><br>    def to_domain(self) -&gt; CreditCard:  # returns domain model<br>        return CreditCard(<br>            self.id,<br>            Money(self.balance_amount, self.balance_currency)<br>        )<br><br>    @staticmethod<br>    def update_from_domain(credit_card: CreditCard) -&gt; None:<br>        CreditCardORM.objects.update_or_create(<br>            id=credit_card.id,<br>            defaults={<br>                &quot;balance_amount&quot;: credit_card.balance.amount,<br>                &quot;balance_currency&quot;:  credit_card.balance.currency<br>            }<br>        )</pre><pre># domain model<br>@dataclass<br>class CreditCard:<br>    id: UUID4<br>    balance: Money<br><br>    def withdraw(self, withdraw_amount: Money) -&gt; Result:<br>         # logic ...</pre><p>This model has only 3 fields but you have to maintain all changes and do it for every new Aggregate. Is it worth it?</p><p>To make my life easier I decided to leverage <a href="https://pydantic-docs.helpmanual.io/">pydantic</a> — a great library, that uses type hints, to provide data validation and json serialization, that we will use.</p><h4>Round 1</h4><pre>class CreditCard(BaseModel):<br>    id: UUID4<br>    balance: Money</pre><pre>    # This should live in some base class.<br>    class Config:<br>        orm_mode = True<br>    # logic ...<br> </pre><pre>class CreditCardRepository:<br><br>    def find(self, card_id: UUID4) -&gt; Optional[CreditCard]:<br>        card_data = CreditCardORM.objects.filter(id=card_id).first()<br>    (1) return CreditCard.from_orm(card_data) if card_data else None <br><br>    def save(self, card: CreditCard) -&gt; None:<br>    (2) card_snapshot = card.dict()<br>        card_id = card_snapshot.pop(&quot;id&quot;)<br>        CreditCardORM.objects.update_or_create(<br>            id=card_id,<br>            defaults=card_snapshot<br>        )</pre><pre>class CreditCardORM(models.Model):<br>    id = models.UUIDField(<br>        primary_key=True, default=uuid.uuid4, editable=False<br>    )<br>    balance_amount = models.DecimalField(<br>        max_digits=19, decimal_places=2<br>    )<br>    balance_currency = models.CharField(<br>        max_length=10<br>    )<br><br>    @property<br>    def balance(self) -&gt; Money:  (3)<br>        return Money(<br>            amount=self.balance_amount,     <br>            currency=self.balance_currency<br>         )<br><br>    @balance.setter  (3)<br>    def balance(self, value: Union[Money, dict]) -&gt; None:<br>        data = value<br>        if isinstance(value, Money):<br>            data = value.dict()<br><br>        self.balance_amount = data.get(&quot;amount&quot;)<br>        self.balance_currency = data.get(&quot;currency&quot;)</pre><ol><li>Use pydantic <em>.from_orm </em>method to easily parse from Django model to domain model.</li><li>Use pydantic <em>.dict() </em>method to parse domain model to dictionary.</li><li>We still have to manually map value objects.</li></ol><p>Advantages:</p><ul><li>Builtin JSON serialization.</li><li>Normalized database structure.</li></ul><p>Drawbacks:</p><ul><li>All fields in our model have to be json serializable. This may sometimes lead to ugly serialization code in our domain model or force to use only pydantic models.</li><li>Domain logic is not “clean python” anymore. We have dependency to external library in our core.</li><li>To use Value Objects like Money we have to manually implement getters and setters for the object and dict.</li></ul><h4>Round 2</h4><p>To make my life even simpler I decided to use JSONField instead.</p><pre>class CreditCard(BaseModel):<br>    id: UUID4<br>    balance: Money<br><br>    def withdraw(self, withdraw_amount: Money) -&gt; Result:<br>        # logic ...<br>        pass</pre><pre><br>class CreditCardJsonORM(models.Model):<br>    id = models.UUIDField(<br>        primary_key=True, default=uuid.uuid4, editable=False<br>    )<br>    timestamp = models.DateTimeField(<br>        auto_now=True, auto_created=True<br>    )<br>    data = models.JSONField()</pre><pre><br>class CreditCardJsonRepository:<br><br>    def find(self, card_id: UUID4) -&gt; Optional[CreditCard]:<br>        try:<br>            credit_card_model = CreditCardJsonORM.objects.get(<br>                id=card_id<br>            )<br>            return CreditCard.parse_obj(credit_card_model.data) (1)<br>        except CreditCardJsonORM.DoesNotExist:<br>            return None<br><br>    def save(self, card: CreditCard) -&gt; None:<br>        card_snapshot = json.loads(card.json()) (2)<br>        CreditCardJsonORM.objects.update_or_create(<br>            id=card.id, data=card_snapshot<br>        )</pre><ol><li>Thanks to dynamic json schema I don’t have to maintain mapping between models or even use pydantic orm_mode.</li><li>Use pydantic <em>.json() </em>method to parse domain model this time.</li></ol><p>Advantages</p><ul><li>Thanks to dynamic schema we can try to create one generic repository for all Aggregates.</li><li>Will also work with noSQL document databases like Mongo.</li><li>Value Objects parsed without any getters or setters.</li></ul><p>Drawbacks</p><ul><li>Reading data from JSON fields could be harder and slower. Probably forces us to use <a href="https://martinfowler.com/bliki/CQRS.html">CQRS</a> pattern.</li><li>Serialization still may be problematic.</li></ul><p>That was my experimental approach to aggregates persistence. I tried it on medium project, that has MongoDB underneath, and it worked pretty well. Let me know what you think!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d148f4cad298" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to make your Python code maintainable with the open/close principle]]></title>
            <link>https://michalgodkowicz.medium.com/how-to-make-your-python-code-maintainable-with-the-open-close-principle-1860fecc8ec0?source=rss-fd6670228960------2</link>
            <guid isPermaLink="false">https://medium.com/p/1860fecc8ec0</guid>
            <category><![CDATA[object-oriented]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[solid]]></category>
            <dc:creator><![CDATA[Michał Godkowicz]]></dc:creator>
            <pubDate>Mon, 07 Sep 2020 16:51:41 GMT</pubDate>
            <atom:updated>2020-09-07T16:51:41.545Z</atom:updated>
            <content:encoded><![CDATA[<p>How to avoid code spaghetti? How to refactor our if-else hell to something easier to read, painless to extend, and fun to work with.</p><p>The second principle of SOLID says</p><blockquote>“Software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification.”</blockquote><p>Let’s say we have to write code responsible for generating offers for our clients based on the order they made. There are a few conditions that have to be considered. Different types of clients need different logic. In very basic implementation this may look something like that:</p><pre>def generate_offer(order: Order) -&gt; Offer:<br>    offer = Offer(order.client)<br><br>    for product in order.get_ordered_products():<br>        product_price = product.price<br><br>        if order.client.is_regular:<br>            # imagine more complex logic here<br>            if product.quantity &gt; 10:<br>                discount = 0.9  # complicated logic<br>                product_price = product_price * discount<br>            elif product.quantity &gt; 5:<br>                product_price = product_price * 0.95<br>        elif order.client.is_vip:<br>            discount = 0.9  # complicated logic<br>            product_price = product_price * discount<br>        else:<br>            if product.quantity &gt; 15:<br>                # imagine more complex logic here<br>                product_price = product_price * 0.05<br><br>        offer.addItem(product, product_price)<br><br>    return offer</pre><p>This is a fairly simple example but will give us what we need. In real projects, we may have much more complicated logic and conditions could change based on a weekday or the number of products in the warehouse. Now imagine that this happened and we actually have not 20 but 8 thousand lines of code. How would you refactor code like that?</p><h3><strong>What should we look for?</strong></h3><p>Very often code can be split into 3 parts. We can look for parts that answer one of those 3 questions:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/548/1*WOpSKX5h2e8kPhu4aru34A.png" /></figure><p><strong>WHAT</strong> changes</p><p>This is a stable part of our code. It shouldn’t change much in the future. In this case, calculating the offer looks like something really steady.</p><pre>    # this code doesn&#39;t change<br>    offer = Offer(order.client)<br><br>    for product in order.get_ordered_products():<br><br>        offer.addItem(product, product_price)<br><br>    return offer</pre><p><strong>HOW</strong> it changes</p><p>In this part, we will know how the discount is calculated. All complex operations will be handled here.</p><pre>if product.quantity &gt; 10:<br>    discount = 0.9  # complicated logic<br>    product_price = product_price * discount<br>elif product.quantity &gt; 5:<br>    product_price = product_price * 0.95</pre><p><strong>WHY</strong> it changes</p><p>How to make a decision about choosing <strong>HOW</strong>? Seems like the main reason to change our discount policy depends on the client type.</p><pre>if order.client.is_regular:<br>    # stuff           <br>elif order.client.is_vip:<br>    # stuff<br>else:<br>    # stuff</pre><p><strong>Object-Oriented Approach</strong></p><pre># HOW<br>class DiscountPolicy(ABC):<br>    @abstractmethod<br>    def calculate(self, product: Product) -&gt; Price:<br>        pass</pre><pre>class VIPClientDiscountPolicy(DiscountPolicy):<br>    def calculate(self, product: Product) -&gt; Price:<br>        # complex logic<br>        return</pre><pre>class RegularClientDiscountPolicy(DiscountPolicy):<br>    def calculate(self, product: Product) -&gt; Price:<br>        # complex logic<br>        return<br><br><br>class NewClientDiscountPolicy(DiscountPolicy):<br>    def calculate(self, product: Product) -&gt; Price:<br>        # complex logic<br>        return<br><br><br># WHY<br>class BidderFactory:<br>    def create(self, client, *args) -&gt; Bidder:<br>        if client.is_vip:<br>            return Bidder(VIPClientDiscountPolicy())</pre><pre>        if client.is_regular:<br>            return Bidder(RegularClientDiscountPolicy())</pre><pre>        return Bidder(NewClientDiscountPolicy())<br><br><br># WHAT is stable. It shouldn&#39;t change in the feature.<br>class Bidder:<br>    def __init__(self, discount_policy: DiscountPolicy):<br>        self.discount_policy = discount_policy<br><br>    def generate_offer(self, order: Order) -&gt; Offer:<br>        offer = Offer(client)<br><br>        for product in order.get_ordered_products():<br>            offer.add_item(product, self.discount_policy.calculate(product))<br><br>        return offer</pre><p>Now our code is really close for modification and open for extension. We can easily add new <em>DiscountPolicy</em> thanks to the <a href="https://en.wikipedia.org/wiki/Strategy_pattern">strategy pattern</a> with a different, more complex implementation that answers the question of <strong>how</strong> price should be calculated.</p><p>By using a factory pattern we can easily decide <strong>why</strong> or when our logic should be different.</p><p>This leaves us with the “<strong>what?”</strong> question. Very simple <em>Bidder</em> class that exposes the behavior with meaningful names.</p><p>Notice that previously isolated building blocks can be now tested separately or could be even created by different teams. The hardest thing to come up with is a common interface, resistant to changes.</p><p>The same design can be accomplished without OOP. In this example, we have a function responsible for providing another function that calculates discounts for our clients.</p><pre>def vip_client_discount_calculator(product):<br>    return</pre><pre>def new_client_discount_calculator(product):<br>    return</pre><pre>def regular_client_discount_calculator(product):<br>    return</pre><pre>def discount_calculator_factory(client):<br>    if client.is_vip:<br>        return vip_client_discount_calculator<br>    return new_client_discount_calculator<br><br><br>def generate_offer(<br>    order: Order,<br>    discount_calculator=new_client_discount_calculator<br>) -&gt; Offer:<br>    offer = Offer(client)<br><br>    for product in order.get_ordered_products():<br>        offer.add_item(product, discount_calculator(product))<br><br>    return offer<br><br><br>generate_offer(order, discount_calculator_factory(client))</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1860fecc8ec0" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>