cd /news/developer-tools/5-design-patterns-used-in-my-new-hab… · home topics developer-tools article
[ARTICLE · art-122330] src=belderbos.dev ↗ pub= topic=developer-tools verified=true sentiment=· neutral

5 design patterns used in my new habit tracker app

Developer Daniel Roy Greenfeld built commitgraph, a Django + HTMX habit tracker app, and shared five design patterns from its development, including pure functions for streak logic, a 7-bit integer to represent weekly schedules, and use of Python's calendar module for month grids. The patterns aim to make code testable and maintainable, with examples such as a `longest_streak` function and a `shade` helper for calendar cells.

read4 min views1 publishedSep 6, 2026
5 design patterns used in my new habit tracker app
Image: Belderbos (auto-discovered)

Shipping fast with AI but don't fully trust the code? I help developers 1:1 turn AI-built apps into something they understand and own. How it works →

There are plenty of habit trackers, but I wanted to build mine with constraints, a calendar view and habit streaks. So I built commitgraph: a small Django + HTMX app. Here are five Python design and testing patterns from building it.

1. Pure functions #

Streak counting and calendar shading live in two plain modules. They take dates and return values. And work independently from Django, the database, or the user. That makes them easy to test.

from datetime import date, timedelta

def longest_streak(dates: list[date], is_due=lambda _: True) -> int:
    days = set(dates)
    if not days:
        return 0
    best = run = 0
    cur, last = min(days), max(days)
    while cur <= last:
        if is_due(cur):
            run = run + 1 if cur in days else 0
            best = max(best, run)
        cur += timedelta(days=1)
    return best

Thanks to this boundary the streak logic is easy to unit test; no database nor user are needed.

Another example: each calendar cell gets a shade from how much you completed that day. It is tempting to compute that in the template. Instead, I turned it into a helper function:

def shade(completed: int, active: int) -> str:
    if active == 0 or completed == 0:
        return "bg-[var(--g0)] text-muted"
    frac = completed / active
    if frac >= 1:
        return "bg-[#a84420] text-white"
    if frac >= 0.6:
        return "bg-[#d97a4e] text-[#3a1c0e]"
    return "bg-[#f6ddc9] text-[#3a1c0e]"

assert shade(5, 5).endswith("text-white") is again easy to test and it's reusable in different parts of the app.

2. A schedule is a 7-bit integer #

Claude suggested this nifty approach: a habit runs on a subset of weekdays. That is seven yes/no answers, which fit cleanly into a single 7-bit integer.

class Habit(models.Model):
    ALL_DAYS = 0b1111111   # every day
    WEEKDAYS = 0b0011111   # Mon-Fri (weekday() 0-4)
    due_days = models.PositiveSmallIntegerField(default=ALL_DAYS)

    def is_due_on(self, day: date) -> bool:
        return bool(self.due_days & (1 << day.weekday()))

No join table, no seven boolean columns. Adding "weekends only" is a new constant, not a migration.

The is_due_on one-liner treats due_days as a 7-bit binary calendar, one switch per weekday, ordered right-to-left from Monday (0) to Sunday (6).

day.weekday() gives 0-6 (Mon-Sun). 1 << day.weekday() puts a single bit at that day's position, and & self.due_days is non-zero only if the habit is scheduled that day. bool() turns that into True/ False.

3. Let the standard library build the month grid #

A month grid can be tricky: leading blanks, trailing blanks, weeks that straddle two months. Python's calendar module already knows all of it.

import calendar

for week in calendar.Calendar(firstweekday=0).monthdatescalendar(year, month):
    for day in week:
        if day.month != month:
            ...  # a padding cell from the previous or next month

monthdatescalendar returns real date objects, one clean list of weeks; no need to write any logic around how many days April has.

4. A query vocabulary on the model #

"Active habits" and "habits active on a given day" show up everywhere. Rather than repeating the filters in every view, I named them on a custom QuerySet so they are chainable:

class HabitQuerySet(models.QuerySet):
    def active(self):
        return self.filter(archived_at__isnull=True)

    def active_on(self, day: date):
        return self.filter(
            Q(start_date__lte=day)
            & (Q(archived_at__isnull=True) | Q(archived_at__date__gte=day))
        )

class Habit(models.Model):
    objects = HabitQuerySet.as_manager()

Now Habit.objects.filter(user=u).active() is very readable and the relatively complex Q expressions are abstracted into the model.

5. "Done and due" is set algebra #

The Today screen needs habits that are due today and not yet checked off. Two sets and one operator.

due_ids = {h.id for h in habits}
done_ids = set(
    HabitCompletion.objects
    .filter(habit__user=user, date=day)
    .values_list("habit_id", flat=True)
) & due_ids

The intersection drops any completion for a habit that is not due today, so a spurious record can't inflate the count. The logic is the math, not a nest of if statements.

Here is a REPL snippet that demonstrates how set intersection (&) filters down to only the elements present in both sets:

>>> due_ids = {10, 11, 12, 13}      # Habits scheduled for today
>>> completed_ids = {11, 13, 99}    # Logged completions (99 is a stray record)

>>> # The '&' operator keeps ONLY IDs present in BOTH sets
>>> done_today = completed_ids & due_ids
>>> print(done_today)  # 10, 12 and 99 are dropped because they are not in both sets
{11, 13}

I have also seen this used in RBAC logic to cross-check user roles with endpoint permissions. The intersection of the two sets is the effective permissions a user has.

Keep reading #

The thread running through all five patterns: when a piece of logic doesn't strictly need the database or a dependency, stick to this boundary. Fetch your primitive values, do the math in plain Python, so it's more testable in isolation.

What is one function in your Django views that would be much easier to trust and test if you decoupled it?

── more in #developer-tools 4 stories · sorted by recency
── more on @commitgraph 3 stories trending now
sponsored brought to you by zahid.host 4,200+ EU-deployed projects
reading about agents? ship yours in a single git push.

Run your AI side-project on zahid.host

EU-based hosting, git-push deploys, automatic HTTPS, no cold starts. Free tier with a custom domain — perfect for shipping the agent you just read about.

$git push zahid main
Live at https://your-agent.zahid.host
Get free account → Pricing
from €0/mo · no card required
LIVE [news/5-design-patterns-us…] indexed:0 read:4min 2026-09-06 ·