<?xml version="1.0" encoding="utf-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
    <channel>
        <title>sillicon</title>
        <link>https://velog.io/</link>
        <description>software engineer</description>
        <lastBuildDate>Sat, 02 Sep 2023 01:54:50 GMT</lastBuildDate>
        <docs>https://validator.w3.org/feed/docs/rss2.html</docs>
        <generator>https://github.com/jpmonette/feed</generator>
        <copyright>Copyright (C) 2019. sillicon. All rights reserved.</copyright>
        <atom:link href="https://v2.velog.io/rss/lucid_fizz" rel="self" type="application/rss+xml"/>
        <item>
            <title><![CDATA[The Merit of Alternating Between Design Docs and Code]]></title>
            <link>https://velog.io/@lucid_fizz/The-Benefits-of-Alternating-Between-Design-Docs-and-Code</link>
            <guid>https://velog.io/@lucid_fizz/The-Benefits-of-Alternating-Between-Design-Docs-and-Code</guid>
            <pubDate>Sat, 02 Sep 2023 01:54:50 GMT</pubDate>
            <description><![CDATA[<p>One effective approach I&#39;ve found in software development is the practice of alternating between writing design documents and actual coding. This iterative process has multiple benefits.</p>
<h2 id="design-first-but-not-too-much">Design First, But Not Too Much</h2>
<p>Starting with a high-level draft of a design document provides a preliminary architectural overview. It sets the stage by outlining the software&#39;s main objectives and offers an initial roadmap for the journey ahead. Yet, this is not an exhaustive exercise; the purpose is to sketch, not to draw every detail.</p>
<h2 id="refining-through-coding">Refining Through Coding</h2>
<p>When transitioning from the design phase to coding, new insights invariably emerge. These insights, often unanticipated during the initial design phase, can lead to significant refinements. Incorporating these learnings back into the design doc ensures it remains a living document, continually updated to reflect the project&#39;s evolving state.</p>
<h2 id="ties-to-domain-driven-design-ddd">Ties to Domain-Driven Design (DDD)</h2>
<p>The idea of starting with a design document aligns with the principles of Domain-Driven Design (DDD). At the heart of DDD is creating an accurate model that represents the domain, its constraints, and its intricacies. Similarly, the design doc seeks to model the software&#39;s architecture and objectives. </p>
<p>Keeping design documents updated and close to the code can be seen as parallel to DDD&#39;s concept of a ubiquitous language. Such a practice ensures a shared understanding, bridging any knowledge gap among team members. Furthermore, as DDD encourages collaboration and discussion about the domain, design docs can serve as catalysts for these essential conversations.</p>
<h2 id="conclusion">Conclusion</h2>
<p>While some developers may lean towards diving directly into code, alternating between design and development offers a balanced perspective. It promotes clarity, foresight, and adaptability, qualities indispensable in a constantly evolving domain. </p>
<p>For those skeptical about the utility of design docs, consider them as extensions of READMEs. Naming them <code>DESIGN.md</code> or something similar and placing them in the project repository ensures they&#39;re accessible and continually relevant.</p>
<hr>
]]></description>
        </item>
        <item>
            <title><![CDATA[docker network_mode:host]]></title>
            <link>https://velog.io/@lucid_fizz/docker-networkmodehost</link>
            <guid>https://velog.io/@lucid_fizz/docker-networkmodehost</guid>
            <pubDate>Mon, 07 Aug 2023 09:37:10 GMT</pubDate>
            <description><![CDATA[<p>docker has host mode network, which stops network isolation</p>
<p>so port mappings will not work</p>
<p>but note that this option is <a href="https://docs.docker.com/network/drivers/host/#:~:text=The%20host%20networking%20driver%20only%20works%20on%20Linux%20hosts%2C%20and%20is%20not%20supported%20on%20Docker%20Desktop%20for%20Mac%2C%20Docker%20Desktop%20for%20Windows%2C%20or%20Docker%20EE%20for%20Windows%20Server.">only avaiable on linux</a>. Not on macOS or Windows.</p>
<p>so a docker-compose file or docker run command working on linux might not work on macOS with this</p>
]]></description>
        </item>
        <item>
            <title><![CDATA[After reading an article about "Leaky Abstractions"
]]></title>
            <link>https://velog.io/@lucid_fizz/After-reading-an-article-about-Leaky-Abstractions</link>
            <guid>https://velog.io/@lucid_fizz/After-reading-an-article-about-Leaky-Abstractions</guid>
            <pubDate>Mon, 31 Jul 2023 09:05:23 GMT</pubDate>
            <description><![CDATA[<blockquote>
<p>The law of leaky abstractions means that whenever somebody comes up with a wizzy new code-generation tool that is supposed to make us all ever-so-efficient, you hear a lot of people saying “learn how to do it manually first, then use the wizzy tool to save time.” Code generation tools which pretend to abstract out something, like all abstractions, leak, and the only way to deal with the leaks competently is to learn about how the abstractions work and what they are abstracting. So the abstractions save us time working, but they don’t save us time learning.</p>
</blockquote>
<p><a href="https://www.joelonsoftware.com/2002/11/11/the-law-of-leaky-abstractions/">https://www.joelonsoftware.com/2002/11/11/the-law-of-leaky-abstractions/</a></p>
<p>old article, but had a lot of fun reading. <strong>abstractions save us time working, but they don’t save us time learning.</strong>.</p>
<p>ChatGPT4 and other AI tools are sort of same I think. Although they also do save time some time learning by being a high-class personal tutor that answers my flood of questions without being irritated.</p>
]]></description>
        </item>
        <item>
            <title><![CDATA[AI tools for coding]]></title>
            <link>https://velog.io/@lucid_fizz/AI-tools-for-coding</link>
            <guid>https://velog.io/@lucid_fizz/AI-tools-for-coding</guid>
            <pubDate>Tue, 25 Jul 2023 01:43:38 GMT</pubDate>
            <description><![CDATA[<h2 id="what-i-use-ai-tools-for">What I use AI tools for</h2>
<p>I mostly use AI tools for coding in these 2 reasons:</p>
<ul>
<li>To solve a conceptual problem<ul>
<li>Large scale: ex. How would I design the structure of a new database</li>
<li>Smaller scale: ex. How would I implement this service function in my api-server</li>
</ul>
</li>
<li>To reduce menial keyboard typing of stuff.<ul>
<li>Implement a type predicate for this interface A<h2 id="stuff-i-used">Stuff I used</h2>
I used chatGPT (both paid and free), Google Bard, new Bing, and HuggingFace chat, Hugging Face Code VSC extension so far.<h2 id="how-i-use">How I use</h2>
I mostly use ChatGPT 4 for the larger conceptual problem. Because it has the highest context retention and reasoning. The smartest one. But this one has a message cap for 25 messages/3 hrs</li>
</ul>
</li>
</ul>
<p>So For menial tasks I would use anything else.</p>
<h2 id="miscellaneous">Miscellaneous</h2>
<ul>
<li>new bing for search. </li>
<li>Hugging Face chat is not really credible IMO. But since it is open-source seems to get a lot of updates. Also the most fun to play with because it spits out lots of funny nonsense</li>
<li>Hugging Face code is also decent if you don&#39;t want to spend money on Github copilot.</li>
</ul>
]]></description>
        </item>
        <item>
            <title><![CDATA[why python f-strings are fast ]]></title>
            <link>https://velog.io/@lucid_fizz/why-python-f-strings-are-fast</link>
            <guid>https://velog.io/@lucid_fizz/why-python-f-strings-are-fast</guid>
            <pubDate>Tue, 13 Jun 2023 05:48:46 GMT</pubDate>
            <description><![CDATA[<p>Conclusion: f-strings are fastest in CPython because it builds the strings straight from <code>stack</code> to improve performance. A new Opcode <code>BUILD_STRING</code> was added specifically to solve this problem.</p>
<p>there are many ways to format a string in python</p>
<ul>
<li>String concatenation.<ul>
<li><code>&quot;My name is &quot; + my_name + &quot;.&quot;</code> </li>
</ul>
</li>
<li>% format</li>
<li><code>&quot;My name is %s.&quot;.format(my_name)</code></li>
<li><code>&quot;&quot;.join([&quot;My name is &quot; , my_name , &quot;.&quot;])</code></li>
<li>f-strings (string literals)<ul>
<li><code>f&quot;My name is {my_name}.&quot;</code></li>
</ul>
</li>
</ul>
<p>We can think about some aspects to consider when choosing which method to use.</p>
<p>First,need to decide which implementation are we using? CPython? PyPI? Rust-Python? CPython is most used, so talking about that.</p>
<p>Then,</p>
<ul>
<li>Usability. easy to make mistakes? easy to write code?</li>
<li>Performance. <ul>
<li>Speed. How fast is it for large strings or when it is repeated?</li>
<li>Memory usage. How many new strings, i.e. PyObjects</li>
</ul>
</li>
</ul>
<p>This blog is about performance part. For Usability you can refer to many good posts, or realpython.org, or google python guide.</p>
<p>Most performance issue in CPython is due to creation of <code>PyObject</code> structs. While strings look mutable in python source code, under the hood new <code>PyObject</code> is created everytime a string is updated.</p>
<p>so &quot;My name is &quot; + my_name + &quot;.&quot; usually shows worst performance.
% format
str.format()
&#39;&#39;.join(list_of_str_to_join) 
these 3 joins the string at once, but with additional parsing.</p>
<p>f-string, introduced at python 3.6, called &#39;&#39;.join() as subroutine in its alpha stage. Then in <a href="https://bugs.python.org/issue27078">this discussion</a>, a patch was made to join them straight from the stack using a <a href="https://hg.python.org/cpython/rev/28e280915508#l10.1">new Opcode</a> <code>BUILD_STRING</code>. </p>
<p>refrences
<a href="https://hg.python.org/cpython/rev/28e280915508#l10.1">https://hg.python.org/cpython/rev/28e280915508#l10.1</a>
<a href="https://bugs.python.org/issue27078">https://bugs.python.org/issue27078</a></p>
]]></description>
        </item>
        <item>
            <title><![CDATA[Visitor Pattern]]></title>
            <link>https://velog.io/@lucid_fizz/Visitor-Pattern</link>
            <guid>https://velog.io/@lucid_fizz/Visitor-Pattern</guid>
            <pubDate>Thu, 09 Mar 2023 03:25:08 GMT</pubDate>
            <description><![CDATA[<p>A behavioral pattern
<em>This post mostly excerpt from Design Patterns (1994)</em></p>
<h3 id="intent">Intent</h3>
<p>Represent an operation to be performed on the elements of an object structure. Visitor lets you define a new operation without changing the classes of the elements on which it operates.</p>
<h3 id="motivation">Motivation</h3>
<p>Consider a compiler that represents programs as <strong>abstract syntax trees</strong>. It will need to perform operations on abstract syntax trees for “static semantic” analyses like checking that all variables are defined. It will also need to generate code. So it might define operations for type-checking, code optimization, flow analysis, checking for variables being assigned values before they’re used, and so on. Moreover, we could use the abstract syntax trees for pretty-printing, program restructuring, code instrumentation, and computing various metrics of a program.</p>
<p>Most of these operations will need to treat nodes that represent assignment statements differently from nodes that represent variables or arithmetic expressions. Hence there will be one class for assignment statements, another for variable accesses, another for arithmetic expressions, and so on. The set of node classes depends on the language being compiled, of course, but it doesn’t change much for a given language.
<img src="https://velog.velcdn.com/images/lucid_fizz/post/cccdc536-bef9-46ba-8393-51fb3c87c7ac/image.png" alt="">
This diagram shows part of the Node class hierarchy. The problem here is that distributing all these operations across the various node classes leads to a system that’s hard to understand, maintain, and change. It will be confusing to have type-checking code mixed with pretty-printing code or flow analysis code. Moreover, adding a new operation usually requires recompiling all of these classes (not really relevant for python). It would be better if each new operation could be added separately, and the node classes were independent of the operations that apply to them.</p>
<p>We can have both by packaging related operations from each class in a separate object, called a visitor, and passing it to elements of the abstract syntax tree as it’s traversed. When an element “accepts” the visitor, it sends a request to the visitor that encodes the element’s class. It also includes the element as an argument. The visitor will then execute the operation for that element—the operation that used to be in the class of the element.</p>
<p>For example, a compiler that didn’t use visitors might type-check a procedure by calling the TypeCheck operation on its abstract syntax tree. Each of the nodes would implement TypeCheck by calling TypeCheck on its components (see the preceding class diagram). If the compiler type-checked a procedure using visitors, then it would create a TypeCheckingVisitor object and call the Accept operation on the abstract syntax tree with that object as an argument. Each of the nodes would implement Accept by calling back on the visitor: an assignment node calls VisitAssignment operation on the visitor, while a variable reference calls VisitVariableReference. What used to be the TypeCheck operation in class AssignmentNode is now the VisitAssignment operation on TypeCheckingVisitor.</p>
<p><img src="https://velog.velcdn.com/images/lucid_fizz/post/4e41d69e-0b26-41eb-ac7a-a072ccd2c3f5/image.png" alt="">
To make visitors work for more than just type-checking, we need an abstract parent class NodeVisitor for all visitors of an abstract syntax tree. NodeVisitor must declare an operation for each node class. An application that needs to compute program metrics will define new subclasses of NodeVisitor and will no longer need to add application-specific code to the node classes. The Visitor pattern encapsulates the operations for each compilation phase in a Visitor associated with that phase.
<img src="https://velog.velcdn.com/images/lucid_fizz/post/84027340-bc90-477f-ac01-1b31670b091c/image.png" alt="">
With the Visitor pattern, you define two class hierarchies: one for the elements being operated on (the Node hierarchy) and one for the visitors that define operations on the elements (the NodeVisitor hierarchy). You create a new operation by adding a new subclass to the visitor class hierarchy. As long as the grammar that the compiler accepts doesn’t change (that is, we don’t have to add new Node subclasses), we can add new functionality simply by defining new NodeVisitor subclasses.</p>
<h3 id="applicability">Applicability</h3>
<p>Use the Visitor pattern when</p>
<ul>
<li>an object structure contains many classes of objects with differing interfaces, and you want to perform operations on these objects that depend on their concrete classes.</li>
<li>many distinct and unrelated operations need to be performed on objects in an object structure, and you want to avoid “polluting” their classes with these operations. Visitor lets you keep related operations together by defining them in one class. When the object structure is shared by many applications, use Visitor to put operations in just those applications that need them.</li>
<li>the classes defining the object structure rarely change, but you often want to define new operations over the structure. Changing the object structure classes requires redefining the interface to all visitors, which is potentially costly. If the object structure classes change often, then it’s probably better to define the operations in those classes.<h3 id="structure">Structure</h3>
<img src="https://velog.velcdn.com/images/lucid_fizz/post/e93d6d21-9d9c-4ee3-8e11-d9fab7d796f7/image.png" alt=""><h3 id="participants">Participants</h3>
</li>
<li>Visitor (NodeVisitor)<ul>
<li>declares a Visit operation for each class of ConcreteElement in the object structure. The operation’s name and signature identifies the class that sends the Visit request to the visitor. That lets the visitor determine the concrete class of the element being visited. Then the visitor can access the element directly through its particular interface</li>
</ul>
</li>
<li>Concrete Visitor (TypeCheckingVisitor)<ul>
<li>implements each operation declared by Visitor. Each operation implements a fragment of the algorithm defined for the corresponding class of object in the structure. ConcreteVisitor provides the context for the algorithm and stores its local state. This state often accumulates results during the traversal of the structure.</li>
</ul>
</li>
<li>Element (Node)<ul>
<li>defines an Accept operation that takes a visitor as an argument.</li>
</ul>
</li>
<li>ConcreteElement (AssignmentNode, VariableRefNode)<ul>
<li>implements an Accept operation that takes a visitor as an argument.</li>
</ul>
</li>
<li>ObjectStructure (Program)<ul>
<li>can enumerate its elements.</li>
<li>may provide a high-level interface to allow the visitor to visit its elements.</li>
<li>may either be a composite or a collection such as a list or a set.<h3 id="collaborations">Collaborations</h3>
</li>
</ul>
</li>
<li>A client that uses the Visitor pattern must create a ConcreteVisitor object and then traverse the object structure, visiting each element with the visitor.</li>
<li>When an element is visited, it calls the Visitor operation that corresponds to its class. The element supplies itself as an argument to this operation to let the visitor access its state, if necessary.
The following interaction diagram illustrates the collaborations between an object structure, a visitor, and two elements:
<img src="https://velog.velcdn.com/images/lucid_fizz/post/58b01f53-86fa-4b78-ba67-6041e50721f8/image.png" alt=""><h3 id="consequences">Consequences</h3>
Some of the benefits and liabilities of the Visitor pattern are as follows:</li>
</ul>
<ol>
<li><p><em>Visitor makes adding new operations easy</em>. Visitors make it easy to add operations that depend on the components of complex objects. You can define a new operation over an object structure simply by adding a new visitor. In contrast, if you spread functionality over many classes, then you must change each class to define a new operation.</p>
</li>
<li><p><em>A visitor gathers related operations and separates unrelated ones.</em> Related behavior isn’t spread over the classes defining the object structure; it’s localized in a visitor. Unrelated sets of behavior are partitioned in their own visitor subclasses. That simplifies both the classes defining the elements and the algorithms defined in the visitors. Any algorithm-specific data structures can be hidden in the visitor.</p>
</li>
<li><p><em>Adding new ConcreteElement classes is hard.</em> The Visitor pattern makes it hard to add new subclasses of Element. Each new ConcreteElement gives rise to a new abstract operation on Visitor and a corresponding implementation in every ConcreteVisitor class. Sometimes a default implementation can be provided in Visitor that can be inherited by most of the ConcreteVisitors, but this is the exception rather than the rule.</p>
<p>So the <strong>key consideration in applying the Visitor pattern is whether you are mostly likely to change the algorithm applied over an object structure or the classes of objects that make up the structure</strong>. The Visitor class hierarchy can be difficult to maintain when new ConcreteElement classes are added frequently. In such cases, it’s probably easier just to define operations on the classes that make up the structure. If the Element class hierarchy is stable, but you are continually adding operations or changing algorithms, then the Visitor pattern will help you manage the changes.</p>
</li>
<li><p><em>Visiting across class hierarchies.</em> An iterator (Iterator Pattern) can visit the objects in a structure as it traverses them by calling their operations. But an iterator can’t work across object structures with different types of elements. Whereas a visitor can visit objects that don&#39;t have a common parent class.</p>
</li>
<li><p><em>Accumulating state.</em> Visitors can accumulate state as they visit each element in the object structure. Without a visitor, this state would be passed as extra arguments to the operations that perform the traversal, or they might appear as global variables.</p>
</li>
<li><p><em>Breaking encapsulation.</em> Visitor’s approach assumes that the ConcreteElement interface is powerful enough to let visitors do their job. As a result, the pattern often forces you to provide public operations that access an element’s internal state, which may compromise its encapsulation.</p>
<h3 id="implementation">Implementation</h3>
<p>Each object structure will have an associated Visitor class. This abstract visitor class declares a VisitConcreteElement operation for each class of ConcreteElement defining the object structure. Each Visit operation on the Visitor declares its argument to be a particular ConcreteElement, allowing the Visitor to access the interface of the ConcreteElement directly. Concrete Visitor classes override each Visit operation to implement visitor-specific behavior for the corresponding ConcreteElement class.
(some example code omitted)</p>
</li>
</ol>
<p>Here are two other implementation issues that arise when you apply the Visitor pattern:</p>
<ol>
<li><p><em>Double dispatch.</em> Effectively, the Visitor pattern lets you add operations to classes without changing them. Visitor achieves this by using a technique called double-dispatch. (not sure what this is yet) It’s a well-known technique. In fact, some programming languages support it directly (CLOS, for example). Languages like C++ and Smalltalk support single-dispatch.</p>
<p>In single-dispatch languages, two criteria determine which operation will fulfill a request: the name of the request and the type of receiver. For example, the operation that a GenerateCode request will call depends  In single-dispatch languages, two criteria determine which operation will fulfill a request: the name of the request and the type of receiver. For example, the operation that a GenerateCode request will call depends  on the type of node object you ask. In C++, calling GenerateCode on an instance of VariableRefNode will call VariableRefNode::GenerateCode (which generates code for a variable reference). Calling GenerateCode on an AssignmentNode will call AssignmentNode::GenerateCode (which will generate code for an assignment). The operation that gets executed depends both on the kind of request and the type of the receiver.</p>
<p>“Double-dispatch” simply means the operation that gets executed depends on the kind of request and the types of two receivers. Accept is a double-dispatch operation. Its meaning depends on two types: the Visitor’s and the Element’s. Double-dispatching lets visitors request different operations on each class of element.(If we can have double-dispatch, then why not triple or quadruple, or any other number? Actually, double-dispatch is just a special case of multiple dispatch, in which the operation is chosen based on any number of types. (CLOS(?) actually supports multiple dispatch.) Languages that support double- or multiple dispatch lessen the need for the Visitor pattern.)</p>
<p><strong>This is the key to the Visitor pattern: The operation that gets executed depends on both the type of Visitor and the type of Element it visits</strong>. Instead of binding operations statically into the Element interface, you can consolidate the operations in a Visitor and use Accept to do the binding at run-time. Extending the Element interface amounts to defining one new Visitor subclass rather than many new Element subclasses.</p>
</li>
<li><p>Who is responsible for traversing the object structure? A visitor must visit each element of the object structure. The question is, how does it get there? We can put responsibility for traversal in any of three places: in the object structure, in the visitor, or in a separate iterator object (see Iterator (257)).</p>
<p>Often the object structure is responsible for iteration. A collection will simply iterate over its elements, calling the Accept operation on each. A composite will commonly traverse itself by having each Accept operation traverse the element’s children and call Accept on each of them recursively.</p>
<p>Another solution is to use an iterator to visit the elements. In C++, you could use either an internal or external iterator, depending on what is available and what is most efficient. In Smalltalk, you usually use an internal iterator using do: and a block. Since internal iterators are implemented by the object structure, using an internal iterator is a lot like making the object structure responsible for iteration. The main difference is that an internal iterator will not cause double-dispatching—it will call an operation on the visitor with an element as an argument as opposed to calling an operation on the element with the visitor as an argument. But it’s easy to use the Visitor pattern with an internal iterator if the operation on the visitor simply calls the operation on the element without recursing.</p>
<p>You could even put the traversal algorithm in the visitor, although you’ll end up duplicating the traversal code in each ConcreteVisitor for each aggregate ConcreteElement. The main reason to put the traversal strategy in the visitor is to implement a particularly complex traversal, one that depends on the results of the operations on the object structure. We’ll give an example of such a case in the Sample Code.</p>
<h3 id="sample-code">Sample Code</h3>
<p>In C++, I try to rewrite in python3. omitted</p>
<h3 id="known-uses">Known Uses</h3>
<p>check in book.</p>
<h3 id="related-patterns">Related Patterns</h3>
<p>Composite: visitors can be used to apply an operation over object hierarchy defined by the Composite Pattern.
Interpreter: Visitor pattern may be applied to the interpretation</p>
</li>
</ol>
]]></description>
        </item>
        <item>
            <title><![CDATA[Iterator Pattern]]></title>
            <link>https://velog.io/@lucid_fizz/Iterator-Pattern</link>
            <guid>https://velog.io/@lucid_fizz/Iterator-Pattern</guid>
            <pubDate>Wed, 08 Mar 2023 12:55:25 GMT</pubDate>
            <description><![CDATA[<h3 id="intent">Intent</h3>
<p>Provide a way to access the elements of an aggregator object sequentially w/o exposing its underlying representation</p>
<h3 id="also-known-as">Also Known As</h3>
<p>Cursor</p>
<h3 id="motivation">Motivation</h3>
<p>An aggregate object needs a way to access elems w/o exposing details. And you might also need different ways to traverse it too. But you don&#39;t want to bloat the interface w/ too many options for traversals.</p>
<p> The key idea in this pattern is to take the responsibility for access and traversal out of the list object and put it into an iterator object. Iterator class will define interface to traverse a List object, as well as keeping track of current elem.</p>
<p> <img src="https://velog.velcdn.com/images/lucid_fizz/post/d408d09d-3566-4b48-98ee-15555525f092/image.png" alt="">
 Separating the traversal mechanism from the List object lets us define iterators for different traversal policies without enumerating them in the List interface. For example, FilteringListIterator might provide access only to those elements that satisfy specific filtering constraints.</p>
<p> Notice that the iterator and the list are coupled, and the client must know that it is a list that’s traversed as opposed to some other aggregate structure. Hence the client commits to a particular aggregate structure. It would be better if we could change the aggregate class without changing client code. We can do this by generalizing the iterator concept to support <strong>polymorphic</strong> iteration.
 Then an abstract class may be defined, making iterator mechanism become independent of concrete aggregate classes.
<img src="https://velog.velcdn.com/images/lucid_fizz/post/8d816d0d-b8ea-446e-a366-8b5333431ae1/image.png" alt="">
 The remaining problem is how to create the iterator. Since we want to write code that’s independent of the concrete List subclasses, we cannot simply instantiate a specific class. Instead, we make the list objects responsible for creating their corresponding iterator. This requires an operation like CreateIterator through which clients request an iterator object.</p>
<p>CreateIterator is an example of a Factory Method. We use it here to let a client ask a list object for the appropriate iterator. The Factory Method approach give rise to two class hierarchies, one for lists and another for iterators. The CreateIterator factory method “connects” the two hierarchies.</p>
<h3 id="applicability">Applicability</h3>
<p>Use the Iterator pattern
• to access an aggregate object’s contents without exposing its internal representation.
• to support multiple traversals of aggregate objects.
• to provide a uniform interface for traversing different aggregate structures (that is, to support polymorphic iteration).</p>
<h3 id="structure">Structure</h3>
<p><img src="https://velog.velcdn.com/images/lucid_fizz/post/80034ddb-db73-408f-ab25-965931e02ced/image.png" alt=""></p>
<h3 id="participants">Participants</h3>
<ul>
<li>Iterator<ul>
<li>defines an interface for accessing and traversing elements.</li>
</ul>
</li>
<li>ConcreteIterator<ul>
<li>implements the Iterator interface.</li>
<li>keeps track of the current position in the traversal of the aggregate.</li>
</ul>
</li>
<li>Aggregate<ul>
<li>defines an interface for creating an Iterator object.</li>
</ul>
</li>
<li>ConcreteAggregate<ul>
<li>implements the Iterator creation interface to return an instance of the proper ConcreteIterator.<h3 id="collaborations">Collaborations</h3>
</li>
<li>A ConcreteIterator keeps track of the current object in the aggregate and can compute the succeeding object in the traversal.<h3 id="consequences">Consequences</h3>
The Iterator pattern has three important consequences:</li>
</ul>
</li>
</ul>
<ol>
<li><p><em>It supports variations in the traversal of an aggregate</em>. Complex aggregates may be traversed in many ways. </p>
</li>
<li><p><em>Iterators simplify the Aggregate interface.</em> Iterator’s traversal interface obviates the need for a similar interface in Aggregate, thereby simplifying the aggregate’s interface.</p>
</li>
<li><p><em>More than one traversal can be pending on an aggregate.</em> An iterator keeps track of its own traversal state. Therefore you can have more than one traversal in progress at once.</p>
<h3 id="implementation-long">Implementation (Long)</h3>
<p>Iterator has many implementation variants and alternatives. Some important ones follow. The trade-offs often depend on the control structures your language provides. Some languages even support this pattern directly.</p>
</li>
<li><p><em>Who controls the iteration?</em> Internal iterator are usually easier to use, as they define the iteration logic. External iterator, meaning client advance traversal, request next elem explicitly, are more flexible.</p>
</li>
<li><p><em>Who defines the traversal algorithm?</em> The iterator is not the only place where the traversal algorithm can be defined. The aggregate might define the traversal algorithm and use the iterator to store just the state of the iteration. This kind of iterator is a cursor, since it merely points to the current position in the aggregate. A client will invoke the Next operation on the aggregate with the cursor as an argument, and the Next operation will change the state of the cursor.</p>
<p>If the iterator is responsible for the traversal algorithm, then it’s easy to use different iteration algorithms on the same aggregate, and it can also be easier to reuse the same algorithm on different aggregates (perhaps strategy pattern?). On the other hand, the traversal algorithm might need to access the private variables of the aggregate. If so, putting the traversal algorithm in the iterator violates the encapsulation of the aggregate.</p>
</li>
<li><p><em>How robust is the iterator?</em> It can be dangerous to modify an aggregate while you’re traversing it. If elements are added or deleted from the aggregate, you might end up accessing an element twice or missing it completely. A simple solution is to copy the aggregate and traverse the copy, but that’s too expensive to do in general. </p>
<p>A robust iterator ensures that insertions and removals won’t interfere with traversal, and it does it without copying the aggregate. There are many ways to implement robust iterators. Most rely on registering the iterator with the aggregate. On insertion or removal, the aggregate either adjusts the internal state of iterators it has produced, or it maintains information internally to ensure proper traversal.
(some examples from book. Not sure what an ET++ is even.. Kofler provides a good discussion of how robust iterators are implemented in ET++ [Kof93]. Murray discusses the implementation of robust iterators for the USL StandardComponents’ List class [Mur93].)</p>
</li>
<li><p><em>Additional Iterator operations.</em> The minimal interface to Iterator consists of the operations First, Next, IsDone, and CurrentItem. (We can make this interface even smaller by merging Next, IsDone, and CurrentItem into a single operation that advances to the next object and returns it. If the traversal is finished, then this operation returns a special value (0, for instance) that marks the end of the iteration.) </p>
<p>Some additional operations might prove useful. For example, ordered aggregates can have a Previous operation that positions the iterator to the previous element. A SkipTo operation is useful for sorted or indexed collections. SkipTo positions the iterator to an object matching specific criteria.</p>
</li>
<li><p><em>Using polymorphic iterators in C++.</em> (I think this is irrelevant for js or python) Polymorphic iterators have their cost. They require the iterator object to be allocated dynamically by a factory method. Hence they should be used only when there’s a need for polymorphism. Otherwise use concrete iterators, which can be allocated on the stack.</p>
<p>Polymorphic iterators have another drawback: the client is responsible for deleting them. This is error-prone, because it’s easy to forget to free a heap-allocated iterator object when you’re finished with it. That’s especially likely when there are multiple exit points in an operation. And if an exception is triggered, the iterator object will never be freed.</p>
<p>The Proxy pattern provides a remedy. We can use a stack-allocated proxy as a stand-in for the real iterator. The proxy deletes the iterator in its destructor. Thus when the proxy goes out of scope, the real iterator will get deallocated along with it. The proxy ensures proper cleanup, even in the face of exceptions. This is an application of the well-known C++ technique “resource allocation is initialization” [ES90]. The Sample Code gives an example.</p>
</li>
<li><p><em>Iterators may have privileged access.</em> An iterator can be viewed as an extension of the aggregate that created it. The iterator and the aggregate are tightly coupled. We can express this close relationship in C++ by making the iterator a friend of its aggregate. Then you don’t need to define aggregate operations whose sole purpose is to let iterators implement traversal efficiently.</p>
<p>However, such privileged access can make defining new traversals difficult, since it’ll require changing the aggregate interface to add another friend. To avoid this problem, the Iterator class can include protected operations for accessing important but publicly unavailable members of the aggregate. Iterator subclasses (and only Iterator subclasses) may use these protected operations to gain privileged access to the aggregate.</p>
</li>
<li><p><em>Iterators for composites.</em> External iterators can be difficult to implement over recursive aggregate structures like those in the Composite pattern, because a position in the structure may span many levels of nested aggregates. Therefore an external iterator has to store a path through the Composite to keep track of the current object. Sometimes it’s easier just to use an internal iterator. It can record the current position simply by calling itself recursively, thereby storing the path implicitly in the call stack.</p>
<p>If the nodes in a Composite have an interface for moving from a node to its siblings, parents, and children, then a cursor-based iterator may offer a better alternative. The cursor only needs to keep track of the current node; it can rely on the node interface to traverse the Composite.
Composites often need to be traversed in more than one way. Preorder, postorder, inorder, and breadth-first traversals are common. You can support each kind of traversal with a different class of iterator.</p>
</li>
<li><p><em>Null iterators.</em> (wow a base case) A NullIterator is a degenerate iterator that’s helpful for handling boundary conditions. By definition, a NullIterator is always done with traversal; that is, its IsDone operation always evaluates to true.</p>
<p>NullIterator can make traversing tree-structured aggregates (like Composites) easier. At each point in the traversal, we ask the current element for an iterator for its children. Aggregate elements return a concrete iterator as usual. But leaf elements return an instance of NullIterator. That lets us implement traversal over the  entire structure in a uniform way.</p>
<h3 id="sample-code">Sample code</h3>
<p>in book as C++, me trying to rewrite in python3</p>
<h3 id="known-uses">Known Uses</h3>
<p>Iterators are common in object-oriented systems. Most collection class libraries offer iterators in one form or another. So, refer to docs on collections for your language of choice?</p>
<h3 id="related-patterns">Related Patterns</h3>
</li>
</ol>
<p>Composite: Iterators are often applied to recursive structures such as Composites.
Factory Method: Polymorphic iterators rely on factory methods to instantiate the appropriate Iterator subclass.
Memento: is often used in conjunction with the Iterator pattern. An iterator can use a memento to capture the state of an iteration. The iterator stores the memento internally.</p>
]]></description>
        </item>
        <item>
            <title><![CDATA[Studying Design Patterns]]></title>
            <link>https://velog.io/@lucid_fizz/Studying-Design-Patterns</link>
            <guid>https://velog.io/@lucid_fizz/Studying-Design-Patterns</guid>
            <pubDate>Thu, 02 Mar 2023 09:43:02 GMT</pubDate>
            <description><![CDATA[<p>Design Patterns (1994) -GoF is a big book.
It is more of a catalog then a textbook to read. It introduces 23 most commonly used design patterns.
(btw, If you are interested, buy the book and read it. It is also available in Google Books as ebook.)</p>
<p>We are a team of 1~2 yr junior devs, so faced w/ a 450 page book, my study group was overwhelmed. Thankfully, there is a <strong>Guide to readers</strong> section, which tells you some of the approaches you can take to this book. You can read the 8 most basic patterns: Abstract Factory, Adapter, Composite, Decorator, Factory Method, Observer, Strategy, Template Method. Or follow w/ <strong>ch2 case study</strong>, which introduces total of 8 patterns, w/ 4 of them also included in Guide to Readers section. Or you can start from one pattern and propagate to other related patterns. </p>
<p>But whichever apporach you take, the end result you want is this: When a problem arises in your daily SW development, you can think of patterns that can solve this problems. You may need to adapt it a bit, like mixing a few patterns together or being smart w/ your implementation. But the key thing is you have a instant pattern match to your problem you can build on. </p>
<p>Our group took the case study route. It was because we wanted to see an actual example of design patterns application. But I don&#39;t think it was the optimal way.</p>
<p>The upside of this choice is that it gives you some place to start on the book. It is a 450 page book, w/ about 350 pages being catalog of popular software Design Patterns. Unless you are experienced in both SW and reading, it can be overwhelming. It was for me.</p>
<p>But there was also downside. While reading through [ch2, A Case Study: Designing a Document Editor], we realized the book is 30 yrs old. So the case study was not relatable albeit being a good example. Also, you have to read 50 page of detailed explanations, so it is some reading. A single pattern catalog takes ~12 pages (i think), so if you wish you could have read at least 4 more patterns. </p>
<p>There are also some augmentations you can take, like accompany an online course in the language of your choice. This book came out 30 yrs ago. The example screenshots are old. C++ is old. I mean it is still used extensively, but there can be better examples. If you are doing web dev or ML, C++ is probably not what you would learn. All the catalogs are also in C++. But then again, it also means there are many good online courses in Java, JS, Python, Rust etc.</p>
<p>Now it is the last week of this study, and I think I at least indexed the 8 patterns mentally.  Starting from these 8 patterns, I can stem from it as needed, checking out related patterns.</p>
<p>===
This was my 2nd study at this company, following Refactoring 2nd ed by Martin Fowler. We studied a subsection each week, met at lunch and discussed points. </p>
]]></description>
        </item>
        <item>
            <title><![CDATA[Command Pattern]]></title>
            <link>https://velog.io/@lucid_fizz/Command-Pattern</link>
            <guid>https://velog.io/@lucid_fizz/Command-Pattern</guid>
            <pubDate>Fri, 24 Feb 2023 10:36:13 GMT</pubDate>
            <description><![CDATA[<p><em>study of Design Patterns (1994). Diagrams are scanned from original text</em></p>
<h3 id="intent">Intent</h3>
<p>Encapsulate request as an object, thereby letting you parameterize clients with difference requests, queue or log requests, and support undoable operations</p>
<h3 id="also-known-as">Also Known As</h3>
<p>Action, Transaction</p>
<h3 id="motivation">Motivation</h3>
<p>Sometimes it’s necessary to issue requests to objects without knowing anything about the operation being requested or the receiver of the request.</p>
<p>Here, <code>Menuitem</code> will have reference to a <code>Command</code>&#39;s instance, <code>command</code>. <code>command.execute()</code> will be called when this <code>MenuItem</code> is clicked.  <img src="https://velog.velcdn.com/images/lucid_fizz/post/c884170d-3101-4f03-96b0-9e7c5107d3de/image.png" alt="">
But <code>MenuItem</code> doesn&#39;t need to know about details of <code>Execute()</code>. It suffices to know that it will cause some expected consequence.</p>
<p>Also, different kind of <code>MenuItem</code> will have reference to different type of <code>Command</code> objects. But it doesn&#39;t matter. <code>MenuItem</code> will just call <code>MenuItem.Command.Execute()</code>. </p>
<p>Then <code>Command</code> subclasses will store reference to receiver of the request, and invoke operations on the receiver as needed. Ex. a <code>PasteCommand</code> could have reference to a <code>Document</code> object, which is supplied to <code>PasteCommand</code> at instantiation. When <code>Execute()</code> is called on <code>PasteCommand</code>, it will run some operations (maybe <code>Document.Paste()</code>) to receiver.<img src="https://velog.velcdn.com/images/lucid_fizz/post/23f3e440-385c-45a8-9bb9-bf039a159877/image.png" alt=""></p>
<p>However, <code>OpenCommand</code>&#39;s <code>Execute()</code> will do different operations like below. 
<img src="https://velog.velcdn.com/images/lucid_fizz/post/f5f66d0f-535c-4216-8937-1d5aa387f706/image.png" alt=""></p>
<p>And sometimes, a <code>MenuItem</code> needs to execute a <em>sequence</em> of commands. Then we can create a macro, <code>MacroCommand</code>, which has a sequence of <code>Command</code> objects that runs in sequence. But this <code>MacroCommand</code> needn&#39;t keep a reference to receiver of commands, as each <code>Command</code> will have that.
<img src="https://velog.velcdn.com/images/lucid_fizz/post/06f4934c-3bd2-4210-b8bb-f505b55e6cf9/image.png" alt=""></p>
<p>In each of these examples, notice how the Command pattern decouples operation invoker object from operation performer object. This will give a lot of flexibility in desiging UI. (I guess this is lot like ReactJS hooks?). We can also change commands dynamically, especially for context-sensitive menus. We can also support command scripting by composing commands into larger ones.</p>
<p> All of this is possible because the object that issues a request only needs to know how to issue it; it doesn’t need to know how the request will be carried out.</p>
<h3 id="applicability">Applicability</h3>
<p>Use the Command Pattern when you want to:</p>
<ul>
<li>Parameterize objects by an action to perform. You can express such parameterization in a procedural language with a <strong>callback</strong> function. Commands are object-oriented replacement for callbacks.</li>
<li>specify, queue, and execute requests at different times. A command object can have a lifetime independent of the original request. If the receiver of a request can be represented in an address-space independent way, then you can transfer a command object forthe request to a different process and fulfill the request there</li>
<li>support undo. <code>Command.Execute()</code> can store state for reversing its effects in the command itself. then <code>Command</code> interface must have sth like <code>Unexecute()</code>. Executed command are stored in a history list. You can have unlimited-level undo and redo if you want to, by traversing this history list of commands.</li>
<li>support logging changes so that they can be reapplied in case of a system crash. Augment <code>Command</code> interface w/ load/store operations, so you can keep a persistent log of changes. When it crashes, reload logged commands from disk and reexecute them in order. I guess this works in simple cases?</li>
<li>strucute a system around high-level operations built on primitives operations. Such a structure is common in information system that support <strong>transactions</strong>. A transaction encapsulates a set of changes to data. The Command pattern offers a way to model transaction. Commands have a common interface, letting you invoke all transactions the same way. Also makes it easy to extend the system with new transactions.<h3 id="structure">Structure</h3>
<img src="https://velog.velcdn.com/images/lucid_fizz/post/594117cc-4203-42de-a7b7-03f6cdb9ea58/image.png" alt=""><h3 id="participants">Participants</h3>
</li>
<li><code>Command</code><ul>
<li>declares an interface for executing an operation.</li>
</ul>
</li>
<li><code>ConcreteCommand</code> (<code>PasteCommand</code>, <code>OpenCommand</code>)<ul>
<li>defines a binding between a <code>Receiver</code> object and an action.</li>
<li>Implements <code>Execute()</code> by invoking necessary operations on <code>Receiver</code>.</li>
</ul>
</li>
<li><code>Client</code> (<code>Application</code>)<ul>
<li>creates a <code>ConcreteCommand</code> object and sets its receiver.</li>
</ul>
</li>
<li><code>Invoker</code> (<code>MenuItem</code>)<ul>
<li>asks the command to carry out the request.</li>
</ul>
</li>
<li><code>Receiver</code> (<code>Document</code>, <code>Application</code>)<ul>
<li>knows how to perform the operations with carrying out a request. Any object can be a receiver.<h3 id="collaborations">Collaborations</h3>
</li>
</ul>
</li>
<li>The client creates a <code>ConcreteCommand</code> object and specifies its receiver.</li>
<li>An <code>Invoker</code> object stores the <code>ConcreteCommand</code> object.</li>
<li>The invoker issues a command by doing <code>Invoker.Command.Execute()</code>. If commands are undoable, <code>ConcreteCommand</code> will store state for undoing the command prior to invoking <code>Execute()</code></li>
<li>The <code>ConcreteCommand</code> object invokes operations on its receiver to carry out the request.</li>
</ul>
<p>The following diagram shows the interactions between these objects. It illustrates how Command decouples the invoker from the receiver (and the request it carries out).<img src="https://velog.velcdn.com/images/lucid_fizz/post/496446a8-9b89-4912-8077-55d1bf332b7d/image.png" alt=""></p>
<h3 id="consequences">Consequences</h3>
<ol>
<li>Command decouples invoker from receiver.</li>
<li>Commands are first-class objects. They can be manipulated and extended like any other objects.</li>
<li>You can assemble commands into a composite command. An example is the <code>MacroCommand</code> class described earlier. In general, composite commands are an instance of the Composite Pattern.</li>
<li>Easy to add new commands, because you don&#39;t have to change existing classes.</li>
</ol>
<h3 id="implementation">Implementation</h3>
<ol>
<li><em>How intelligent should a command be?</em> One extreme can make command merely a binding between a receiver and the actions that carry out the request. Another extreme it implements everything itself w/o delegating to a receiver at all. The latter extreme is useful when you want to:</li>
</ol>
<ul>
<li>define commands that are independent of existing classes.</li>
<li>no suitable receiver exists</li>
<li>command knows its receiver explicitly.
For example, a command that creates another application window may be just as capable of creating the window as any other object. 
Somewhere in between the two extremes are commands that have enough knowledege to find their receiver dynamically.</li>
</ul>
<ol start="2">
<li><em>Supporting undo and redo</em>. Commands can support undo and redo capabilities if they provide a way to reverse their execution (ex. <code>Unexecute()</code>, <code>Undo()</code>). A <code>ConcreteCommand</code> class might need to store additional state to do so. This state can include:</li>
</ol>
<ul>
<li>the <code>Receiver</code> object, which actually carries out operations in response to the request.</li>
<li>the arguments to the operation performed on the receiver</li>
<li>any original values in the receiver that can change as a result of handling the request. The receiver must provide operations that let the command return the receiver to its prior state.</li>
</ul>
<p>Usually <strong>history list</strong> of commands that have been executed is kept, w/ reasonable size limit. Traverse thru the list and call <code>Execute()</code>/<code>Unexecute()</code> as needed.</p>
<p>An undoable command might have to be copied before it can be placed on the history list. That&#39;s because the command object that carried out the original request, will perform other requests at later times. Copying is required to distinguish different invoacations of the same command if its state can vary across invocations.</p>
<p>For example, a <code>DeleteCommand</code> that deletes selected objects must store different sets of objects each time it&#39;s executed. Therefore the <code>DeleteCommand</code> object must be copied following execution, and the copy is placed on the history list. If the command&#39;s state doesn&#39;t change, keeping a reference to it in the object is enough. Commands that must be copied before being placed on the history list act as prototypes.</p>
<ol start="3">
<li><p><em>Avoiding error accumulation in the undo process.</em> Hysterisis can be a problem in ensuring a reliable semantics-preserving undo/redo mechanism. Erros can accumulate as commands are executed, unexecuted, and reexecuted repeatedly so that an application&#39;s state eventually diverges from original values. It may be necessary therefor to store more info in the command to ensure that objects are restored to their original state. The Memento Pattern can be applied to give the command access to this info w/o exposing the internals of other objects.</p>
</li>
<li><p><em>Using C++ Templates.</em> For commands that aren&#39;t undoable &amp;&amp; don&#39;t require arguments. Shown in Sample Code section.</p>
</li>
</ol>
<h3 id="sample-code">Sample Code</h3>
<p>Book C++, me python.
not sure what using C++ templates meant above.</p>
<h3 id="known-uses">Known Uses</h3>
<p>some papers, old examples. someting about <strong>functors</strong>, bojects that are functions.</p>
<h3 id="related-patterns">Related Patterns</h3>
<p>Composite Pattern to implement MacroCommands
Memento Pattern to keep state the command requires for undoing operations.
Prototype Pattern for commands that must be copied before being placed on the history list.</p>
]]></description>
        </item>
        <item>
            <title><![CDATA[Bridge Pattern]]></title>
            <link>https://velog.io/@lucid_fizz/Bridge-Pattern</link>
            <guid>https://velog.io/@lucid_fizz/Bridge-Pattern</guid>
            <pubDate>Wed, 22 Feb 2023 07:37:22 GMT</pubDate>
            <description><![CDATA[<p><em>study of Design Patterns (1994)</em></p>
<h3 id="intent">Intent</h3>
<p>Decouple an abstraction from its implementation so that the two can vary independently.</p>
<h3 id="also-known-as">Also Known As</h3>
<p>Handle/Body</p>
<h3 id="motivation">Motivation</h3>
<p>Inheritance is usually the way when an abstraction can have several implementations. Sometimes it is not flexible enough. </p>
<p>Say, <code>Window</code> abstract class has many product subclasses <code>IconWindow</code>, <code>ButtonWindow</code> etc. Then, to support platforms, you have explosion of subclasses. <code>(# of product kind) x (# of platforms to support)</code>. Better managed in two hiearchies <code>Window</code> for type, <code>WindowImpl</code> for platform.</p>
<p>Also, client code becomes dependent on the platform. for example , to use window on macOS, you would need to instantiate <code>MacIconWindow</code>, <code>MacButtonWindow</code> etc., not just <code>IconWindow</code> or <code>ButtonWindow</code>. This makes porting really difficult. Clients should be able to create a window w/o commiting to a concrete information. i.e. instantiate windows w/o mentioning specific platforms.
<em>diagram from book</em>
<img src="https://velog.velcdn.com/images/lucid_fizz/post/a324e29a-88ba-4992-88e5-b675cdda61d0/image.png" alt="">
This relationship between <code>Window</code> and<code>WindowImpl</code> abstract classes is Bridge.</p>
<h3 id="applicability">Applicability</h3>
<p>Use when</p>
<ul>
<li>You want to avoid a permanent binding between abstraction and its implementaion. For example, when implementaion must be selected or switched at run-time.</li>
<li>Both the abstraction and implementation should be extensible by subclassing. Birdge Pattern lets you combine different abstracion and implementaions and also extend them independently.<h3 id="structure">Structure</h3>
<img src="https://velog.velcdn.com/images/lucid_fizz/post/50195fc2-ddb9-4d58-90e7-62290909bf93/image.png" alt=""><h3 id="participants">Participants</h3>
</li>
<li>Abstraction (Window)<ul>
<li>defines the abstraction&#39;s interface</li>
<li>maintains a reference to an object of type Implementor.</li>
</ul>
</li>
<li>RefmedAbstraction (IconWindow)<ul>
<li>extends the interface defined by Abstraction.</li>
</ul>
</li>
<li>Implementor (WindowImp)<ul>
<li>Defines the inteerface for implementaion classes. Doesn&#39;t have to correspond exactly to Abstraction&#39;s interface; can be different. </li>
<li>Typically, Implementor defines primitives, Abstraction has higher-level operations based on these primitives.</li>
</ul>
</li>
<li>ConcreteImplementor (XWindowImp, PMWindowImp)<ul>
<li>implements the Implementor interface and defines its concrete implementation<h3 id="collaborations">Collaborations</h3>
</li>
</ul>
</li>
<li>Abstraction forwards client requests to its Implementor object.<h3 id="consequences">Consequences</h3>
</li>
</ul>
<ol>
<li><em>Decoupling interface and implementation</em>. An implementation is not bound permanently to an interface. It can be configured at run-time. Even possible to change its implementation at run-time.</li>
</ol>
<p>Also eliminates compile-time dependencies. Changing an implementation class doesn’t require recompiling the Abstraction class and its clients. Essential when binary compatibility for difference versions of a class library.</p>
<p>Encourage layering that can lead to a better-structured system.</p>
<ol start="2">
<li><em>Improved Extensibility</em>. You can extend the Abstraction and Implementor hiearchies independently.</li>
<li><em>Hiding implementation details from clients</em>. Hide stuff like sharing of implementor objects and the accompanying reference count mechanism (if any).<h3 id="implementation">Implementation</h3>
</li>
<li><em>Only one Implementor</em>. then its a degenerate case. why bother? but still can be useful when a change in implementation of a class must not effect existing clients (ie. when recompile no, but relink ok). In C++, can hide class interface of Implementor class in a private header file that isn&#39;t provided to clients.</li>
<li><em>Creating the right Implementor object</em>. 
If Abstraction know about all ConcreteImplementor classes, then it can instantiate one of them in its constructor, i.e. decide using parameters passed to its constructor. ex. a collection class takes small <code>size</code>, then use linked list. if larger <code>size</code>, hash table etc.</li>
</ol>
<p>Another approach is to choose a default, then change it later accordingly. ex. If collection grows too big, change to hash table.</p>
<p>Also possible to delegate the decision to another oject altogeter. In the Window/WindowImp example, we can introduce a factory object (see Abstract Factory (87)) whose sole duty is to encapsulate platform-specifics. The factory knows what kind of WindowImp object to create for the platform in use; a Window simply asks it for a WindowImp, and it returns the right kind. A benefit of this approach is that Abstraction is not coupled directly to any of the Implementor classes.</p>
<ol start="3">
<li><p><em>Sharing implementors</em>. 
from book about reference count managing for shared Implementors.</p>
<pre><code class="language-cpp">Handle&amp; Handle::operator= (const Handle&amp; other) {
 other._body-&gt;Ref();
 _body-&gt;Unref();

 if(_body-&gt;RefCount() == 0_ {
     delete _body;
 }
 _body = other._body;

 return *this;
</code></pre>
</li>
</ol>
<p>```
4. <em>Using multiple inheritance</em>. In C++, you can use multiple inheritance to combine an interface with its implementaion. Possible in typescript and python too. Ex. a class can inherit publicly from Abstraction, and privately from a ConcreteImplementor. But this relies on static inheritance, binding implementation to its interface. Therefore you can&#39;t implement a true Bridge w/ multiple inheritance, at least not in C++.</p>
<h3 id="sample-code">Sample Code</h3>
<p>In book, C++. I rewrite it in python3 skipping details.</p>
<h3 id="known-uses">Known Uses</h3>
<p>only skim thru. What is an ET++? libg++? NXImage?</p>
<h3 id="related-patterns">Related Patterns</h3>
<p>Abstract Factory to create and configure a particular Bridge.
The Adapter pattern is geared toward making unrelated classes work together. It is usually applied to systems after they’re designed. Bridge, on the other hand, is used up-front in a design to let abstractions and implementations vary independently.</p>
]]></description>
        </item>
        <item>
            <title><![CDATA[import vs require in Javascript]]></title>
            <link>https://velog.io/@lucid_fizz/import-vs-require-in-Javascript</link>
            <guid>https://velog.io/@lucid_fizz/import-vs-require-in-Javascript</guid>
            <pubDate>Mon, 20 Feb 2023 06:06:14 GMT</pubDate>
            <description><![CDATA[<h3 id="some-history">Some history</h3>
<p>Javascript language specification is standardized, by ECMAScript specification.
the ES in ES6 is short for ECMAScript</p>
<p>In ES6, which is the current standard for javascript, using <code>import</code> is the standard.</p>
<p>However, in nodeJS, we often see <code>require</code> to use modules. This is because before ES6 standard, nodeJS introduced CommonJS as its standard, and this used <code>require</code> to use modules.</p>
<h3 id="comparison">Comparison</h3>
<p>So currently, it is recommended to use <code>import</code>.
Some of its advantages are</p>
<ul>
<li>The ES6 standard </li>
<li><code>import</code> is determined at compile time, asynchronously. so enables:<ul>
<li>Support for static analysis -&gt; debuggin</li>
<li>tree shaking -&gt; removed unused code</li>
<li>dynamic code loading. uses <code>Promise</code> to resolve module imports</li>
</ul>
</li>
<li>can import only needed part of module.</li>
</ul>
<p>But we still need to konw <code>require</code>
as it </p>
<ul>
<li>still legacy code base uses this.</li>
<li>enables dynamic loading of modules at runtime.<h4 id="miscellaneous">Miscellaneous</h4>
I hear it is pain to create a js module that can handle both <code>import</code> and <code>require</code>. </li>
</ul>
]]></description>
        </item>
        <item>
            <title><![CDATA[correcting  unmocked  jest functions]]></title>
            <link>https://velog.io/@lucid_fizz/typescript-module-imports</link>
            <guid>https://velog.io/@lucid_fizz/typescript-module-imports</guid>
            <pubDate>Mon, 20 Feb 2023 05:35:53 GMT</pubDate>
            <description><![CDATA[<h3 id="problem">Problem</h3>
<p>function mocking using jest fails</p>
<h4 id="description">description</h4>
<p>file A - class <code>Scanner</code> has <code>Scanner.useScan()</code> method, that uses <code>scan()</code> from fileB, but is not injected as parameted, and used using <code>import</code>.
file B - has <code>export const scan = () =&gt; {}// omit</code> arrow function
test T - tests <code>Scanner</code> class from file A, including <code>useScan()</code></p>
<p>in T, <code>scan</code> is imported using <code>import {scan} from &#39;./B&#39;</code>
then mocked using jest</p>
<pre><code class="language-ts">// T.spec.ts
jest.mock(&#39;./B&#39;, () =&gt; ({
  scan : jest.fn()
})</code></pre>
<p>however, original function from file B, not the mocked function, is used when testing. This is because we can&#39;t DI <code>scan()</code> function at test file, and is instead imported from file A. </p>
<pre><code class="language-ts">// A.ts
import {scan} from &#39;./B&#39;</code></pre>
<h3 id="reason">Reason</h3>
<p><code>import {scan} from &#39;./B&#39;</code>
and
<code>import * as scanModule from &#39;./B&#39;</code>
has different internal workings.
first one imports only the function to a variable. So if we mock it, it will stay inside current context.
However, second one imports the entire module as an object. So if we mock it, the mocked module will be use even if it is used in a different file.</p>
<h3 id="solution">Solution</h3>
<h4 id="1-use-dependency-injection-imo-best-practice">1. Use Dependency Injection (IMO Best Practice)</h4>
<p>If <code>useScan()</code> takes <code>scan()</code> as argument,</p>
<pre><code class="language-ts">// A.ts
// import {scan} from &#39;./B&#39;
class Scanner {
  ////
  useScan(scanFunc: scanFuncType){
   ////
    scanFunc() // omit detai;s
  }</code></pre>
<p>we can use mocked version of <code>scan()</code> as argument for <code>useScan()</code> instead of actual<code>scan()</code> in test file</p>
<h4 id="2-mock-the-entire-module-in-test-file">2. mock the entire module in test file</h4>
<p>do either</p>
<ul>
<li>import entire module and mock the functions you want.<pre><code class="language-ts">// T.spec.ts
import * as ScanModule from &#39;./B&#39;
</code></pre>
</li>
</ul>
<p>jest.mock(&#39;./B&#39;, ()=&gt;({
 scan: jest.fn() 
  }))</p>
<pre><code>- mock the module before importing function (**not verified**)
```ts
// T.spec.ts
jest.mock(&#39;/B&#39;)
import {scan} from &#39;./B&#39;</code></pre><p>then test </p>
<p>```ts
// T.spec.ts
describe(&#39;useScanner&#39;, () =&gt;{
    testScanner.useScan() // now uses mocked version of <code>scan()</code>
    expect(scan).toHaveBeenCalled() // <code>scan</code> name can vary
})</p>
]]></description>
        </item>
        <item>
            <title><![CDATA[Duplicate files in the git repo on macOS]]></title>
            <link>https://velog.io/@lucid_fizz/Duplicate-files-in-the-git-repo-on-macOS</link>
            <guid>https://velog.io/@lucid_fizz/Duplicate-files-in-the-git-repo-on-macOS</guid>
            <pubDate>Thu, 16 Feb 2023 05:46:27 GMT</pubDate>
            <description><![CDATA[<h4 id="my-problem">My Problem</h4>
<p>when using git on macOS, duplicate files appeared after switching branches.</p>
<h4 id="solution">Solution</h4>
<p>move your git repo to somewhere not tracked by iCloud</p>
<h4 id="mechanism">Mechanism</h4>
<p>iCloud watches registered directories.  When git sweeps files to change branches etc, iCloud will also detect a file change, and try to its own synching routine. Underlying process depends on its synching routine/algorithm.</p>
<h4 id="explanation">Explanation</h4>
<p>Don&#39;t use together a file synching service (iCloud, Dropbox, Google Drive eetc.) and a version control (git, svc etc.). Will run into duplicates. if you use repository hosting service like github, gitlab, Bitbucket), you alreaday get avilability and security you are getting from iCloud.</p>
<h5 id="reference">reference</h5>
<p><a href="https://stackoverflow.com/questions/59308049/icloud-drive-desktop-sync-vs-git-deleted-files-reappear-and-duplicates-with-n">https://stackoverflow.com/questions/59308049/icloud-drive-desktop-sync-vs-git-deleted-files-reappear-and-duplicates-with-n</a>
<a href="https://stackoverflow.com/questions/62385234/git-keeps-duplicating-files-and-appending-2-at-end-of-filename">https://stackoverflow.com/questions/62385234/git-keeps-duplicating-files-and-appending-2-at-end-of-filename</a></p>
]]></description>
        </item>
        <item>
            <title><![CDATA[Abstract Factory Pattern]]></title>
            <link>https://velog.io/@lucid_fizz/Abstract-Factory-Pattern</link>
            <guid>https://velog.io/@lucid_fizz/Abstract-Factory-Pattern</guid>
            <pubDate>Wed, 15 Feb 2023 05:12:31 GMT</pubDate>
            <description><![CDATA[<h3 id="intent">Intent</h3>
<p>Provide an interface for creating families of related or dependent objects, w/o specifiying their concrete classes.</p>
<h3 id="also-known-as">Also Known As</h3>
<p>Kit</p>
<h3 id="motivation">Motivation</h3>
<p>To enable easy changing of the look, feel of an application. Also clients should stay independent of the prevailing look and feel. <code>WidgetFactory</code> is the topmost abstract class. There will be concrete subclass of <code>WidgetFactory</code> for each look-and-feel standard. ex. <code>MotifWidgetFactory</code>, which returns a Motif scroll bar. <code>PMWidgetFactory</code>, returning a scroll bar for Presentaion Manager.<img src="https://velog.velcdn.com/images/lucid_fizz/post/e8de4b74-f201-4d4f-8b03-503ec5aa7bb2/image.png" alt="">
Clients have no idea of <code>WidgetFactory</code> interface. Only use instance of the concrete subclasses, but adhere to interface defined by the abstract class <code>WidgetFactory</code>.</p>
<h3 id="applicability">Applicability</h3>
<ul>
<li>A system should be independent of how its products are created, composed, and represented.</li>
<li>A system should be configured with one of multiple families of products.</li>
<li>A family of related product objects is designed to be used together, and you need to enforce this constraint.</li>
<li>You want to provide a class library of products, and want to reveal interfaces only, not implementation<h3 id="structure">Structure</h3>
<img src="https://velog.velcdn.com/images/lucid_fizz/post/50d58908-bbe9-4f29-8741-3bd3d8b7b4dc/image.png" alt=""><h3 id="participants">Participants</h3>
</li>
<li>AbstractFactory (WidgetFactory)<ul>
<li>declares an interface for operations that create abstract product objects.</li>
</ul>
</li>
<li>ConcreteFactory (MotifWidgetFactory, PMWidgetFactory)<ul>
<li>implements the operations to create concrete product objects.</li>
</ul>
</li>
<li>AbstractProduct (Window, ScrollBar)<ul>
<li>declares an interface for a type of product object.</li>
</ul>
</li>
<li>ConcreteProduct (MotifWindow, MotifScrollBar)<ul>
<li>defines a product object to be created by the corresponding concrete factory.<ul>
<li>implements the AbstractProduct interface.</li>
</ul>
</li>
</ul>
</li>
<li>Client<ul>
<li>Only use interfaces defined by <code>AbstratFactory</code> and <code>AbstractProduct</code> <h3 id="collaborations">Collaborations</h3>
<ul>
<li>Normally a single instance of a <code>ConcreteFactory</code> class is created at run-time. Of course. its a factory. Creates one kind of product. If client wants different product, use another factory.</li>
<li><code>AbstractFactory</code> defers creation of product objects to its <code>ConcreteFactory</code> subclass.<h3 id="consequences">Consequences</h3>
Benefits &amp; Liabilities</li>
</ul>
</li>
</ul>
</li>
</ul>
<ol>
<li><em>It isolates concrete classes</em>. Product class names are isolated in the implementation of the concrete factory. not in client code.</li>
<li>_ It makes exchangin product families easy_. The class of concrete factory appears only once in an application, where it&#39;s instantiated. So no duplicate code change when changin concrete factory to use. </li>
<li><em>Promotes consistency among products</em>. <code>AbstractFactory</code> enforcement.</li>
<li><em>Supporting new kinds of products is difficult</em>. Fixed interface. What if new product requires extended interface? hard. Lots of code to change. But one possible solution in Implementaion section.<h3 id="implementation">Implementation</h3>
Some useful techniques for implementing the Abstrat Factory pattern.</li>
<li><em>Factories as singletons</em>.</li>
<li><em>Creating the products</em>. See Factory Method pattern for each product. This overrides I think the <code>constructor()</code> for product classes? 
If many product families are possible, refer to Prototype pattern. A <code>javascript</code> like pattern I think. 
<em>Pure Prototype apporach</em>
Concrete factory has protype of a product. Factory clones the prototype, and creates the product. Eliminates the need for a new concrete factory calss for each new product family. 
<em>Prototype variant</em>
Possible in languages that treat classes as first-class objects. Define a new factory by initializing an instance of concrete factory with classes of products, not by subclassing.  This approach takes advantage of language characteristics, whereas the pure Prototype-based approach is language-independent.</li>
<li><em>Defining extensible factories</em>. <code>AbstractFactory</code> usually defines a different operation for each kind of product it can produce. The kinds of products are encoded in the operation signatures. Adding a new kind of product requires changin the AbstractFactory interface and all the classes that depend on it.</li>
</ol>
<ul>
<li>A more flexible, but less safe design is to add a parameter to operations that create objects. This parameter specified the kind of object to be created. Can be class identifier, integer, whatever. Then <code>AbstractFactory</code> would only need a single <code>make()</code> method with a parmeter indicating the kind of object to create. This is the technique used in the Prototype- and the class-based abstract factories discuessed earlier.  </li>
<li>This variation is easier to use in a dynamically typed language (js, python). </li>
<li>A inherent problem: All products are returned to the client with the same abstract interface as given by the return type. The client will not be able to differentiate or mkae safe assumptions about the class of a product. If clients need to perform subclass-specific operations, they won&#39;t be accessible through the abstract interface. Could do a downcast, but not always feasible or safe, as downcast can fail. This is a classic trade-off for a highly flexible and extensible interface.<h3 id="sample-code">Sample Code</h3>
in C++ in books.
if you want dynamic language example, there is also SmallTalk example. But you have to know the C++ example first to understand.<h3 id="known-uses">Known Uses</h3>
Old cases.. Interviews? ET++?<h3 id="related-patterns">Related Patterns</h3>
implement using Factory Method, or Prototype
A concrete factory is often a Singleton.</li>
</ul>
]]></description>
        </item>
        <item>
            <title><![CDATA[Decorator Pattern]]></title>
            <link>https://velog.io/@lucid_fizz/Decorator-Pattern</link>
            <guid>https://velog.io/@lucid_fizz/Decorator-Pattern</guid>
            <pubDate>Mon, 13 Feb 2023 10:54:02 GMT</pubDate>
            <description><![CDATA[<p>Yes, this is the decorators we use.</p>
<pre><code class="language-py">@some_decorator
def some_function():
    pass</code></pre>
<h3 id="intent">Intent</h3>
<p>Dynamic attachment of responsibilities to an object. A flexible alternative to subclass for extending functionality.</p>
<h3 id="also-known-as">Also Known As</h3>
<p>Wrapper</p>
<h3 id="motivation">Motivation</h3>
<p>For adding responsibilities to individual objects, but not to an entire class. We can do this w/ inheritance. However, if this <code>responsibility(A)</code> can be decided statically, we can be more flexible and enclose the <code>component</code> in another object that does <code>A</code>. We call this enclosing object <code>Decorator</code>.</p>
<p><code>Decorator</code> conforms to the interface of the <code>component</code> it decorates, so that its prescence is transparent to the <code>component</code>&#39;s clients. This <code>Decorator</code> forwards requests to the <code>component</code>&#39;s clients and optionally perform additional actions before/after forwarding. Transparency lets you neset decorators recursively, theoretically unlimited amount. Some example involving text editor is in book.</p>
<p>Again, transparenct allows clients to not depend at all on the decoration.</p>
<h3 id="applicability">Applicability</h3>
<p>Use Decorator</p>
<ul>
<li>to add responsibilities to individual objects dynamically and transparently. i.e. w/o affecting other objects</li>
<li>for responsibilities that can be withdrawn.</li>
<li>when extension by subclassing is impractical. Sometimes a large number of independent extensions are possible and would produce explosion of subclasses to support every combination. Or a class definition may be hidden or otherwise unavailable for subclassing.<h3 id="structure">Structure</h3>
</li>
<li>diagram from book*
<img src="https://velog.velcdn.com/images/lucid_fizz/post/ded73e58-98df-4fe0-83a7-8791aea6d464/image.png" alt=""><h3 id="participants">Participants</h3>
</li>
<li><em>Component*</em> </li>
<li>Defines the interfact for objects that can have responsibilities added to them dynamically.</li>
</ul>
<p><strong>ConcreteComponent</strong> </p>
<ul>
<li>Defines and object, where additional responsibilities can be attached.</li>
</ul>
<p><strong>Decorator</strong></p>
<ul>
<li>maintains a reference to <code>Component</code> object</li>
<li>defines an interface that conforms to <code>Component</code>&#39;s interface</li>
</ul>
<p><strong>ConcereteDecorator</strong></p>
<ul>
<li>adds responsibilities to the component.<h3 id="collaborations">Collaborations</h3>
Decorator forwards requests to its <code>Component</code> object. It may optionally perform additional operations before/after forwarding the request<h3 id="consequences">Consequences</h3>
At least 2 key benefits and 2 liabilities:</li>
</ul>
<ol>
<li><em>More flexibility then static inheritance</em>. Instead of creating a class for each responsibility, use decorators to add/remove responsibility at runtime simply by attaching and detaching them. Also, by mixing decorators you can also mix and match responsibilities.</li>
<li><em>Avoids feature-laden classes high up in the hiearchy</em>. Decorators add pay-as-you-go approach to adding responsibilities. Instead of trying to support all foreseeable features in a complex, customizable class, you can define a simple class and add functionality incrementally with Decorator objects. A functionality compose of many responsibilities can be made from simple pieces, the decorator. Thus, application need not pay for features it don&#39;t use. Even when unforseen extensions arise, they can be added independently from the classes of objects they extend. Extending a complex class may expose details unrelated to the responsibilities you&#39;re adding.</li>
<li><em>A decorator and its component aren&#39;t identical</em>. A decorator acts as a transparent enclosure. But from object identity point of view, decorated component and component itself is different. Hence you shouldn&#39;t rely on object identitiy when you use decorators. (?maybe this means comparing object using memory address?)</li>
<li><em>Lots of little objects</em>. Often result in systems compose of lots of little objects that look alike, and differ only in the way they are interconnnected. Not in their class of in the value of their variables. These systems can be easy to customize for people who already knows them, but can be hard to learn and debug.<h3 id="implementation">Implementation</h3>
Several issues to consider.</li>
<li><em>Interface conformance</em>. A decorator&#39;s object interface must conform to the interface of the component it decorates. <code>ConcreteDecorator</code> classes must there for inherit from a common class (can be language dependent)</li>
<li><em>Omitting the abstract Decorator class</em>. No need to define an abstract <code>Decorator</code> class when you only need to add one responsibility.</li>
<li><em>Keeping Component classes lightweight&quot;</em>. To ensure a conforming interface, components and decorators must inherit from a common <code>Component</code> class. Import tant to keep this common class light. Focus on interfacd, not data. Don&#39;t make subclasses pay for features they don&#39;t need.</li>
<li><em>Changing the skin of an object vs changing its guts</em>. If you need to changes guts, Strategy Pattern is a good example. It is better where <code>Component</code> class is instrinsically heavyweight, so Decorator pattern is too costly to apply. And as Decorator Pattern changes only the skin, the component being decorated need not know about its decorators. Conversely, in Strategy Pattern the component must know about list of strategies it can use.   <img src="https://velog.velcdn.com/images/lucid_fizz/post/9f215104-0f91-49e3-9fb8-69effcf89a9f/image.png" alt="Decorator/Strategy Pattern differnce" width="500" height="300"/>
Also, strategy pattern can have its own modified interface. Where Decorator must conform to unified interface.
### Sample code 
In book, C++. I also rewrite it in python.
### Known uses
Graphical, Streams etc.
<img src="https://velog.velcdn.com/images/lucid_fizz/post/ab76dbfd-1ba5-4ea4-96e8-630ca86af2ae/image.png" alt="Decorator for Stream" width="500" height="300"/>
### Related Patterns
Adapter: can also add completely new interface, not just responsibilities.
Composite: can be viewed as degenerate composite w/ one component.
Strategy: Strategy changes guts, Decorator changes skin.</li>
</ol>
]]></description>
        </item>
        <item>
            <title><![CDATA[Strategy Pattern]]></title>
            <link>https://velog.io/@lucid_fizz/Strategy-Pattern</link>
            <guid>https://velog.io/@lucid_fizz/Strategy-Pattern</guid>
            <pubDate>Tue, 07 Feb 2023 08:12:07 GMT</pubDate>
            <description><![CDATA[<p><em>Study of GoF&#39;s Design Patterns (1994)</em></p>
<h3 id="intent">Intent</h3>
<p>Define a family of algorithms, encapsulate each one, make them interchangeable. Strategy lets the algorithm vary independently from clients that use it.</p>
<h3 id="also-known-as">Also Known As</h3>
<p>Policy</p>
<h3 id="motivation">Motivation</h3>
<p>Don&#39;t hardwire algorithms to classes that require them. What happens if algorithm changes? What if many classes commonly use this algorithm? What if bug is found, and it needs to be changed? Avoid duplicate code and support different algorithms using the same interface.</p>
<p><em>diagram from book</em>
<img src="https://velog.velcdn.com/images/lucid_fizz/post/77901c2e-bf22-4b34-b999-a614f0ef067b/image.png" alt="">
In this case, <code>Composition</code> class uses <code>Compositor</code> class to call <code>Compose()</code>, which manipulates <code>Composition</code>&#39;s members. But which compositor it uses can vary, even at runtime.</p>
<h3 id="applicability">Applicability</h3>
<ul>
<li>Many related classes differ only in their behavior.</li>
<li>Need different variants of an algorithm</li>
<li>Algorithm uses data that clients shouldn&#39;t know about</li>
<li>A class defines many behaviors, and these appear as multiple conditional statements in its operations. You can move these conditionals to their Own Strategy class.<h3 id="structure">structure</h3>
<img src="https://velog.velcdn.com/images/lucid_fizz/post/9071147a-443e-4bea-9a4b-d7cff30eb3c4/image.png" alt=""><h3 id="participants">Participants</h3>
</li>
<li><code>Strategy</code> (Compositor)<ul>
<li>declares an interface common to all algorithms.<ul>
<li><code>ConcreteStrategy</code></li>
<li>implements algorithm</li>
</ul>
</li>
</ul>
</li>
<li><code>Context</code> (Composition)<ul>
<li>is configured with a <code>ConcreteStrategy</code> object</li>
<li>has reference to a <code>Strategy</code> Object<h3 id="collaborations">Collaborations</h3>
<ul>
<li>Context may pass relavant data or itself to Strategy to determine the algorithm. Passing itself also allows callback functionality.</li>
<li>A context forwards requests from its clients to its strategy. Clients usually create and pass a ConcreteStrategy object to the context.<h3 id="consequences">Consequences</h3>
</li>
</ul>
</li>
</ul>
</li>
</ul>
<ol>
<li><em>Familes of related algorithms</em>. Filter out common functionality using inheritance. Subclasses for specific algorithm, which can is reusable.</li>
<li><em>An alternative to subclassing.</em></li>
<li><em>Strategies eliminate conditional statements</em>. yay.</li>
<li><em>A choice of implementations</em>. Different algorithms, same behavior</li>
<li><em>Clients must be aware of different strategies</em>. So, only use when the variation in behavior is relevant to clients</li>
<li><em>Communication overhead between <code>Strategy</code> and <code>Context</code></em>. Relevant info, or <code>Context</code> itself is passed. But some algorithms may not use all info, while some use all. If this is an issue, neee tighter coupling between <code>Strategy</code> and <code>Context</code>.</li>
<li><em>Increased number of objects</em>. Sometimes can be avoided by implementing stateless objects that contexts can share. Refer to Flyweight pattern.<h3 id="implementation">Implementation</h3>
</li>
<li>Defining the <code>Strategy</code> and <code>Context</code> interfaces. Passing the <code>Context</code> itself couples it, but allows explicit request to <code>Context</code> from <code>Strategy</code>. Or you can pass data as parameters to decouple it, but then might pass data that some algorithms don&#39;t need. Choose wisely.</li>
<li>Strategies as template parameters. Some C++ stuff. If algorithm to use is decided at compile-time, and not changed during run-time. </li>
<li>Making <code>Strategy</code> objects optional. Check <code>Context</code> checks if <code>Strategy</code> objects exist. If not, carry out default behavior. if yes, use <code>Strategy</code>. Benefit is clients don&#39;t have to deal with <code>Strategy</code> objects at all, unless they don&#39;t like the default behavior.<h3 id="sample-code">Sample code</h3>
in book, C++.<h3 id="known-uses">Known Uses</h3>
Many known uses, but I know not one of these. Refer to book if needed<h3 id="related-patterns">Related Patterns</h3>
Flyweight Pattern</li>
</ol>
]]></description>
        </item>
        <item>
            <title><![CDATA[Composite Pattern]]></title>
            <link>https://velog.io/@lucid_fizz/Composite-Pattern</link>
            <guid>https://velog.io/@lucid_fizz/Composite-Pattern</guid>
            <pubDate>Wed, 01 Feb 2023 08:43:26 GMT</pubDate>
            <description><![CDATA[<p><em>Studying GoF&#39;s Design Patterns(1994) book</em></p>
<h3 id="composite-pattern">Composite pattern</h3>
<h4 id="intent">Intent</h4>
<p>Using tree structure to represent part-whole hiearchies. Let&#39;s clients treat both individual objects and compositions of objects uniformly.</p>
<h4 id="motivation">Motivation</h4>
<p>The key is an abstract class that can represent both primitives and containers that contain a composition of these containers.</p>
<h5 id="diagram-from-textbook">Diagram from textbook</h5>
<p>![]
(<a href="https://velog.velcdn.com/images/lucid_fizz/post/f0fa03c4-6ab3-443d-aca0-9642c77805ed/image.png">https://velog.velcdn.com/images/lucid_fizz/post/f0fa03c4-6ab3-443d-aca0-9642c77805ed/image.png</a>)</p>
<p>So <code>Graphic</code> is the abstract class. And <code>Line</code>, <code>Rectangle</code>, <code>Text</code> are derived primitive subclasses. Then <code>Picture</code> Class is a container(or aggregate), composed of these primitive classes. Therefore it has child managing feature like <code>Add()</code>, <code>Remove()</code>, <code>GetChild()</code>. Since <code>Picture</code> Class also conforms to <code>Graphic</code> Abstract class, its <code>draw()</code> can tell its child to call <code>draw()</code> recursively. Note that <code>Picture</code> class can also be a child to another <code>Picture</code> class.</p>
<h5 id="a-more-general-diagram-from-book">A more general diagram from book</h5>
<p><img src="https://velog.velcdn.com/images/lucid_fizz/post/dce2d838-708f-4fd5-8b30-236b49b05e3f/image.png" alt=""></p>
<h4 id="participants">Participants</h4>
<p>Component - the abstract class
Leaf - primitives
Composite - aggregate of primitives + child related functionality
Client - uses objects in composition, via the component interface.</p>
<h4 id="consequences">Consequences</h4>
<p>Defines hiearchy where primitive objects can be composed into more complex objects recursively.
Client code is simpler. Client code can treat <code>Composite</code> and <code>Leaf</code> as same. No need for tag-and-case-statement-style functions
Make it easier to add new components, using the <code>Component</code> abstract class.
Can make your design overly general. As downside of making adding new components easier, the abstract class can be too general to enforce constraints. May need to do runtime checks instead of using type system at compile time.</p>
<h4 id="implementation">Implementation</h4>
<p><em>Explicit parent reference</em>. Usually in the Component abstract class. Make sure to have the invariant, where parent has reference to child and child has reference to parent. reference should go both ways, like doubly-linked list. Easiest way is to change a component&#39;s parent only when it is added or removed from composite.</p>
<p><em>Sharing components</em>. You can make it so there can only be one parent. But to share component, a child can have more than one parent. But this can lead to ambiguities. Flyweight Pattern shows how to rework a design to avoid having reference to parents altogether, by externalizing some or all of their state.</p>
<p><em>Maximizing the Component interface</em>. good, but sometimes conflicts with principle of class hiearchy design that says a class should only define operations that are meaningful to its subclasses.</p>
<p><em>Declaring the child management operations</em>. You can define them in components, or define them in composites. tradeoff vs safety tradeoff. 
or you could try to do <code>GetComposite()</code> check in component abstract class, that defaults to a null pointer. If it returns a composite object, you can do child management operations. Else, no. Usually it’s better to make Add and Remove fail by default (perhaps by raising an exception) if the component isn’t allowed to have children or if the argument of Remove isn’t a child of the component, respectively.</p>
<p><em>Should component implement a list of components</em>? No. Only if there are very few children in the structure.</p>
<p><em>Child ordering</em>. If needed, but design carefully. check Iterator pattern.</p>
<p><em>Caching to improve performance</em>. Maybe. But when component changes, it needto invalidate cache of parents. I think modern interpreters/processors or sth handles this well already?</p>
<p><em>Who should delete components</em>? Most languages have garbage collection nowdays. just remove reference to it. no need to <code>free()</code> memory or anything. </p>
<p><em>What&#39;s the best DS for storing components</em>? Depends. check Interpreter pattern for example.</p>
]]></description>
        </item>
        <item>
            <title><![CDATA[Installing old npm packages on m1 mac workaround]]></title>
            <link>https://velog.io/@lucid_fizz/Installing-old-npm-packages-on-m1-mac-workaround</link>
            <guid>https://velog.io/@lucid_fizz/Installing-old-npm-packages-on-m1-mac-workaround</guid>
            <pubDate>Wed, 25 Jan 2023 07:34:18 GMT</pubDate>
            <description><![CDATA[<p>I had problem with installing electron v8.1.1 for m1 mac</p>
<pre><code class="language-js">npm ERR! code 1
npm ERR! path /path/to/my/project/node_modules/electron
npm ERR! command failed
npm ERR! command sh -c node install.js
npm ERR! node:internal/process/promises:246
npm ERR!           triggerUncaughtException(err, true /* fromPromise */);
npm ERR!           ^
npm ERR! 
npm ERR! GotError [HTTPError]: Response code 404 (Not Found) for https://github.com/electron/electron/releases/download/v8.1.1/electron-v8.1.1-darwin-arm64.zip</code></pre>
<p>It says <code>darwin-arm64 v8.1.1 electron</code> doesn&#39;t exist.
Makes sense because 
m1 mac release was 11/17, 2020
electron v8.1.1 was 3/10, 2020</p>
<p>So how to solve?
<code>arch -x86_64 [:args]</code>
don&#39;t know how <code>arch</code> command works, but this fixed the problem for me
<em>note that program started in this manner, and its child process will try to inherit architecture all the same</em>
so if i start a zsh session with <code>arch -x86_64</code>, other programs invoked from this shell will also try to mimic architecture </p>
<h3 id="way-1">way 1</h3>
<p>launch the shell with different architecture, and use node with nvm</p>
<pre><code class="language-py">nvm install [:temp node version]
nvm use [:temp node version]
nvm uninstall [:target node version] # if installed already
arch -x86_64 zsh  # launch a zsh session with -x86_64 architecture.
arch  # check architecture.  might result in i386 also.
nvm install [:target node version]
nvm use [:target node version] # install and use target npm
</code></pre>
<h3 id="way-2">way 2</h3>
<p><strong>not tested</strong>
run <code>npm i</code> with designated architecture</p>
<pre><code>arch -x86_64 npm i</code></pre><p>reference:
<a href="https://stackoverflow.com/questions/68896696/having-trouble-installing-npm-on-mac-m1">https://stackoverflow.com/questions/68896696/having-trouble-installing-npm-on-mac-m1</a>
<a href="https://news.ycombinator.com/item?id=25132217#:~:text=Stickiness%20of%20architecture">https://news.ycombinator.com/item?id=25132217#:~:text=Stickiness%20of%20architecture</a></p>
]]></description>
        </item>
        <item>
            <title><![CDATA[Electron tutorial notes]]></title>
            <link>https://velog.io/@lucid_fizz/Electron-tutorial-notes</link>
            <guid>https://velog.io/@lucid_fizz/Electron-tutorial-notes</guid>
            <pubDate>Fri, 20 Jan 2023 09:35:53 GMT</pubDate>
            <description><![CDATA[<p><em>This is my notes while doing <a href="https://www.electronjs.org/docs/latest/tutorial/tutorial-prerequisites">official electron tutorial</a>.</em></p>
<h2 id="notes">Notes</h2>
<h3 id="building-your-first-app">Building Your First App</h3>
<p>Electron don&#39;t support ECMAscript <code>import</code>s. Must use <code>require</code></p>
<p>there is also option to debug using <a href="https://www.electronjs.org/docs/latest/tutorial/tutorial-first-app#optional-debugging-from-vs-code">VScode</a>. Might be useful later on. </p>
<h3 id="using-preload-scripts">Using Preload Scripts</h3>
<p>goal :try previliged APIs on renderer, Electron&#39;s IPC</p>
<p>Electron&#39;s main process runs on node.js w/ full OS access, Electron modules, and npm packages. But renderer shouldn&#39;t for security reasons.</p>
<p>two new files, <code>preload.js</code>, <code>renderer.js</code>
this will expose a <code>versions</code> obj? or sth to electron rendere</p>
<pre><code class="language-js">// preload.js
const { contextBridge } = require(&quot;electron&quot;)

contextBridge.exposeInMainWorld(&#39;versions&#39;, {
    node: () =&gt; process.versions.node,
    chrome: () =&gt; process.versions.chrome,
    electron: () =&gt; process.versions.electron,
})</code></pre>
<p>and this renderer will modify some HTML elements, using the &#39;versions&#39; object?&#39;s getters</p>
<pre><code class="language-js">// renderer.js
const information = document.getElementById(&#39;info&#39;)
information.innerText = `This app is using Chrome (v${versions.chrome()}), Node.js (v${versions.node()}), and Electron (v${versions.electron()})`
</code></pre>
<p>notice the <code>&lt;p&gt;</code> with <code>id=&quot;info&quot;</code> and added <code>&lt;script src=&#39;renderer.js&gt;</code></p>
<pre><code class="language-html">&lt;!DOCTYPE html&gt;
&lt;html&gt;

&lt;head&gt;
    &lt;meta charset=&quot;UTF-8&quot; /&gt;
    &lt;!-- https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP --&gt;
    &lt;meta http-equiv=&quot;Content-Security-Policy&quot; content=&quot;default-src &#39;self&#39;; script-src &#39;self&#39;&quot; /&gt;
    &lt;meta http-equiv=&quot;X-Content-Security-Policy&quot; content=&quot;default-src &#39;self&#39;; script-src &#39;self&#39;&quot; /&gt;
    &lt;title&gt;Hello from Electron renderer!&lt;/title&gt;
&lt;/head&gt;

&lt;body&gt;
    &lt;h1&gt;Hello from Electron renderer!&lt;/h1&gt;
    &lt;p&gt;👋&lt;/p&gt;
    &lt;p id=&quot;info&quot;&gt;&lt;/p&gt;
&lt;/body&gt;
&lt;script src=&quot;./renderer.js&quot;&gt;&lt;/script&gt;

&lt;/html&gt;</code></pre>
<p>now for the IPC interprocess communication</p>
<p>electron&#39;s main and renderer process have its own responsibilities. so, main process can&#39;t access the HTML DOM, and rendere can&#39;t access nodejs APIs. </p>
<p>but electron has <code>ipcMAin</code>, <code>ipcRenderer</code> modules for the IPC. use this.</p>
<p>for security reasons, don&#39;t expose the whole <code>ipcRenderer</code> module via preload script.
do it like this. wrap it in <code>contextBridge</code> module.</p>
<pre><code class="language-js">// preload.js
contextBridge.exposeInMainWorld(&#39;versions&#39;, {
  // ... skip
  ping: () =&gt; ipcRenderer.invoke(&#39;ping&#39;),</code></pre>
<p>now write handler in main</p>
<pre><code class="language-js">// main.js
// setup handler before loading loadFile.
ipcMain.handle(&#39;ping&#39;, () =&gt;  &#39;pong&#39; )
win.loadFile(&#39;index.html&#39;)</code></pre>
<p>then use it in renderer</p>
<pre><code class="language-js">// renderer.js
const func = async () =&gt; {
  const response = await window.versions.ping()
  console.log(response) // prints out &#39;pong&#39;
}

func()</code></pre>
<p>if <code>pong</code> doesn&#39;t log, check developer tools of electron app, not terminal.
In macOS, you can go thru <code>view</code> menu on top or  <code>option+cmd+I</code></p>
<p>if it logs <code>undefined</code>, make sure arrow function returns sth</p>
<pre><code class="language-js">//ex
() =&gt; {&#39;pong&#39;} // wrong. executes code block on function call, but returns nothing
() =&gt; &#39;pong&#39; // good. returns string</code></pre>
<h3 id="adding-features">Adding Features</h3>
<p>tutorial says some things, then says refer to its <a href="https://www.electronjs.org/docs/latest/tutorial/examples">examples</a></p>
]]></description>
        </item>
        <item>
            <title><![CDATA[Electron concept study-Process Model]]></title>
            <link>https://velog.io/@lucid_fizz/Electron-concept-study-Process-Model</link>
            <guid>https://velog.io/@lucid_fizz/Electron-concept-study-Process-Model</guid>
            <pubDate>Thu, 12 Jan 2023 07:35:37 GMT</pubDate>
            <description><![CDATA[<blockquote>
<p>This is my notes on <a href="https://www.electronjs.org/docs/latest/tutorial/process-model">https://www.electronjs.org/docs/latest/tutorial/process-model</a>, and not a complete summary</p>
</blockquote>
<p>why is election multi-process? web browsers like chrome are multi-process. Each tab, ui, plugin is a process. Explained very well in this <a href="https://www.google.com/googlebooks/chrome/">Chrome Comic</a> I liked.</p>
<p>So an electron app has a single main process that runs in node.js. This is the entrypoint, and can require and use all of node.js APIs. so it can read, write stuff anywhere. high level permission</p>
<p>This main process creates an app window using <code>BrowserWindow</code>module. 
like,</p>
<pre><code class="language-js">// main.js
const { BrowserWindow } = require(&#39;electron&#39;)

const win = new BrowserWindow({ width: 800, height: 1500 })
win.loadURL(&#39;https://github.com&#39;)

const contents = win.webContents
console.log(contents)</code></pre>
<p>This provides apps with a renderer, kind of like Chromium wrapper.</p>
<ul>
<li>Also, for security reasons explained well in the Chrome Comic, these renderers have very little privilege. It cannot use node.js APIs to control the native machine or other renderes, or <code>require</code> other modules. To use npm modules in rederer, you need to use same bundler toolchains like <code>webpack</code> or <code>parcel</code> to build the binary in beforehand.</li>
</ul>
<p>Or you can use preload scripts, which are run in a global <code>Window</code> interface. This can access node.js APIs.</p>
<p>or use utility process using <code>UtilityProcess</code> api, which can use use node.js and npm modules</p>
<p>moreover, electron has Native APIs to control native desktop functionality like menus, dialogs, tray icns.</p>
]]></description>
        </item>
    </channel>
</rss>