<?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 Akshathaholla on Medium]]></title>
        <description><![CDATA[Stories by Akshathaholla on Medium]]></description>
        <link>https://medium.com/@akshathaholla91?source=rss-79fc5b3ffbe1------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*w_HZX1Hd1MXzJ7M2xnxbEg.jpeg</url>
            <title>Stories by Akshathaholla on Medium</title>
            <link>https://medium.com/@akshathaholla91?source=rss-79fc5b3ffbe1------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 20 Nov 2026 21:31:35 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@akshathaholla91/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[The Entity-Attribute-Value (EAV) Pattern]]></title>
            <link>https://medium.com/@akshathaholla91/the-entity-attribute-value-eav-pattern-8bfc522403cc?source=rss-79fc5b3ffbe1------2</link>
            <guid isPermaLink="false">https://medium.com/p/8bfc522403cc</guid>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[data-modeling]]></category>
            <category><![CDATA[software-architecture]]></category>
            <dc:creator><![CDATA[Akshathaholla]]></dc:creator>
            <pubDate>Tue, 29 Sep 2026 13:32:47 GMT</pubDate>
            <atom:updated>2026-09-29T13:32:47.811Z</atom:updated>
            <content:encoded><![CDATA[<p>Lets you store an entity’s properties as rows instead of columns — so adding a new property is an insert, not a schema migration.</p><p>Relational databases want you to know your columns in advance. A products table with price, weight, color works fine — until the business sells shoes (needs size), electronics (needs voltage), and books (needs page_count), and next quarter adds a category nobody&#39;s thought of yet. Adding a column per attribute per category either produces a table with hundreds of mostly-NULL columns, or a fresh migration every time someone wants to track one more property on one more category of thing.</p><p><strong>Entity-Attribute-Value</strong> (also called EAV, or “open schema”) solves this by not modeling attributes as columns at all. Instead, each attribute a specific entity happens to have becomes its own <em>row</em>. The schema stops describing “what columns exist” and starts describing “what attribute rows are allowed to exist for entities of this kind” — which means new attributes are something you insert, not something you migrate.</p><h4>The shape</h4><p>Where a normal table has one row per entity and one column per attribute, EAV flips that: one row <em>per attribute value</em>, with the attribute’s identity as data inside the row rather than as a column name.</p><pre>Conventional table                    EAV shape<br><br>products                              entities            attributes<br>┌────┬───────┬────────┬───────┐      ┌────┬──────┐       ┌────┬─────────┬──────────┐<br>│ id │ price │ weight │ color │      │ id │ kind │       │ id │ name    │ data_type│<br>├────┼───────┼────────┼───────┤      ├────┼──────┤       ├────┼─────────┼──────────┤<br>│ 1  │ 19.99 │ NULL   │ NULL  │      │ 1  │ shoe │       │ 1  │ size    │ integer  │<br>│ 2  │ NULL  │ NULL   │ red   │      │ 2  │ shirt│       │ 2  │ color   │ string   │<br>└────┴───────┴────────┴───────┘      └────┴──────┘       └────┴─────────┴──────────┘<br> (columns fixed at migration time)                         (rows insertable anytime)<br><br>                                       values<br>                                      ┌────┬───────────┬─────────────┬───────┐<br>                                      │ id │ entity_id │ attribute_id│ value │<br>                                      ├────┼───────────┼─────────────┼───────┤<br>                                      │ 1  │ 1         │ 1           │ &quot;10&quot;  │<br>                                      │ 2  │ 2         │ 2           │ &quot;red&quot; │<br>                                      └────┴───────────┴─────────────┴───────┘</pre><p>Three tables carry the weight a conventional schema would have spread across dozens of category-specific columns:</p><ul><li><strong>entities</strong> — the thing itself (a product, a reference-data entry, a patient record).</li><li><strong>attributes</strong> — the <em>definition</em> of a property: its name, and usually its data type and validation rules.</li><li><strong>values</strong> — one row per (entity, attribute) pair, holding the actual value.</li></ul><p>Adding “voltage” as a trackable property for electronics is one INSERT into attributes — no ALTER TABLE, no downtime, no migration to review.</p><p>Lets look at the example:</p><pre>CREATE TABLE attributes (<br>    id          INT PRIMARY KEY,<br>    name        VARCHAR(50),<br>    data_type   VARCHAR(20)   -- &#39;string&#39;, &#39;integer&#39;, &#39;boolean&#39;, ...<br>);<br><br>CREATE TABLE entity_values (<br>    entity_id     INT,<br>    attribute_id  INT REFERENCES attributes(id),<br>    value         VARCHAR(255),   -- always stored as text<br>    PRIMARY KEY (entity_id, attribute_id)<br>);<br><br>INSERT INTO attributes VALUES<br>    (1, &#39;size&#39;,  &#39;integer&#39;),<br>    (2, &#39;color&#39;, &#39;string&#39;);<br><br>INSERT INTO entity_values VALUES<br>    (101, 1, &#39;10&#39;),<br>    (101, 2, &#39;red&#39;),<br>    (102, 2, &#39;blue&#39;);</pre><p>Reading “everything about entity 101” means a query, not a fixed set of columns:</p><pre>SELECT a.name, v.value<br>FROM entity_values v<br>JOIN attributes a ON a.id = v.attribute_id<br>WHERE v.entity_id = 101;<br><br>-- name  | value<br>-- ------+------<br>-- size  | 10<br>-- color | red</pre><p>In application code, this normally gets wrapped so callers don’t touch the raw rows directly:</p><pre>class Attribute:<br>    def __init__(self, id, name, data_type):<br>        self.id = id<br>        self.name = name<br>        self.data_type = data_type<br><br>class Entity:<br>    def __init__(self, id):<br>        self.id = id<br>        self.values = {}   # attribute_id -&gt; raw string value<br><br>    def set(self, attribute: Attribute, raw_value: str):<br>        self.values[attribute.id] = raw_value<br><br>    def get(self, attribute: Attribute):<br>        raw = self.values.get(attribute.id)<br>        if raw is None:<br>            return None<br>        return {<br>            &quot;integer&quot;: int,<br>            &quot;boolean&quot;: lambda v: v == &quot;true&quot;,<br>            &quot;string&quot;:  str,<br>        }[attribute.data_type](raw)<br><br>size  = Attribute(1, &quot;size&quot;, &quot;integer&quot;)<br>color = Attribute(2, &quot;color&quot;, &quot;string&quot;)<br><br>shoe = Entity(101)<br>shoe.set(size, &quot;10&quot;)<br>shoe.set(color, &quot;red&quot;)<br><br>print(shoe.get(size))    # 10 (an actual int, not &quot;10&quot;)</pre><p>Note the last piece: everything is stored as value: VARCHAR, and the <em>attribute&#39;s</em> declared data_type is what tells the application how to interpret and validate it on the way out. The database never natively type-checks a value — that responsibility moves into application code, which is the central tradeoff of the whole pattern.</p><h4>When to use it</h4><ul><li><strong>The set of attributes is genuinely unbounded or user-defined</strong> — a form builder, a product catalog spanning wildly different categories, medical records where every specialty tracks different observations.</li><li><strong>New attributes need to appear without a deployment</strong> — a business user adding a field through an admin screen, not a developer shipping a migration.</li><li><strong>Most entities only populate a handful of attributes out of a much larger possible set</strong>, so a sparse row-per-value model beats a wide table full of NULLs.</li></ul><p>The tradeoff here is that every “what’s the value of X” question becomes a join and a lookup instead of a column access, the database can no longer enforce a value’s type or NOT NULL constraint for you, and a simple WHERE color = &#39;red&#39; query becomes a join against the values table instead of a plain column filter. For a fixed, well-known set of attributes, a normal table with real columns is still simpler, faster, and lets the database do more of the correctness work for you. EAV pays off exactly at the point where &quot;add a new attribute&quot; needs to stop being a schema change.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8bfc522403cc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Type Object Pattern]]></title>
            <link>https://medium.com/@akshathaholla91/the-type-object-pattern-14d25dd5bfe9?source=rss-79fc5b3ffbe1------2</link>
            <guid isPermaLink="false">https://medium.com/p/14d25dd5bfe9</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[objectorientedprogramming]]></category>
            <category><![CDATA[software-architecture]]></category>
            <dc:creator><![CDATA[Akshathaholla]]></dc:creator>
            <pubDate>Tue, 29 Sep 2026 13:07:25 GMT</pubDate>
            <atom:updated>2026-09-29T13:07:25.987Z</atom:updated>
            <content:encoded><![CDATA[<p>Helps you create new categories of an entity as data at runtime — instead of writing a new subclass for each one.</p><p>Sometimes a system needs many <em>kinds</em> of something — many species of monster in a game, many categories of product in a catalog, many grades of a material — and that list of kinds isn’t fixed at compile time. New kinds get added constantly, usually by a non-programmer (a game designer, a business analyst, a data admin), and nobody wants to wait for a code deploy and a new subclass every time someone invents a new monster or adds a new product category.</p><p>The naive OOP instinct is inheritance: a Dragon class, a Goblin class, a Troll class, each extending a Monster base class. That works until kind #40 shows up and someone realizes half the &quot;kinds&quot; only differ by a couple of numbers — health, attack power, name — not by behavior. At that point you&#39;re writing a new class purely to hold different data, which is a sign the class hierarchy is doing a data problem&#39;s job.</p><p><strong>Type Object</strong> (documented by Bobby Woolf, and later by Robert Nystrom in <em>Game Programming Patterns</em>) solves this by taking the “kind” out of the class hierarchy entirely and turning it into an object you can create at runtime, just like any other piece of data.</p><h4>The shape</h4><p>Instead of one class per kind, you use exactly two classes, related to each other instead of nested in an inheritance tree:</p><pre>     MonsterType                    Monster<br>  ┌──────────────┐              ┌──────────────┐<br>  │ name          │◄── type ────│ type          │<br>  │ health        │             │ currentHealth │<br>  │ attack        │             │ position      │<br>  └──────────────┘              └──────────────┘<br>        ▲                              <br>        │ instances                     <br>   &quot;Dragon&quot;, &quot;Goblin&quot;, &quot;Troll&quot; — created at runtime, not compiled in</pre><ul><li><strong>The instance class</strong> (Monster) holds the state that varies <em>per individual</em> — this dragon&#39;s current health, its position on the map.</li><li><strong>The type object</strong> (MonsterType) holds the state that&#39;s shared by every individual <em>of that kind</em> — a dragon&#39;s base health, its attack value, its name.</li><li>Every instance holds a <strong>reference</strong> to its type object instead of inheriting from a type-specific subclass.</li></ul><p>Adding “Griffin” as a new kind of monster is no longer “write a new class” — it’s “construct a new MonsterType object and hand it a name, health, and attack value.&quot; That can happen from a config file, a database row, or a level editor, with zero recompilation.</p><p>Let’s look at the example</p><pre>class MonsterType <br>{<br>    private final String name;<br>    private final int baseHealth;<br>    private final int attack;<br><br>    MonsterType(String name, int baseHealth, int attack) <br>    {<br>        this.name = name;<br>        this.baseHealth = baseHealth;<br>        this.attack = attack;<br>    }<br><br>    int getBaseHealth() { return baseHealth; }<br>    int getAttack()     { return attack; }<br>    String getName()    { return name; }<br>}<br><br>class Monster <br>{<br>    private final MonsterType type;<br>    private int currentHealth;<br><br>    Monster(MonsterType type) <br>    {<br>        this.type = type;<br>        this.currentHealth = type.getBaseHealth();  // starts at the type&#39;s baseline<br>    }<br><br>    void takeDamage(int amount) {<br>        currentHealth -= amount;<br>    }<br><br>    int attackPower() {<br>        return type.getAttack();   // delegated to the type object, not hardcoded per class<br>    }<br><br>    boolean isAlive() {<br>        return currentHealth &gt; 0;<br>    }<br>}</pre><p>Defining kinds and spawning instances, entirely at runtime:</p><pre>MonsterType dragonType = new MonsterType(&quot;Dragon&quot;, 300, 45);<br>MonsterType goblinType = new MonsterType(&quot;Goblin&quot;, 20, 5);<br><br>Monster dragon1 = new Monster(dragonType);<br>Monster goblin1 = new Monster(goblinType);<br>Monster goblin2 = new Monster(goblinType);   // same type, independent instance state<br><br>goblin1.takeDamage(15);<br>System.out.println(goblin1.isAlive());        // true — 5 HP left<br>System.out.println(dragon1.attackPower());    // 45 — read straight from its type</pre><p>Notice goblin1 and goblin2 share the exact same MonsterType object but track completely independent currentHealth. And a game designer adding a &quot;Griffin&quot; needs nothing more than:</p><pre>MonsterType griffinType = new MonsterType(&quot;Griffin&quot;, 90, 22);</pre><p>No new class, no recompile, no deploy.</p><h4>A common refinement: type inheritance</h4><p>A plain Type Object gets repetitive fast if related kinds share most of their stats — an “Elite Goblin” that’s just a Goblin with higher stats. Rather than duplicating every field, type objects can themselves form a small hierarchy, where a type looks up a value on its parent type if it doesn&#39;t define one:</p><pre>class MonsterType <br>{<br>    private final MonsterType parent;   // may be null<br>    private final Integer attack;       // null means &quot;inherit from parent&quot;<br><br>    Integer getAttack() <br>    {<br>        if (attack != null) return attack;<br>        return parent != null ? parent.getAttack() : null;<br>    }<br>}</pre><p>This gives you the <em>reuse</em> benefit people originally reached for class inheritance to get, without needing a compiled class per kind — the “inheritance” now lives in the data, between type objects, not in the language’s class hierarchy.</p><h4>When to use it</h4><ul><li><strong>The list of kinds grows over time</strong>, and the people adding new kinds aren’t necessarily writing code.</li><li><strong>Kinds mostly differ by data, not behavior</strong> — if every kind needs genuinely different logic (not just different numbers), a real subclass is often still the right tool.</li><li><strong>You want kinds to be data</strong> — storable in a database, editable in a UI, loadable from a config file — rather than baked into the binary.</li></ul><p>The tradeoff is indirection: every read of a shared property goes through instance.type.getX() instead of a direct field access, and the compiler can no longer help you catch a typo&#39;d kind name the way it would catch a misspelled class name. For a system with a handful of fixed, behaviorally-distinct kinds, plain inheritance or a simple enum is still simpler. Type Object pays off exactly at the point where &quot;add a new kind&quot; needs to stop being a code change.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=14d25dd5bfe9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Stacked Pull Requests]]></title>
            <link>https://medium.com/@akshathaholla91/stacked-pull-requests-94a85af3fa94?source=rss-79fc5b3ffbe1------2</link>
            <guid isPermaLink="false">https://medium.com/p/94a85af3fa94</guid>
            <category><![CDATA[git-workflow]]></category>
            <category><![CDATA[git]]></category>
            <category><![CDATA[github]]></category>
            <dc:creator><![CDATA[Akshathaholla]]></dc:creator>
            <pubDate>Mon, 28 Sep 2026 13:14:06 GMT</pubDate>
            <atom:updated>2026-09-28T13:14:06.006Z</atom:updated>
            <content:encoded><![CDATA[<p><em>A way of shipping one large change as a sequence of small, dependent reviews</em></p><h4>The one big PR problem</h4><p>Most teams ship features on a single long-lived branch: work for a few days, open one pull request, and wait. The PR grows to forty files before anyone sees it. Reviewers skim instead of read. Feedback lands three days later, main has moved on underneath you, and now there’s a rebase to do before anyone can even discuss the comments. Nothing about this is anyone’s fault — it’s just what happens when a whole feature is reviewed as one object.</p><p>Stacked PRs are a different unit of review. Instead of one branch and one PR, the change is split into an ordered sequence of small branches, each one built directly on top of the last. Each PR shows only what it adds. Reviewers read a diff in minutes instead of an afternoon, and — because the pieces are ordered, not just small — the reviewer always has exactly the context the change needs and nothing more.</p><h4>What actually makes it a stack</h4><p>Each branch in a stack has the branch below it as its base — not main. PR #402 is opened against PR #401, not against main; PR #403 is opened against #402, and so on. Because the base is the previous branch rather than main, the platform can compute each PR&#39;s diff against only its immediate parent — so what a reviewer sees is genuinely just that layer&#39;s contribution, even though every branch also contains everything below it.</p><p>Example, a token-rotation feature split four ways:</p><pre>main<br> └─ #401  auth: add token refresh<br>     └─ #402  auth: rotate refresh tokens<br>         └─ #403  api: use rotated tokens<br>             └─ #404  ui: show token expiry banner</pre><p>You don’t have to wait for #401 to merge before starting #402 — you branch off your own unmerged work and keep going. That’s the part that actually saves time: review and the next unit of work happen in parallel instead of in sequence.</p><h4>The daily loop: restacking</h4><p>The cost of that parallelism shows up the moment review feedback lands on a lower PR. Fix something in #401, and its commit history changes — which means #402, #403, and #404 are all now based on a version of #401 that no longer exists. Every branch above the edit has to be rebased onto the new version of the one below it. This is called <strong>restacking</strong>, and in a stack of any real depth it happens constantly — every round of review comments on any layer triggers it for every layer above.</p><p>Done by hand, that’s checking out each branch in order, rebasing, resolving whatever conflicts fall out, and force-pushing — four times, for a four-deep stack, for one round of feedback on the bottom layer. Git 2.38 added rebase --update-refs specifically for this: it moves every branch pointer in the stack together during a single rebase, rather than one at a time. Dedicated stacking tools go further and turn the whole sequence into one command.</p><h4>Merging bottom-up</h4><p>A stack always merges in the order it was built. Once #401 is approved and merged into main, #402’s base moves to main — it’s now the new bottom of the stack, carrying only its own diff. Repeat for each layer as approvals land. A merge queue that understands stacks will do this automatically: merge a layer, retarget everything above it, re-run checks, and merge the next one the moment it’s green — so the stack stays in sync without anyone manually walking it.</p><h4>Who’s built for it</h4><p>Git itself — rebase — update-refs moves a whole stack in one rebase. No visualization, no PR bookkeeping — you still track the order yourself.</p><p>GitHub base-branch chains — Point each PR’s base at the PR below it. GitHub shows only the incremental diff and retargets the base once the lower PR merges.</p><p>Graphite — CLI and web layer built around the stack as the unit of work — create, submit, restack, and merge an entire stack with single commands, with a visual map of the whole thing.</p><p>Sapling — Meta’s source-control client, stack-first from the ground up — commands operate on the stack directly rather than on named branches.</p><p>git-branchless — Adds a commit-based “smartlog” and safe, undo-able rebase tooling on top of plain Git, for stacking without a hosted service.</p><p>spr — Lean CLI that maps a linear stack of local commits to one GitHub PR per commit, updating each one on every push.</p><p>Phabricator / Differential — Where “stacked diffs” started, inside Meta, before Git-native tooling existed. Still the reference point people cite.</p><h4>What you get</h4><ul><li>Each PR is small enough that someone can actually review it carefully</li><li>Review and the next unit of work happen at the same time, not in sequence</li><li>Smaller changes mean bugs are easier to catch before they slip through</li><li>Git history that reads as a deliberate sequence, not one squashed blob</li></ul><h4>What it costs</h4><ul><li>Restacking discipline isn’t optional — skip it and branches quietly drift apart</li><li>A reviewer who only sees one small piece might miss the bigger picture</li><li>Good tooling isn’t everywhere — many teams still have to manage this by hand</li><li>Everyone on the team needs to be comfortable with force-pushing safely</li></ul><h4>When to use it</h4><p>Stacking is worth the extra effort when you’re working on something that takes several days, or when the work naturally happens in steps — where step two only makes sense after step one is done. In those cases, you can already see how to split the work before you even start.</p><p>It’s not worth it for a quick one-line fix, for throwaway experiments you don’t plan to keep, or for a team that isn’t comfortable with git and doesn’t have tools to manage the stack. In those cases, the extra coordination work outweighs the benefit of smaller reviews.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=94a85af3fa94" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Scoped Values in JDK 25 — A Better Way to Share Data Across Threads]]></title>
            <link>https://medium.com/@akshathaholla91/scoped-values-in-jdk-25-a-better-way-to-share-data-across-threads-0074f41e8ce3?source=rss-79fc5b3ffbe1------2</link>
            <guid isPermaLink="false">https://medium.com/p/0074f41e8ce3</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[scoped-values]]></category>
            <category><![CDATA[java-memory-management]]></category>
            <category><![CDATA[jdk-25]]></category>
            <category><![CDATA[threadlocal]]></category>
            <dc:creator><![CDATA[Akshathaholla]]></dc:creator>
            <pubDate>Thu, 30 Jul 2026 15:32:43 GMT</pubDate>
            <atom:updated>2026-07-30T15:32:43.160Z</atom:updated>
            <content:encoded><![CDATA[<p>JDK 25 finalizes Scoped Values (JEP 506), a feature that has been previewed and refined across five consecutive JDK releases — from incubation in JDK 20 all the way through four preview rounds. The result is a clean, memory-efficient replacement for one of Java’s oldest and most problematic mechanisms: ThreadLocal.</p><h4>The Problem Scoped Values Solve</h4><p>Passing data down the call stack is harder than it looks</p><p>In a well-structured Java program, methods communicate through parameters. Method A calls method B, passing what B needs. B calls C, passing what C needs. This works well most of the time — until a deeply nested method needs access to data that originated several frames up the stack, in code that has no logical reason to know about the internal details of whatever is below it.</p><p>The classic example is a web framework. The framework creates a FrameworkContext — containing authentication details, transaction IDs, and database connections — at the top of a request-handling thread, then hands control to user application code. Later, when user code calls back into the framework to read from the database, the framework needs that same context again.</p><p>Passing FrameworkContext explicitly as a parameter through every user method is impractical: it pollutes APIs, forces application developers to carry framework internals they don’t understand or care about and breaks every time the framework adds a new internal field.</p><h4>ThreadLocal: the traditional workaround</h4><p>Java’s answer since version 1.2 has been ThreadLocal. A thread-local variable holds a separate value per thread. The framework writes the context at the top of the call:</p><pre>private static final ThreadLocal&lt;FrameworkContext&gt; CONTEXT = new ThreadLocal&lt;&gt;();<br><br>  void serve(Request request, Response response) {<br>      CONTEXT.set(createContext(request));   // store at top<br>      Application.handle(request, response);<br>  }<br><br>  public PersistedObject readKey(String key) {<br>      var context = CONTEXT.get();           // retrieve deep in stack<br>      return getDBConnection(context).readKey(key);<br>  }</pre><p>This works, but ThreadLocal carries three fundamental design flaws that have become increasingly painful as Java has evolved:</p><p>1. <strong>Unconstrained mutability -</strong> Any code that can call get() can also call set(). There is no enforcement of the intended one-way, top-down flow of data. Deep callees can silently overwrite a value that other parts of the code expect to be stable.</p><p>2. <strong>Unbounded lifetime -</strong> A thread-local value persists for the entire lifetime of the thread unless someone explicitly calls remove(). In thread pools — the dominant execution model for server applications — a value written for one request can silently leak into a completely unrelated request running on the same pooled thread later. This is a source of both security vulnerabilities and hard-to-diagnose bugs.</p><p>3. <strong>Expensive inheritance -</strong> When a child thread is created from a parent that uses InheritableThreadLocal, the child receives its own copy of every thread-local value the parent has set. With virtual threads — where a single<br> application might sustain hundreds of thousands or millions of concurrent threads — that copying overhead becomes a serious memory problem.</p><h4>Enter Scoped Values</h4><p>A ScopedValue&lt;V&gt; is a container that binds a value to the current thread for a precisely bounded period: the duration of a single run() or call() invocation. Outside that period, the value does not exist. Inside it, any method on the call stack — no matter how deeply nested — can read it. Nobody can change it.</p><pre>private static final ScopedValue&lt;FrameworkContext&gt; CONTEXT = ScopedValue.newInstance();<br><br>  void serve(Request request, Response response) {<br>      ScopedValue.where(CONTEXT, createContext(request))<br>                 .run(() -&gt; Application.handle(request, response));<br>      // CONTEXT is unbound here — get() would throw<br>  }<br><br>  public PersistedObject readKey(String key) {<br>      var context = CONTEXT.get();  // always safe inside run()<br>      return getDBConnection(context).readKey(key);<br>  }</pre><p>The scoped value is declared once as a static final field. The value is bound at the entry point with where(…).run(…). The binding is automatically destroyed when run() returns. There is no set() method. There is no<br> remove() to forget.</p><h4>What “Scoped” Actually Means</h4><p>The word “scoped” here refers to dynamic scope, not the lexical scope Java programmers are familiar with.</p><p>Lexical scope is about program text: a variable declared inside { } is accessible within those braces and nowhere else, something you can verify by reading the source without running it.</p><p>Dynamic scope is about runtime execution. When method a calls b which calls c, the scoped value binding established in a is visible throughout the entire chain — b and c and anything they call — because those methods execute within the dynamic scope of a’s run() call. The binding’s lifetime is visually obvious from the structure of the code. This is what the JEP authors mean by comprehensibility: the lifetime of shared data is apparent from reading the source.</p><h4>Rebinding: Nested Scopes</h4><p>Scoped values are immutable within a given scope — but a callee can establish a nested scope with a different binding for its own callees, without affecting what the caller sees:</p><pre>private static final ScopedValue&lt;String&gt; X = ScopedValue.newInstance();<br><br>void foo() {<br>    ScopedValue.where(X, &quot;hello&quot;).run(() -&gt; bar());<br>}<br><br>void bar() {<br>    System.out.println(X.get()); // hello<br>    ScopedValue.where(X, &quot;goodbye&quot;).run(() -&gt; baz());<br>    System.out.println(X.get()); // hello again - nested binding is gone<br>}<br><br>void baz() {<br>    System.out.println(X.get()); // goodbye<br>}</pre><p>bar() cannot change the value of X as seen by itself, but it can present a different value to baz(). Once baz() returns and the nested run() exits, bar() sees “hello” again. This nesting is safe, predictable, and automatic.</p><p>This property makes scoped values well suited to use cases like:</p><ol><li>Re-entrancy detection — bind a flag before entering a non-re-entrant section; check isBound() deeper in the stack.</li><li>Nested transactions — rebind a transaction object to represent flattened or nested transaction semantics.</li><li>Graphics contexts — propagate a drawing context through a rendering tree, with subtrees able to rebind it for their local coordinate system.</li></ol><h4>Inheritance Across Virtual Threads — Without Copying</h4><p>The memory efficiency story of scoped values becomes most compelling when combined with Virtual Threads (JEP 444) and Structured Concurrency (JEP 505).</p><p>Suppose application code handling a request needs to fetch user information and product offers concurrently, each in its own virtual thread:</p><pre> @Override<br>  public Response handle(Request request, Response response) {<br>      try (var scope = new StructuredTaskScope.ShutdownOnFailure()) {<br>          Supplier&lt;UserInfo&gt;    user   = scope.fork(() -&gt; readUserInfo());  // child thread 1<br>          Supplier&lt;List&lt;Offer&gt;&gt; offers = scope.fork(() -&gt; fetchOffers());   // child thread 2<br>          scope.join().throwIfFailed();<br>          return new Response(user.get(), offers.get());<br>      }<br>  }</pre><p>Both readUserInfo() and fetchOffers() eventually call Framework.readKey(), which reads CONTEXT. Those methods are<br> running in child threads, not the request-handling thread where CONTEXT was bound. Yet the binding is automatically visible to them — because StructuredTaskScope.fork() inherits scoped values from the parent thread.</p><p>Critically, inheritance here means sharing, not copying. The child threads do not receive their own private copies of the binding. They read the same immutable value from the parent’s scope. There is no per-child-thread allocation for each inherited scoped value.</p><p>This is the direct contrast with InheritableThreadLocal, which copies every inherited value into each child thread. With a million virtual threads, ThreadLocal inheritance multiplies memory usage by a million. Scoped value inheritance does not.</p><p>The structured concurrency model also guarantees that child threads terminate before run() returns, so the binding’s lifetime remains bounded even when it spans multiple threads.</p><p>The binding outlives the thread that created it — but never outlives the run() call. Memory safety is preserved.</p><h4>Memory and Performance</h4><p>The JEP is explicit about performance: reading a scoped value with get() is often as fast as reading a local variable, regardless of how many stack frames separate the reader from the binder. This is because the JVM implements scoped values using a thread-local cache rather than a stack walk — binding a value writes it to a small per-thread structure; reading it checks the cache first.</p><p>ThreadLocal.get(), by contrast, requires a hash table lookup keyed by the ThreadLocal object. The performance gap becomes especially pronounced in deeply nested call chains.</p><h4>When to Migrate — and When Not To</h4><p>Scoped values are not a universal replacement for ThreadLocal. The JEP is clear about where migration makes sense and where it does not.</p><p>Good candidates for migration:</p><ol><li>Hidden method parameters — data that flows one-way from a top-level entry point to callees.</li><li>Request-scoped or transaction-scoped context in web frameworks.</li><li>Re-entrancy guards and recursion depth counters.</li><li>Any case where the current ThreadLocal usage follows a write-once, read-many pattern.</li></ol><p>Stay with ThreadLocal when:</p><ol><li>A callee legitimately needs to write a value back up to a caller — two-way communication is not what scoped values are designed for.</li><li>You are caching expensive-to-create, mutable per-thread objects for reuse across many unrelated tasks (e.g., legacy SimpleDateFormat caching). Scoped values are released at scope exit; they are not a persistent cache.</li></ol><h4>Summary</h4><p>Scoped Values are the right answer to a problem Java developers have worked around imperfectly for over two decades. ThreadLocal was a pragmatic tool for its era — single-threaded request handlers, small thread pools, modest concurrency. In the era of virtual threads and structured concurrency, its costs are too high and its guarantees too weak.</p><p>Scoped Values offer everything ThreadLocal provided for the common one-way-sharing use case, and drop everything that made it dangerous: mutability, unbounded lifetime, and expensive per-thread copying. The result is code that is easier to reason about, cheaper to run, and far safer in high-concurrency environments where virtual threads number in the millions.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0074f41e8ce3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Party Role Archetype in System Design]]></title>
            <link>https://medium.com/@akshathaholla91/party-role-archetype-in-system-design-0cc5d3bddc4e?source=rss-79fc5b3ffbe1------2</link>
            <guid isPermaLink="false">https://medium.com/p/0cc5d3bddc4e</guid>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[system-architecture]]></category>
            <category><![CDATA[design-systems]]></category>
            <category><![CDATA[software-design-patterns]]></category>
            <category><![CDATA[data-modelling]]></category>
            <dc:creator><![CDATA[Akshathaholla]]></dc:creator>
            <pubDate>Sun, 26 Jul 2026 17:34:05 GMT</pubDate>
            <atom:updated>2026-07-26T17:34:05.211Z</atom:updated>
            <content:encoded><![CDATA[<p>The Party Role pattern is a data modeling archetype used in enterprise system design to represent entities (people or organizations) that can play multiple, evolving roles within a system — without duplicating their core data for each role.</p><p>It typically consists of three core concepts:</p><h4>Party</h4><p>A Party represents the <em>core, enduring identity</em> of an entity capable of participating in the system — independent of anything it does, plays, or connects to. It is the stable anchor beneath all roles and relationships, not a role or connection itself.</p><p>Key conceptual properties of a party:</p><ul><li>Identity-only, not functional — a party captures <em>who or what</em> something is (its intrinsic, identifying attributes), not what it does. What it does is layered on separately as roles.</li><li>Generalized across types — a party can be an individual or a collective (e.g., a group, organization, or system), unified under one concept so the rest of the model doesn’t need to distinguish between them when handling roles or relationships.</li><li>Persistent across time — a party’s identity doesn’t start or end when a role or relationship does; it exists continuously, while roles and relationships attached to it can come and go.</li><li>Role-agnostic — a party can exist with zero, one, or many roles simultaneously; holding no role at all doesn’t make it any less a party.</li><li>The shared reference point — every role belongs to exactly one party, and every relationship ultimately traces back to the parties involved — making the party the common anchor that lets roles and relationships be added, removed, or reorganized without disturbing the underlying identity.</li></ul><h4>Role</h4><p>A Role represents a <em>context-specific capacity</em> that a party takes on — it’s not what the party <em>is</em>, but what it’s <em>doing</em> at a given time in a given context. The same underlying entity remains one continuous identity, while its roles are separate, layered classifications on top of that identity.</p><p>Key conceptual properties of a role:</p><ul><li>Not intrinsic, but assumed — a role isn’t a permanent trait of the entity; it’s something taken on and potentially dropped later. The entity itself doesn’t change when a role starts or ends.</li><li>Non-exclusive — an entity can hold several roles at once. Taking on one role doesn’t require giving up another.</li><li>Time-bound — a role has a beginning and, often, an end. The same entity can occupy a given role, stop, and later re-occupy it, with each occurrence tracked separately.</li><li>Carries its own context — attributes, permissions, or obligations that make sense only for a particular role (and would be meaningless for the entity in general) attach to the role, not to the entity’s core identity.</li><li>Independently governed — rules about who can hold a role, what a role permits, or how a role can change are defined separately from the entity’s core definition, so new roles can be introduced without altering what the entity fundamentally is.</li></ul><h4>Party Relationship</h4><p>A Relationship represents a <em>connection between two entities</em>, defined by the nature of how they relate to one another. It exists separately from either entity and only makes sense as something shared between the two.</p><p>Key conceptual properties of a relationship:</p><ul><li>Binds two participants — a relationship always involves two sides, and the way each side participates may differ (one side might initiate, the other receive; or both may participate symmetrically).</li><li>Typed by nature — relationships have a category describing what kind of connection they represent, which determines what behavior or expectations apply.</li><li>Contextual, not absolute — the same two entities can be connected by more than one relationship simultaneously, each independent of the others, since a relationship reflects one <em>aspect</em> of how they interact rather than the totality of their connection.</li><li>Directional or mutual — some relationships treat both sides equally, while others distinguish a clear “from” and “to” side with different meaning on each end.</li><li>Time-bound — like roles, relationships can begin and end, and a past relationship is meaningful to retain rather than erase.</li><li>More meaningful when tied to capacity, not identity alone — a relationship is usually really about how two entities relate <em>given what each is doing at the time</em>, rather than a connection between their bare identities. This is why relationships are often understood as connecting the <em>roles</em> two entities are playing, not the entities themselves.</li></ul><p>The Party Role pattern models an entity’s core identity separately from what it <em>does</em>: a Role is a temporary, non-exclusive capacity an entity takes on (like a hat it wears), while a Relationship is a connection between two entities, typically meaningful only in terms of the specific roles they’re each playing at the time. Together, they let one identity hold many roles at once, and let those roles link to each other in flexible, time-bound ways, without hardcoding fixed categories into the entity itself.</p><h3>Advantages</h3><ol><li>Eliminates data duplication — A single party’s identity data (name, contact, address) is stored once, regardless of how many roles it plays.</li><li>Handles multi-role entities naturally — The same person can be a Customer <em>and</em> an Employee <em>and</em> a Shareholder without schema conflicts or duplicate records.</li><li>Extensible without schema changes — Adding a new role type (e.g., “Supplier”) doesn’t require altering the core Party table — just adding a new role type/record.</li><li>Supports role lifecycle — Roles can be added, removed, or time-bounded (e.g., “Employee from 2020–2023”) independent of the underlying party record.</li><li>Enables unified reporting — Queries like “all parties we’ve ever interacted with” become simple, since everything anchors to one Party table.</li><li>Models real-world relationships cleanly — Party-to-party relationships (e.g., Company ↔ Employee, Parent ↔ Subsidiary) are modeled explicitly and consistently.</li></ol><h3>Disadvantages</h3><ol><li>Increased schema complexity — Even simple queries (e.g., “get all customers”) require joining Party, PartyRole, and RoleType tables instead of hitting one flat table.</li><li>Harder to enforce role-specific constraints — Database-level constraints (NOT NULL, foreign keys specific to a role) are harder to apply generically across a shared structure.</li><li>Performance overhead — Multiple joins and generalized tables can be slower than denormalized, role-specific tables, especially at scale.</li><li>Steeper learning curve — Developers unfamiliar with the pattern often find the abstraction unintuitive compared to straightforward Customer/Employee tables.</li><li>Risk of over-generalization — Excessive abstraction can produce an anemic model where business meaning is buried under generic Party/Role/Relationship tables, making the schema hard to read at a glance.</li><li>Application logic burden — Business rules that would be a simple column constraint in a specific table now often must be enforced in application code instead of the database.</li></ol><h3>When to Use It</h3><p>This pattern earns its complexity when entities genuinely play multiple, overlapping, or evolving roles (common in CRM, insurance, healthcare, or B2B platforms). For simpler domains where each entity has one fixed role for its lifetime, a straightforward, denormalized table per entity type is usually simpler and faster to work with.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0cc5d3bddc4e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Strategy Factory Pattern Implementation for scheduling strategies]]></title>
            <link>https://medium.com/@akshathaholla91/strategy-factory-pattern-implementation-for-scheduling-strategies-4a22f10a8405?source=rss-79fc5b3ffbe1------2</link>
            <guid isPermaLink="false">https://medium.com/p/4a22f10a8405</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[design-pattern-in-java]]></category>
            <category><![CDATA[scheduling]]></category>
            <category><![CDATA[strategy-pattern]]></category>
            <category><![CDATA[factory-pattern]]></category>
            <dc:creator><![CDATA[Akshathaholla]]></dc:creator>
            <pubDate>Sat, 29 Mar 2025 18:09:50 GMT</pubDate>
            <atom:updated>2025-03-29T18:09:50.260Z</atom:updated>
            <content:encoded><![CDATA[<p>Design patterns are standard solutions to frequent problems in software design. They serve as pre-defined templates that you can adapt to address recurring design issues in your code.</p><p>Unlike off-the-shelf functions or libraries that you can directly integrate into your program, a design pattern is a broad concept for resolving a particular problem. You can use the pattern’s guidelines to develop a solution tailored to the specific needs of your program.</p><p>Design patterns are often mistaken for algorithms, as both provide typical solutions to known problems. However, while an algorithm specifies a precise sequence of actions to achieve a goal, a design pattern offers a more abstract description of a solution. The implementation of the same pattern can vary significantly between different programs. A useful analogy is that an algorithm is like a cooking recipe, with clear steps to reach a goal. In contrast, a design pattern is akin to a blueprint: it outlines the desired outcome and its features, but the exact steps to achieve it are left to the implementer.</p><p>Let’s look at the basics of Strategy and Factory patterns and implement a combination of the two for scheduling strategies.</p><h3>Factory Pattern</h3><p>The Factory Pattern is a creational design pattern that provides an interface for creating objects in a superclass, but allows subclasses to alter the type of objects that will be created. This pattern is particularly useful when the exact type of object to be created isn’t known until runtime. The Factory pattern suggests that you replace direct object construction calls with calls to a factory method. Objects returned by these factory methods are called Product. Let’s take the example of scheduling strategies and try to use factory pattern for its implementation.</p><p>As the first step we will implement the product interface and the concrete products which have the round robin and priority scheduling strategy scheduler implementations.</p><pre>// Product Interface<br>interface Scheduler {<br>    void schedule(List&lt;Integer&gt; tasks);<br>}<br><br>// Concrete Products<br>class RoundRobinScheduler implements Scheduler {<br>    public void schedule(List&lt;Integer&gt; tasks) {<br>        // Simplified for demonstration<br>        System.out.println(&quot;Scheduling tasks using Round Robin: &quot; + tasks);<br>    }<br>}<br><br>class PriorityScheduler implements Scheduler {<br>    public void schedule(List&lt;Integer&gt; tasks) {<br>        // Simplified for demonstration<br>        Collections.sort(tasks);<br>        System.out.println(&quot;Scheduling tasks using Priority: &quot; + tasks);<br>    }<br>}</pre><p>Next, we implement the Factory interface and concrete factories for each of the scheduling strategy products.</p><pre>// Factory Interface<br>abstract class SchedulerFactory {<br>    public abstract Scheduler createScheduler();<br>}<br><br>// Concrete Factories<br>class RoundRobinSchedulerFactory extends SchedulerFactory {<br>    public Scheduler createScheduler() {<br>        return new RoundRobinScheduler();<br>    }<br>}<br><br>class PrioritySchedulerFactory extends SchedulerFactory {<br>    public Scheduler createScheduler() {<br>        return new PriorityScheduler();<br>    }<br>}</pre><p>Using the above interfaces and classes we can write the various scheduler factories as shown below.</p><pre>public class Main {<br>    public static void main(String[] args) {<br>        List&lt;Integer&gt; tasks = Arrays.asList(3, 1, 2, 4);<br><br>        SchedulerFactory factory = new RoundRobinSchedulerFactory();<br>        Scheduler scheduler = factory.createScheduler();<br>        scheduler.schedule(tasks);<br><br>        factory = new PrioritySchedulerFactory();<br>        scheduler = factory.createScheduler();<br>        scheduler.schedule(tasks);<br>    }<br>}</pre><h3>Strategy Pattern</h3><p>The Strategy Pattern is a behavioral design pattern that defines a family of algorithms, encapsulates each one, and makes them interchangeable. The strategy pattern lets the algorithm vary independently from clients that use it.</p><p>The Strategy pattern involves taking a class that performs a specific task in various ways and extracting these different algorithms into separate classes known as strategies.</p><p>The original class, referred to as the context, should have a field to store a reference to one of these strategies. Instead of executing the task itself, the context delegates the work to the linked strategy object.</p><p>The context does not choose the appropriate algorithm for the task. Instead, the client provides the desired strategy to the context. The context is not deeply aware of the strategies; it interacts with all strategies through a common interface that exposes a single method to trigger the algorithm encapsulated within the chosen strategy. This approach makes the context independent of concrete strategies, allowing you to add new algorithms or modify existing ones without altering the context or other strategies code.</p><p>Let’s try to implement this pattern for scheduling strategies discussed above. Here we define the scheduling strategy interface and implement the concrete Strategies for both Round Robin and Priority scheduling.</p><pre>// Strategy Interface<br>interface SchedulingStrategy {<br>    void schedule(List&lt;Integer&gt; tasks);<br>}<br><br>// Concrete Strategies<br>class RoundRobinStrategy implements SchedulingStrategy {<br>    public void schedule(List&lt;Integer&gt; tasks) {<br>        // Simplified for demonstration<br>        System.out.println(&quot;Scheduling tasks using Round Robin: &quot; + tasks);<br>    }<br>}<br><br>class PriorityStrategy implements SchedulingStrategy {<br>    public void schedule(List&lt;Integer&gt; tasks) {<br>        // Simplified for demonstration<br>        Collections.sort(tasks);<br>        System.out.println(&quot;Scheduling tasks using Priority: &quot; + tasks);<br>    }<br>}</pre><p>Next, we define the context</p><pre>//Context<br>class Scheduler {<br>    private SchedulingStrategy strategy;<br><br>    public Scheduler(SchedulingStrategy strategy) {<br>        this.strategy = strategy;<br>    }<br><br>    public void setStrategy(SchedulingStrategy strategy) {<br>        this.strategy = strategy;<br>    }<br><br>    public void schedule(List&lt;Integer&gt; tasks) {<br>        strategy.schedule(tasks);<br>    }<br>}</pre><p>After this we define the factory interface and Concrete factories where the strategy gets passed to the context class.</p><pre>// Factory Interface<br>abstract class SchedulerFactory {<br>    public abstract Scheduler createScheduler();<br>}<br><br>// Concrete Factories<br>class RoundRobinSchedulerFactory extends SchedulerFactory {<br>    public Scheduler createScheduler() {<br>        return new Scheduler(new RoundRobinStrategy());<br>    }<br>}<br><br>class PrioritySchedulerFactory extends SchedulerFactory {<br>    public Scheduler createScheduler() {<br>        return new Scheduler(new PriorityStrategy());<br>    }<br>}</pre><p>The Strategy and factory classes defined above can be used together as shown below.</p><pre>public class Main {<br>    public static void main(String[] args) {<br>        List&lt;Integer&gt; tasks = Arrays.asList(3, 1, 2, 4);<br><br>        SchedulerFactory factory = new RoundRobinSchedulerFactory();<br>        Scheduler scheduler = factory.createScheduler();<br>        scheduler.schedule(tasks);<br><br>        factory = new PrioritySchedulerFactory();<br>        scheduler = factory.createScheduler();<br>        scheduler.schedule(tasks);<br>    }<br>}</pre><p>This can further be modified as shown below by setting up a Scheduling Strategy Factory instead of creating separate factories for each strategy as shown below.</p><pre>// Factory<br>class SchedulingStrategyFactory {<br>    public SchedulingStrategy createInstance(String strategyType) {<br>        switch (strategyType) {<br>            case &quot;RoundRobin&quot;:<br>                return new RoundRobinStrategy();<br>            case &quot;Priority&quot;:<br>                return new PriorityStrategy();<br>            default:<br>                throw new IllegalArgumentException(&quot;Unknown strategy type: &quot; + strategyType);<br>        }<br>    }<br>}</pre><p>This Scheduling Strategy Factory is used as shown below.</p><pre>public class Main {<br>    public static void main(String[] args) {<br>        List&lt;Integer&gt; tasks = Arrays.asList(3, 1, 2, 4);<br><br>        SchedulingStrategyFactory strategyFactory = new SchedulingStrategyFactory();<br>        SchedulingStrategy strategy = strategyFactory.createInstance(&quot;RoundRobin&quot;);<br>        Scheduler scheduler = new Scheduler(strategy);<br>        scheduler.schedule(tasks);<br><br>        strategy = strategyFactory.createInstance(&quot;Priority&quot;);<br>        scheduler.setStrategy(strategy);<br>        scheduler.schedule(tasks);<br>    }<br>}</pre><p>This demonstrates how to dynamically select and create different scheduling strategies at runtime using a combination of both these patterns. By introducing the SchedulingStrategyFactory, we further decouple the creation of strategy instances from the client code, making the system more flexible and easier to extend. This approach allows you to add new strategies by simply updating the factory without modifying the client code.</p><p>We observe the following advantages by combining these two patterns in this example.</p><p>By using the Strategy Pattern, you can easily switch between different algorithms at runtime. The SchedulingStrategyFactory further enhances this flexibility by allowing you to create different strategy instances based on input parameters. This makes your system adaptable to various requirements and conditions.</p><p>The Factory Pattern encapsulates the object creation process, which means that the client code doesn’t need to know the details of how the strategies are instantiated. This reduces the coupling between the client code and the concrete strategy classes, making the system more modular.</p><p>Adding new scheduling strategies becomes straightforward. You simply need to implement the new strategy class and update the factory method to handle the new strategy type. This adheres to the Open/Closed Principle, where the system is open for extension but closed for modification.</p><p>The SchedulingStrategyFactory allows you to select and create strategies at runtime based on dynamic input. This is particularly useful in scenarios where the best strategy depends on user preferences, system conditions, or other runtime factors.</p><ul><li>Single Responsibility Principle (SRP): Each class has a single responsibility. The Scheduler class is responsible for scheduling tasks, while the strategy classes are responsible for implementing the scheduling algorithms. The factory class is responsible for creating strategy instances.</li><li>Open/Closed Principle (OCP): The system is open for extension but closed for modification. You can add new strategies without changing the existing code.</li><li>Dependency Inversion Principle (DIP): The Scheduler class depends on abstractions (the SchedulingStrategy interface) rather than concrete implementations.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4a22f10a8405" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Zero Shot, One Shot and Few Shot Prompting]]></title>
            <link>https://medium.com/@akshathaholla91/zero-shot-one-shot-and-few-shot-prompting-663c265ec467?source=rss-79fc5b3ffbe1------2</link>
            <guid isPermaLink="false">https://medium.com/p/663c265ec467</guid>
            <category><![CDATA[one-shot-prompting]]></category>
            <category><![CDATA[genai]]></category>
            <category><![CDATA[few-shot-prompting]]></category>
            <category><![CDATA[prompt-engineering]]></category>
            <category><![CDATA[zero-shot-prompting]]></category>
            <dc:creator><![CDATA[Akshathaholla]]></dc:creator>
            <pubDate>Mon, 30 Sep 2024 11:21:23 GMT</pubDate>
            <atom:updated>2024-09-30T11:21:23.475Z</atom:updated>
            <content:encoded><![CDATA[<p>Large Language Models are trained on large amounts of data and this large-scale training enables these models to generate text, translate text, summarize content and answer questions based on the data it has been trained on.</p><p>We employ three techniques for providing input prompts to these models.</p><h4>Zero Shot Prompting</h4><p>Zero Shot prompting means that the prompts that are used to interact with the LLM does not contain any examples as part of it. The prompt gives a straightforward instruction without providing any samples guiding the generation of output. Here, the model relies on its language understanding and patterns that it has learned during its training to generate the appropriate output.</p><pre>Prompt:  &quot;Who is the author of Othello?&quot;</pre><pre>Response: &quot;The author of Othello is William Shakespeare. Othello is a tragedy written by Shakespeare around 1603-1604 and is considered one of his greatest works&quot;</pre><p>The above prompt and the response provided by the model demonstrates how a zero-shot prompt provided as an input to the model generates a response based on the general data that the language model was trained on earlier and was not explicitly provided with an input sample.</p><h4>One Shot Prompting</h4><p>One shot prompting refers to providing a single example as part of the prompt to help guide the model to produce an appropriate output by providing minimal but essential information. It can be used to indicate a template in which the output is expected or to tell the model how the input has to be handled based on the sample provided.</p><pre>Prompt: &quot;Classify the sentiment of the text provided.<br>Here is an example: &#39;I love eating chocolates&#39; -&gt; &#39;Positive&#39;. <br>Now classify the following text &#39;I hate travelling late in the night&#39;&quot;<br>Response: Negative</pre><p>From the above example the model understands that the sentiment of the statement has to be analyzed and returned as an output in a specific format.</p><p>Both Zero shot and One shot prompting rely on the general knowledge of the pre-trained models to perform actions that they are not explicitly trained on. In case of one shot prompting a single example is provided to frame the response in required manner.</p><h4>Few Shot Prompting</h4><p>Few Shot prompting involves providing multiple examples (atleast 2+) to enable the model to perform actions that are difficult to explain through instructions alone or when you want a very specific out format. Using the given examples the model recognizes the expected pattern and applies it to the output response.</p><pre>Prompt: &quot;Input: 1+1  Output: The sum of the numbers is 2.<br>        Input: 2-1  Output: The difference of the numbers is 1.<br>        Input: 2*1  Output: The product of the numbers is 2.<br>        Input: 2%1  Output:&quot;<br>Response: The remainder of the numbers is 0.</pre><p>The above example demonstrates the model’s ability to identify that the task is an arithmetic operation based on the given examples and provide an output in a format similar to the ones provided in the samples. The advantage of Few shot prompting over zero and one shot is that the accuracy is significantly improved due to multiple examples being provided which in turn helps the model to better understand the task and structure the response.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=663c265ec467" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Templatized Email body Generation using Large Language Models]]></title>
            <link>https://medium.com/@akshathaholla91/templatized-email-body-generation-using-large-language-models-9e7aa3df0ad?source=rss-79fc5b3ffbe1------2</link>
            <guid isPermaLink="false">https://medium.com/p/9e7aa3df0ad</guid>
            <category><![CDATA[openai]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[ai-email-generator]]></category>
            <dc:creator><![CDATA[Akshathaholla]]></dc:creator>
            <pubDate>Tue, 26 Sep 2023 18:14:33 GMT</pubDate>
            <atom:updated>2023-09-26T18:14:33.410Z</atom:updated>
            <content:encoded><![CDATA[<p>Imagine having a conversation with a computer that not only understands your words but can generate entire essays, poetry, or code at your command. Welcome to the era of Large Language Models, or LLMs for short, where machines have evolved to understand and create text in a way that seems almost uncanny.</p><p>A large language model (LLM) is a type of artificial intelligence (AI) algorithm that uses deep learning techniques and massively large data sets to understand, summarize, generate and predict new content.</p><p>In this blog we will explore how we can leverage the power of LLMs to automate personalized Email content generation.</p><p>Let’s take an example where an E-commerce retailer is interested to use Large Language models that can generate product description and generate a mail for the list of their existing customers with appropriate information. Let us take a look at the steps involved.</p><p><strong>Reading customers list and Product list</strong></p><p>Here we will use a sample customer list and product list available in the links below for customizing the content of the email body. We first save the data from the links into local csv files.</p><pre>import requests<br><br>customers_url = &quot;https://media.githubusercontent.com/media/datablist/sample-csv-files/main/files/people/people-100.csv&quot;<br>customers_file_name = &quot;./customers.csv&quot;<br><br>result=requests.get(customers_url)<br><br>with open(customers_file_name, &quot;w&quot;) as file:<br><br>    file.write(result.text)<br><br>products_url = &quot;https://diviengine.com/downloads/Divi-Engine-WooCommerce-Sample-Products.csv&quot;<br>products_file_name = &quot;./products.csv&quot;<br>result=requests.get(products_url)<br>with open(products_file_name, &quot;w&quot;) as file:<br>    file.write(result.text)</pre><p>Next we read the csv files and load it into memory</p><pre>import csv<br><br>def read_csv(filename):<br>    with open(filename, &#39;r&#39;) as file:<br>        return list(csv.DictReader(file))<br><br>products = read_csv(products_file_name)<br>customers = read_csv(customers_file_name)</pre><p><strong>Generating prompt with required variables for customers</strong></p><p>Here we create a sample prompt template which plays an important role in ensuring that the email generated has the right context and content. The customer and product information is utilized to customize the email body so that the content generated is highly personalized. The prompt also needs to be descriptive about what exactly is expected as part of the body.</p><p>The generated content is only as good as the prompt template that is designed.</p><pre>def generate_email_prompt(info: dict):<br>    prompt = &quot;&quot;&quot; Your goal is to write a personalized outbound email from {sales_rep}, a sales rep at  {company} to {prospect}.<br>    A good email is personalized and informs the customer on how your product can help the customer.<br>    Be sure to use value selling: A sales methodology that focuses on how your product or service will provide value to the customer instead of focusing on price or solution.<br>    % INFORMATION ABOUT {company}:<br>    a fashion and apparel company<br>    products list:<br>    {products_info}<br><br>    % INFORMATION ABOUT {prospect}:<br>    {text}<br><br>    % INCLUDE THE FOLLOWING PIECES IN YOUR RESPONSE:<br>    - Start the email with the sentence: &quot;We have amazing discounts on our premium products such as ...&quot; then insert the description of the product.<br>    - The sentence: &quot;We observed that XYZ product suits your taste &quot; Replace XYZ with one of the products<br>    - A 1-2 sentence description about the products, be brief<br>    - End your email with a call-to-action such as asking them to set up time to talk more<br><br>    % YOUR RESPONSE:&quot;&quot;&quot;<br>    for key in info.keys():<br>        prompt=prompt.replace(&quot;{&quot;+key+&quot;}&quot;,info[key])<br>    return prompt<br><br>customer_infos = []<br>for customer in customers[:5]:<br>    info = {}<br>    info[&#39;company&#39;] = &quot;XYZ&quot;<br>    info[&#39;sales_rep&#39;] = &quot;ABC&quot;<br>    info[&#39;prospect&#39;] = customer[&quot;First Name&quot;] + &quot; &quot; + customer[&quot;Last Name&quot;]<br>    info[&#39;text&#39;] = customer[&quot;Job Title&quot;]<br>    products_info= &quot;&quot;<br>    i=1<br>    for product in products[:5]:<br>        products_info += f&quot;\n {i}. Product Name: {product[&#39;Name&#39;]} \n  Description: {product[&#39;Short description&#39;]}&quot;<br>        i+=1<br>    info[&#39;products_info&#39;]=products_info<br>    customer_infos.append(info)<br>llm_chain=LLMChain(prompt=prompt_template,llm=llm, verbose = True)<br><br><br>prompts = [generate_email_prompt(info) for info in customer_infos]</pre><p>Once the prompt is generated for various customers we use OpenAI Completion for generating the final email content from the prompt that is provided.</p><p><strong>Interface with LLMs and generate Email content</strong></p><p>The last step is to interface with the hosted LLMs of your choice using Hugging face or OpenAI or Cohere (Here we chose OpenAI)</p><pre>import os<br>import openai<br><br>openai.api_key = os.getenv(&quot;OPENAI_API_KEY&quot;)<br><br>responses = [openai.Completion.create(<br>  model=&quot;text-davinci-003&quot;,<br>  prompt=prompt,<br>  temperature=0,<br>  max_tokens=3000,<br>  top_p=1.0,<br>  frequency_penalty=0.0,<br>  presence_penalty=0.0<br>) for prompt in prompts]<br><br>email_body = responses[0][&quot;choices&quot;][0].text</pre><p>Here the temperature parameter is a hyperparameter that can be used to control the randomness and creativity of the generated text in a generative language model. When the temperature is set to a low value it results in more conservative and predictable text. The temperature value can be varied based on the creativity you wish to see in the generated text. We have chosen text-davinci-003 which is a text generation model available as part of OpenAI. We have set a max token limit of 3000. Depending on the model used, requests can use up to 3000 tokens shared between prompt and completion. If your prompt is 1000 tokens, your completion can be 2000 tokens at most. top_p limits the pool of available tokens that can be chosen from, for completion. The value 1 represents a big pool so lot of tokens are available for the completion. Frequency_penalty is used to discourage the model from repeating frequently used/present words while presence_penalty encourages the model to use a more diverse range of words in the generated text.</p><p><strong>Sample Response</strong></p><pre>Dear Shelby Terrell,<br><br>We have amazing discounts on our premium products such as the Divi Engine String Bag . We observed that the Divi Engine String Bag suits your taste. This fashionable string bag is made of 100% cotton and is the perfect size for carrying your everyday essentials. We also have Brand Buttons and Brand Buttons - Divi and Divi Engine, which are perfect for representing your favorite CMS, eCommerce Platform, Website Builder, or Plugin Company in style.<br><br>We would love to discuss how our products can help you reach your goals. Please let us know when you are available to set up a time to talk more.<br><br>Thank you for your time and consideration.<br><br>Sincerely,<br>ABC<br>XYZ</pre><p>In conclusion, the capability of LLMs as an automated email/content generation tool is undeniable. From crafting persuasive marketing emails to streamlining customer support responses, these AI-driven solutions have proven their worth in today’s fast-paced digital landscape.</p><p>However, as we embrace this technology, it’s crucial to remember that while AI can automate the process of generating emails, it cannot replace the human touch entirely. Personalization, empathy, and context-awareness are qualities that only human writers can truly provide. Thus, the synergy between AI-generated content and human creativity is the key to unlocking the full potential of email communication.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9e7aa3df0ad" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Scheduling Poll based Tasks using Timer in Java]]></title>
            <link>https://medium.com/@akshathaholla91/scheduling-poll-based-tasks-using-timer-in-java-bebbb0e814aa?source=rss-79fc5b3ffbe1------2</link>
            <guid isPermaLink="false">https://medium.com/p/bebbb0e814aa</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[scheduling]]></category>
            <category><![CDATA[timer]]></category>
            <category><![CDATA[polling]]></category>
            <dc:creator><![CDATA[Akshathaholla]]></dc:creator>
            <pubDate>Thu, 29 Sep 2022 15:10:38 GMT</pubDate>
            <atom:updated>2022-09-29T15:10:38.025Z</atom:updated>
            <content:encoded><![CDATA[<p>Many projects require automation in accepting/reading data from an external source on a timely basis and require certain tasks to be scheduled for processing that data. Scheduling tasks to start at a specified time and periodically polling for a given duration is required in cases where the source of the data does not provide any form of push based triggers for alerting the arrival of data. One of the ways in which this can be achieved in Java is by using the <em>Java.util.Timer</em> class with a little bit of additional functionality added for maintaining the timer lifecycle.</p><h3>Implementation</h3><p>We will start by creating a class that Extends the <em>Java.util.TimerTask</em> class as below</p><pre>public class ScheduleTimerTask extends TimerTask {<br>    private Timer timer;<br><br>    public ScheduleTimerTask(Timer timer) {<br>        this.timer = timer;<br>    }<br><br>    @Override<br>    public void run() {<br>        if (isDataAvailable()) {<br>            this.cancel();<br>            timer.cancel();<br>        }<br>    }<br><br>    private boolean isDataAvailable() {<br>    //Check whether required data is available and perform processing<br>    }<br>}</pre><p>The Timer takes an implementation of Timer Task class as an input that can be scheduled to run at a specific time once or multiple times based on a poll period.</p><p>In ScheduleTimerTask class we take the Timer instance as a constructor parameter so that we have control over the Timer instance for cancellation/purging once the required input data is received. Here this.cancel() cancels the TimerTask but the timer itself continues if there are other tasks registered against it. Since we only have one task per timer, we cancel the timer as well using timer.cancel().</p><pre>public class SampleScheduler {<br>    public static void main(String[] args) {<br>        List&lt;Schedule&gt; schedules = this.getSchedules();<br>        for (Schedule schedule : schedules) {<br>            this.scheduleTask(schedule.getStartTime(), schedule.getPollDuration());<br>        }<br><br>    }<br><br>    public void scheduleTask(Date startTime, long pollDuration) {<br>        Timer timer = new Timer();<br>        ScheduleTimerTask scheduleTimerTask = new ScheduleTimerTask(timer);<br>        timer.scheduleAtFixedRate(scheduleTimerTask, startTime, pollDuration);<br>    }<br><br>    public List&lt;Schedule&gt; getSchedules() {<br>        //Get schedules for incoming data<br>    }<br>}</pre><p>The above class shows a sample scheduler which gets the available schedules and creates a Timer and ScheduleTimerTask for each of them and calls scheduleAtFixedRate for starting the Timer at the given Start time and polling for data at the specified poll duration. During each poll the run method checks for availability of the data until it is received and subsequently cancels both the TimerTask and Timer as mentioned earlier once the data is available.</p><p>Additionally , if the schedule has an end time at which polling has to stop, an additional check could be applied in the run method to compare current time against end time and stop the task and the timer once end time is reached.</p><h3>Conclusion</h3><p>While there are many other alternative approaches available such as using RateLimiter from Guava library, the above approach provides a simple way to Schedule and run poll based tasks using the built in Java Timer Class.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bebbb0e814aa" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>