<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Rashed Alam on Medium]]></title>
        <description><![CDATA[Stories by Rashed Alam on Medium]]></description>
        <link>https://medium.com/@skull-sage?source=rss-6b55f8f694ad------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*JcS5RYml0lsdWLdjjpvl9w.png</url>
            <title>Stories by Rashed Alam on Medium</title>
            <link>https://medium.com/@skull-sage?source=rss-6b55f8f694ad------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 22 Nov 2026 11:22:48 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@skull-sage/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Apache Kafka in the realm of Event Driven Architecture (EDA)]]></title>
            <link>https://medium.com/@skull-sage/apache-kafka-in-the-realm-of-event-driven-architecture-eda-4bde67067279?source=rss-6b55f8f694ad------2</link>
            <guid isPermaLink="false">https://medium.com/p/4bde67067279</guid>
            <category><![CDATA[event-driven-architecture]]></category>
            <category><![CDATA[cqrs-pattern]]></category>
            <category><![CDATA[log-shipping]]></category>
            <category><![CDATA[kafka]]></category>
            <category><![CDATA[log-aggregation]]></category>
            <dc:creator><![CDATA[Rashed Alam]]></dc:creator>
            <pubDate>Mon, 27 Jan 2025 16:00:38 GMT</pubDate>
            <atom:updated>2025-01-28T07:39:51.712Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*o031mb2_jXZItRTDNMsyQQ.png" /></figure><p>Important EDA pattern in distributed application services and how Kafka helps to address them! important blog articles that helped me grasping concepts in depth are linked as I deemed appropriate.</p><p>Many modern business application are now being written in microservice method: loosely coupled components segregated by their use case boundary, each component can run independently in distributed manner and one component failure wouldn’t affect the others. The complexity of such distributed implementation however is governed by <a href="https://en.wikipedia.org/wiki/CAP_theorem"><strong>CAP theorem</strong></a><strong> </strong>which dictates “for a partitioned system if one wish to achieve High Availability would not be able to achieve High Consistency”.</p><p>But we could however, achieve high availability while maintaining eventual consistency, that is, instead of reflecting a data update immediately across the system, updates get propagated gradually from one component to another. <em>Eventual consistency </em>is the natural result of Event Driven Architecture(EDA)</p><p>Event Driven Architecture(EDA) is a communication strategy among two or more distributed(loosely coupled) business components that facilitates with (but not limited to) <em>eventual consistency</em>; where one component needs to react consistently for an event occurred in another isolated component.</p><p>The standard elements of an EDA are:</p><ul><li><strong>Publisher/Emitter</strong> that publish a notification containing relevant data of a component’s event. Event data record(s) are immutable, contain all necessary information to consume it and can have predefined schema on which decoupled-distributed components can agree upon.</li><li><strong>Consumer/Subscriber</strong> that listens to such event data and acts upon them independently. Consumer and Publisher don’t have any knowledge of each other; Consumer can continue working on event data even in case of failure of publisher.</li><li><strong>Event stream Channel </strong>that contains all emitted event data in totally-ordered, unbounded sequence ensuring delivery of event(s) at least once to its subscriber(s)</li></ul><p>Apache Kafka is a well known event streaming platform that fits very well in the realm of EDA with a basic communication architecture:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/883/1*6wtVLkWejurKi5y2ejAH9w.png" /><figcaption>A simplistic view of event data flow from producer to consumer</figcaption></figure><p>The above diagram is merely a birds eye view. The detailed flow of event stream for a topic from producer to consumer obviously requires a more detailed article :) but in a nutshell:</p><ul><li>Kafka allows multiple producers to publish event record to a topic and multiple consumer to subscribe to that topic. Producer/Consumer can come and go independently; Consumer(s) can act as part of a group and can’t remove event record.</li><li>a broker(Kafka server) store &amp; organize those event records for durability &amp; high scalability but doesn’t support arbitrary access lookup of data.</li></ul><p>In the realm of EDA, I have used Kafka so far for following use cases and they worked pretty well.</p><h3><strong>Log Aggregation</strong></h3><p>For query centric applications, logging the queried data from several components is really valuable to build insights. Such log generation however happens at burst rates making it significantly harder for the application’s datastore to keep up with ‘expensive’ operations such as log ingestion and indexing at the same time.</p><p>Kafka can be used as a buffer, offering an intermediate, durable datastore where</p><ul><li>a <em>source connector</em> generally try to utilize a <strong>change data capture mechanism</strong> of application datastores for colleting and streaming change logs</li><li>an ingestion process will act as a sink, collating the logs into a read-optimized database (for example, Elasticsearch or HBase) for building analytics or other query serving purposes.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/844/1*1ZjLzh_VQR5hoqOf8g3avA.png" /></figure><p>A log aggregation pipeline may also contain many intermediate steps: sanitize log entries, building canonical form, compressing and encrypt log content etc.</p><h3>Staged Event-Driven Architecture(SEDA)</h3><p>This architecture is most suitable when we have business cases where independent components needs to take action on interdependent conditions &amp; pre-populated state. In this architecture:</p><ul><li>Event data flow unidirectionally through a series of intermediate processing stages linked by topics.</li><li>Each stage performs a mapping operation then upon condition criteria publishes transformed event records to the next topic.</li><li>Each Intermediate stages simultaneously act as both consumers and producers</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1015/1*Bf9nnkLv4wNb183QH3_l9g.png" /></figure><p>SEDA can also be used in log aggregation; in fact, log aggregation is a narrow specialization of SEDA.</p><h3>CQRS &amp; Event Sourcing</h3><p>Command-Query Responsibility Segregation (CQRS) is one of my favorite design pattern that segregates data mutating actions from query actions: There is generally two different data model that designates to same data context:</p><ul><li><em>write-model,</em> on which mutating commands create/change/delete gets executed.</li><li><em>read-model, </em>a denormalized form (along with in memory cache) to serve query request faster.</li></ul><p>Incorporating EDA really simplifies CQRS where an application component mutates <em>write-model </em>and raises event data so that another independent component build <em>read-model </em>for fast serving.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/710/1*V1nkdeXt6geFayV1mMat8Q.png" /></figure><p>Event-sourcing pattern is closely related to CQRS pattern that requires storing state version of read-model transitioned by event. These consequently supports audit trail along with undo and redo.</p><p>Kafka can also act as a common event-sourced ledger. It’s consumer group concept can be used to feed different query-centric datastores.</p><p>According to my experience though, a full-fledged implementation of event sourcing pattern can be really daunting and might not be suitable approach to adopt in early stage of development.</p><p><strong>For further reading</strong></p><ul><li><a href="https://towardsdatascience.com/using-kafka-as-a-temporary-data-store-and-data-loss-prevention-tool-in-the-data-lake-5472f2b586e">Using Kafka as a Temporary Data Store and Data-loss Prevention Tool in The Data Lake</a></li><li><a href="https://docs.confluent.io/platform/current/connect/index.html#connectors">Kafka Connect | Confluent Documentation</a></li><li><a href="https://klarrio.medium.com/database-replication-with-change-data-capture-over-kafka-975bc60cecce">Database Replication with Change Data Capture over Kafka</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4bde67067279" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Effective Java: EnumMap]]></title>
            <link>https://medium.com/@skull-sage/effective-java-enummap-f554303c8840?source=rss-6b55f8f694ad------2</link>
            <guid isPermaLink="false">https://medium.com/p/f554303c8840</guid>
            <category><![CDATA[enum]]></category>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[enummap]]></category>
            <category><![CDATA[hashmap]]></category>
            <dc:creator><![CDATA[Rashed Alam]]></dc:creator>
            <pubDate>Tue, 12 Dec 2023 20:41:23 GMT</pubDate>
            <atom:updated>2025-01-27T16:12:29.579Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*GiiqWymCJyx4Wi3VJKFZWg.png" /></figure><p>To support storing data as <em>key-value</em> format, Java has many implementation ofMap such as HashMap, IdentityHashMap, LinkedHashMap, TreeMap,etc. All of these Map allow <em>keys</em> to be of arbitrary object type; even null is allowed to be used as <em>key</em>.</p><p><a href="https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/util/EnumMap.html">EnumMap</a> is a specialized Map implementation for use exclusively with an <a href="https://docs.oracle.com/javase/8/docs/api/java/lang/Enum.html">Enum</a> type <em>keys</em>. Consequently, unlike other maps, EnumMap doesn’t permit null keys.</p><p>Lets discuss Enum ordinal. For an enum type such as follows :</p><pre>enum MessageFlag{<br>  DEBUG, INFO, WARNING, ERROR<br>}</pre><p>Java compiler generates an associated ordinal value for each declared constant according to its position in the declaration, accessible by ordinal() function, where the initial constant is assigned an ordinal of zero.</p><pre>DEBUG | INFO | WARNING | ERROR<br>  0       1       2        3</pre><pre>System.out.println(MessageFlag.WARNING.ordinal()); // prints 2</pre><p>We can useEnumMap for this MessageFlag enum to create a color mapping for each flag type:</p><pre>EnumMap&lt;MessageFlag, String&gt; colorMap = new EnumMap&lt;&gt;(MessageFlag.class);<br>colorMap.put(MessageFlag.INFO, &quot;blue&quot;);<br>colorMap.put(MessageFlag.WARNING, &quot;amber&quot;);<br>colorMap.put(MessageFlag.ERROR, &quot;red&quot;);<br>colorMap.put(MessageFlag.DEBUG, &quot;grey&quot;);</pre><p>As shown in the initialization step, we must provide the Enum type we intend to use (MessageFlag) as key for the map.</p><p>EnumMap is represented internally as arrays and its keys are naturally ordered according to the ordinal value of each constant. Following example demonstrates this with EnumMap.keySet() function:</p><pre>Object[] keyArr =  colorMap.keySet().toArray(); <br>System.out.println(keyArr[2]); // prints WARNING</pre><p>Another important property of EnumMap is, unlike HashMap/TreeMap it’s iterators returned by collection views(<a href="https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/util/EnumMap.html#keySet()">keySet()</a>, <a href="https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/util/EnumMap.html#entrySet()">entrySet()</a>, and <a href="https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/util/EnumMap.html#values()">values()</a>) are <em>weekly consistent:</em> won’t throw <a href="https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/util/ConcurrentModificationException.html">ConcurrentModificationException</a> and any concurrent modifications <em>may/may not be reflected while the iteration in progress</em>.</p><pre>Thread itrThread = new Thread(()-&gt;{<br>   // AsyncUtil.uncheckedSleep(700);<br>    colorMap.keySet().forEach(key -&gt; {<br>        AsyncUtil.uncheckedSleep(2000);<br>        System.out.printf(&quot;ITR-THREAD: (%s =&gt; %s)\n&quot;, key, colorMap.remove(key));<br>    });<br>});</pre><pre>itrThread.start();</pre><pre>// an utility that uncheck InterruptedException of Thread.sleep :) <br>AsyncUtil.uncheckedSleep(100); <br>colorMap.remove(MessageFlag.DEBUG); // removing value for DEBUG<br>AsyncUtil.uncheckedSleep(200);<br>colorMap.remove(MessageFlag.WARNING); // removing value for WARNING</pre><p>If you notice the printed message carefully from above you will see it prints mapping of DEBUG mapped value as DEBUG =&gt; nulland doesn’t print mapping for WARNING . The reason is lambda captured the local key before the main thread could remove it in case of DEBUG.</p><p>These two properties make EnumMap compact and efficient for case of ordinal index based time-costly computations on large dataset. For example: lets say we have large list of restaurants List&lt;Restaurant&gt; and we want to calculate sales count by RestaurantType Enum. Using EnumMap&lt;ResturantType, Integer&gt; to do the computation will be lot faster and safe from concurrent modification exception; even though it might not be able to capture data modification in real-time.</p><p>Another use case I have found for EnumMap is when I want to do functional mapping for well-defined data type. For example if for a service, incoming data types are string and I were to write a type resolver mapping from String to Specific type:</p><pre>enum DataTypes<br>{<br>  Integer, Long, Instant<br>}<br><br>EnumMap&lt;DataTypes, TypeResolver&gt; resolverMap = new EnumMap&lt;&gt;(DataTypes.class);<br>resolverMap.put(DataTypes.Long, TypeResolvers.longResolver());<br>// other mappings</pre><p>Statically typed language always helps writing better code that can work as living documentation along with runtime type safety and performance. EnumMap is just another example of these effective features :).</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f554303c8840" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[All hail Java annotations]]></title>
            <link>https://medium.com/@skull-sage/all-hail-java-annotations-262504209685?source=rss-6b55f8f694ad------2</link>
            <guid isPermaLink="false">https://medium.com/p/262504209685</guid>
            <category><![CDATA[dagger-2]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[annotations]]></category>
            <category><![CDATA[junit-5]]></category>
            <dc:creator><![CDATA[Rashed Alam]]></dc:creator>
            <pubDate>Sun, 22 Oct 2023 00:19:31 GMT</pubDate>
            <atom:updated>2023-10-22T02:32:12.063Z</atom:updated>
            <content:encoded><![CDATA[<p>Lets discuss how annotation has proved to be an useful mechanism in Java world from compile time code generation to test utilities.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*OW59hfSRT3eImSCuy41IDw.png" /></figure><p>Source code commenting helps us adding descriptions for future walkthrough and understanding the reasoning about any class/method implementations. Well, But compiler doesn’t try to make sense of arbitrary comments. Capability to add <em>metadata </em>(data that can describe other data)<em> </em>can help compiler reporting various implementation details such as it’s<em> </em>author, super class method overriding and even dependency relationship among classes and method arguments during compile time and/or runtime.</p><p>Java 5 has introduced Annotation, a type of @interface that allows defining metadata to class and methods. Member Elements of an annotation looks a lot like interface method and can have following types:</p><ul><li>primitive</li><li>String</li><li>an Enum</li><li>another Annotation</li><li>Class</li><li>an array of any of the above</li></ul><p>Here is a rudimentary example of TaskSchedule annotation that helps scheduling a task:</p><pre>@Documented <br>@Retention(RetentionPolicy.RUNTIME)<br>@Target(ElementType.TYPE)<br>@interface TaskSchedule<br>{<br>    int dayLapse() default 1;<br>    String at();<br>}<br><br>@TaskSchedule(dayLapse = 3, at=&quot;4:00pm&quot;)<br>class CalcUsageRanking <br>{<br>       public void execute(){<br>           // a long-running task to compute user&#39;s usage rank<br>       }<br>}</pre><p>As you have noticed we can apply meta annotation to describe an annotations. Following standard meta annotations are generally used in annotation declaration:</p><ul><li><a href="https://docs.oracle.com/javase/8/docs/api/java/lang/annotation/Documented.html">@Documened</a> annotation tells compiler @TaskSchedule should appear in JavaDoc.</li><li><a href="https://docs.oracle.com/javase/8/docs/api/java/lang/annotation/Retention.html">@Retention</a> specifies if the annotation should only appear in source, .class or be available at runtime.</li><li><a href="https://docs.oracle.com/javase/8/docs/api/java/lang/annotation/Target.html">@Target</a> specifies if the annotation be applied to a field, method or a type.</li></ul><p>Here is how we can access the defined @TaskSchedule member value:</p><pre>CalcUsageRanking task  = new CalcUsageRanking();<br>TaskSchedule schedule = task.getClass().getAnnotation(TaskSchedule.class);<br>System.out.printf(&quot;Execute every %d days at %s&quot;, schedule.dayLapse(), schedule.at());</pre><p>There are many <a href="https://docs.oracle.com/javase/tutorial/java/annotations/predefined.htm">predefined annotations</a> types that are well known to Java programmers. From Java 8, Type annotations and Pluggable Type Systems have been introduced. This allows external type checkers help user writing code that are less error-prone. Interested reader can visit <a href="https://checkerframework.org/">Checker Framework</a>, though I personally haven’t used it.</p><p>Lets discuss some advantages annotations have provided in Java world.</p><h4><strong>Information for the compiler</strong></h4><p>Annotations can be used by the compiler to detect errors or suppress warnings. Using standard @Override annotation indicates that the annotated method overrides a declaration from <em>supertype</em>. Consistently using it protects from large class of nefarious bugs that might happen from inconsistent signature matching or typos of intended methods.</p><p>@SafeVarargs is another standard annotation that helps suppress compiler warning whenever programmer intends to. <a href="https://stackoverflow.com/a/14252221/1173114">Stackoverflow</a> has really nice answer describing its usage.</p><h4><strong>Compile-time processing: dagger</strong></h4><p>Software tools can process annotation information to generate code, XML files, and so forth during compile time. Notably, the <a href="https://dagger.dev/"><strong>dagger</strong></a> dependency injection library calculate dependency graph, reports unmet requirements for initialization and invocations during compile time. It has concepts of @Component, @Module to specify dependency providers and relationship; @Singleton, <strong>@</strong>Scope for managing scopes of dependencies. @Component work as dependency root and glue all the required dependency defined by sub-components and modules.</p><p>If a programmer need to understand dependencies among different parts, all he has to do is to start from interfaces annotated with @Component. To be truthful, I have found it as one of the most cleanly developed library and used it to write my own simple RPC style service framework.</p><h4><strong>Runtime processing: Spring framework and Spring Boot</strong></h4><p>The example we have given in introductory section is one example how annotation can be used during runtime execution. <strong>Spring Boot </strong>is a popular Java framework that has implemented dependency management system utilizing annotation. It manages initializations of dependency beans and their lifecycles during runtime with the rigorous usage of <em>reflection</em>. The @Component, @Configuration, @Bean and @Autowire are most commonly used by programmers to define dependencies in Spring land.</p><h4>Test Utilities: Junit</h4><p><strong>JUnit 3</strong> required its users to add “<em>test</em>” prefix to designate test methods. However, while using such <strong>naming pattern,</strong> a simple typo such as <em>tset</em>SafetyOverride could easily result in silent non-execution. <strong>JUnit 4</strong> Introduced @test annotation to designate test methods and consequently removed all the disadvantages associated with previous naming patterns. Parameterized annotation even helps specifying exception a test method must check against.</p><p><strong>JUnit 5</strong> has introduced @BeforeAll, @BeforeEach @AfterAll @AfterEach annotation that allowed us writing fluent test utilities to help testing different parts of services in asynchronous environment taking advantage of CountDownLatch mechanism.</p><p>In this article I have tried to summarize basics of Java annotation and listed some well known tools that leverages this mechanism helping programmers in real world applications development. One issue I have found with annotation processor library though, declaring them in build tools such as gradle is not transitive.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=262504209685" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Immutability: Usefulness of readonly in Typescript]]></title>
            <link>https://medium.com/@skull-sage/immutability-usefulness-of-readonly-in-typescript-ed2a122d7fd4?source=rss-6b55f8f694ad------2</link>
            <guid isPermaLink="false">https://medium.com/p/ed2a122d7fd4</guid>
            <category><![CDATA[readonly]]></category>
            <category><![CDATA[immutability]]></category>
            <category><![CDATA[typescript]]></category>
            <dc:creator><![CDATA[Rashed Alam]]></dc:creator>
            <pubDate>Wed, 20 Sep 2023 00:35:45 GMT</pubDate>
            <atom:updated>2023-09-24T02:28:26.249Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*Kd_9P_GJC8hq--IHLYbSnQ.png" /></figure><p>In <a href="https://en.wikipedia.org/wiki/Object-oriented_computer_programming">object-oriented</a> (OO) and <a href="https://en.wikipedia.org/wiki/Functional_programming">functional</a> programming, an <strong>object</strong> is immutable if its state cannot be modified after it is created. As in most OOP, objects are <em>passed by reference</em> to other parts of application, such as methods or UI component’s props. If any part of application <em>mutates </em>an object while other parts are depending on its state, any changes to that state can easily lead to inconsistencies during runtime. This is especially true for runtime executing in <em>asynchronous </em>context.</p><p>In JS, objects are also <em>passed by reference</em>. We can use const declaration to mark a variable as immutable. This make variable with primitive type read-only, but for object, properties are still mutable. We have few options to make object properties read-only:</p><ul><li>We can use Object.defineProperty to mark a property writable: false.</li></ul><pre>const obj = { propA: {<br>        nestedA: 1,<br>        <br>    },<br>}; <br>Object.defineProperty(obj, &#39;propA&#39;, {writable: false});<br><br>obj.propA.nestedA = 2; // valid<br>obj.propA  = null; // error</pre><ul><li>We can use Object.freeze to make an object <em>shallowly</em> immutable: only top level properties become read-only, nested properties remain mutable.</li></ul><pre>const obj = { propA: {<br>        nestedA: 1,<br>    },<br>};<br>Object.freeze(obj);<br>obj.propA.nestedA = 2; // valid<br>obj.propA = null; // error: Cannot assign to read only property</pre><p>To make an object deeply immutable, we can always write an utility method that recursively traverse all <em>object</em> properties (including nested) and freeze them utilizing Object.freeze. However, mutation of read-only properties gets <strong>reported only during runtime</strong><em> </em>as error.</p><p>In JS, developer uses functional programming a lot. As a safe-guard against mutability, we can use concept of pure function to establish a contract. This is one reason, UI library like<strong> React </strong>recommends always to implement pure functional component. To define a pure function:</p><ol><li>Given the same inputs, a pure function should always return the same result.</li><li>the function has no side effects: It does not change any objects or variables (needless to say its arguments) that existed before it was called.</li></ol><p>Example of a simplest pure function:</p><pre>function double(arg) {<br>  return 2 * arg;<br>} </pre><p>However, for a pure function that does a lots of calculation, developer can easily write code that mistakenly mutate an argument that has deep nested properties. A type system can prevent such mistake at compile time always works as the <em>best </em>safe-guard.</p><h3>readonly in TypeScript</h3><p>TypeScript (TS) being superset of JavaScript introduces a comprehensible type systems developer can use to write type safe code. In TS type system, we can use readonly modifier while decelerating properties of <strong>interface </strong>and <strong>type alias</strong> to mark them as immutable.</p><pre>type Person = {<br>    readonly name : {<br>        fullName : string,<br>        readonly nickName: String<br><br>    }<br>}<br> <br>const person:Person = {<br>    name: {<br>        fullName: &quot;Hoshikage Kisame&quot;,<br>        nickName: &quot;Blackfish&quot;<br>    }<br>}<br><br>person.name = {}; // compile time error<br>person.name.fullName = &quot;Namikaze Mintao&quot;; // okay<br>person.name.nickName = &quot;Nikka&quot; // compile time error</pre><p>We can use readonly modifier while <em>anonymous typing</em> a function argument too:</p><pre>function pureFoo(data: {<br>    readonly bar: number,<br>    readonly baz: number<br>}) {<br>    //...<br>}<br><br>let config = { bar: 123, baz: 123 };<br>pureFoo(config);<br>// now we are sure pureFoo could not change state of its argument.</pre><p>class properties that are marked as readonly needs to be instantiated at the point of declaration or in the constructor as shown below:</p><pre>class FooClz {<br>    readonly bar = 1; // OK<br>    readonly baz: string;<br>    constructor() {<br>        this.baz = &quot;hello&quot;; // OK<br>    }<br>}</pre><p>A Quick way to enforce every props to be readonly would be to use mapped types:</p><pre>interface IMarkReadOnly <br>{<br>  readonly [key :string] : any; <br>}<br><br>class Foo implements IMarkReadOnly<br>{<br>  name : string;<br>  published: boolean; // Error: must be initilized here or in constructor<br><br>  constructor(){<br>    this.name = &quot;Okay&quot;; <br>    <br>  }<br>}</pre><h4>Readonly&lt;Type&gt;</h4><p>This generic utility type takes a type T and marks all of its properties as readonly using mapped types:</p><pre>interface Todo {<br>  title: string;<br>}<br> <br>const todo: Readonly&lt;Todo&gt; = {<br>  title: &quot;Delete inactive users&quot;,<br>};<br> <br>todo.title = &quot;Hello&quot;;</pre><p>I find it important to note that in TS, Object.freeze&lt;T&gt; method returns the Readonly&lt;T&gt; type, which provides a bridge between the concept of freezing objects in JavaScript and the concept of readonly types in TypeScript.</p><pre>const foo = Object.freeze({bar: &#39;Big&#39;, baz: &quot;Hello&quot;});<br><br>foo.bar = &quot;Ah no!&quot;; // compile time error</pre><p>TS ships with <a href="https://www.typescriptlang.org/docs/handbook/2/objects.html#the-readonlyarray-type">ReadonlyArray&lt;T&gt;</a> type too, which serves as an interface for providing readonly arrays of a generic type T.</p><pre>let foo: ReadonlyArray&lt;number&gt; = [1, 2, 3]; <br>foo.push(4); // Error: `push` does not exist as foo is readonly <br>foo = foo.concat([4]); // Okay: create a copy</pre><h4>Escaping readonly</h4><p>The compile time assurance of readonly is gone with redeclaration of type extensions or argument casting. This is shown in following examples.</p><p><strong>Example 1: </strong>during extensions</p><pre>interface IFoo<br>{<br>    readonly bar:string<br>    baz:number<br>}<br><br>class FooClz implements IFoo<br>{<br>    bar:string; // TS doesn&#39;t enforce readonly<br>    baz:number;<br><br>    constructor()<br>    {<br>        this.bar = &quot;Big&quot;;<br>        this.baz = 404;<br>    }<br>}<br><br>const foo : FooClz = new FooClz();<br>foo.bar = &quot;Small&quot;; // mutating; </pre><p><strong>Example 2: </strong>anonymous typing an argument</p><pre>type FooType = {readonly bar : number}<br>let foo : FooType = {bar : 100}<br><br>function letsMutateFoo(arg: { bar: number }) {<br>    arg.bar = 420;<br>}<br><br>letsMutateFoo(foo);  <br>console.log(foo.bar); // 420! eascaping readonly worked :)<br>foo.bar = 101; // compiletime error!</pre><p>readonly is one of the many goodies TypeScript has offered for type safe development. But as we have shown, redeclaration can help escaping it, developer should always write code that is sensible :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ed2a122d7fd4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Type alias vs Interface in Typescript]]></title>
            <link>https://medium.com/@skull-sage/type-alias-vs-interface-in-typescript-650272516a6c?source=rss-6b55f8f694ad------2</link>
            <guid isPermaLink="false">https://medium.com/p/650272516a6c</guid>
            <category><![CDATA[typealias]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[interfaces]]></category>
            <dc:creator><![CDATA[Rashed Alam]]></dc:creator>
            <pubDate>Fri, 15 Sep 2023 13:48:23 GMT</pubDate>
            <atom:updated>2023-09-17T22:58:46.588Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*3nlyUFNC3UnsAjj5Su1W-A.png" /></figure><p>TypeScript (TS) is a superset of JavaScript (JS) that introduces static typing capabilities allowing tighter code of contract for OOP in JS. Consequently TS helps catching errors at compile-time rather than runtime and works as a living documentation. Unlike many other strongly typed language such as Java, it:</p><ol><li>allows structural type conformation known as “duck typing”</li><li>has nested type declaration capabilities for properties.</li></ol><p>Both <strong>Type alias </strong>and <strong>Interface</strong> are used to define custom data types, but as we will see in this article, they serve distinct purposes.</p><h3>Interface</h3><p><strong>Interface</strong> in TypeScript allows explicitly describing an object’s shape. we can use it to specify the structure an object must adhere to: props that must be defined and props that are optional.</p><pre>export interface IUser<br>{<br>    identity: { // nested type declaration<br>        email: string,<br>        phone: string<br>    }<br>    readonly role: string // immutable after initialization<br>    thumbnail?:string // suffix &#39;?&#39; means thumbnail is optional<br>}<br><br>const loggedUer: IUser = { <br>    identity: {email: &quot;kafka@mail.com&quot;, phone: &quot;20X-0000404&quot;},<br>    role: &quot;junior_dev&quot;<br>}</pre><h3>Type alias</h3><p>With <strong>Type alias</strong>, we have the flexibility to create name aliases for existing data types, combining multiple types including <strong>interfaces</strong> with <em>union</em>( | ) and <em>intersection</em>( &amp; ) and reusing the alias across codebase. With type alias we can also specify shape of <em>object literals</em>.</p><pre>type ID = number | string;<br><br>interface Colorful {<br>    color: string;<br>}<br><br>interface Shape {<br>    id: ID <br>    name: string;<br>}<br><br>type ColorfulShape = Colorful &amp; Shape;<br><br>const shapeColorful:ColorfulShape = {<br>    color: &quot;0xFFFF&quot;, <br>    name: &quot;circle&quot;, <br>    id: 404<br>}</pre><p>As we can see both Type alias and Interface can be used to specify shape of an object. We can create new <strong>interface</strong> by extending a <strong>type alias, </strong>we can also create new <strong>type alias</strong> by combining an <strong>interface</strong>. However:</p><ul><li><strong>Type alias</strong> can be used to combine <em>primitive types</em> but <strong>interface</strong> is tied to object shape.</li><li>class can implements interfaces to establish a clear contract in code.</li></ul><pre>interface IUser{<br>    //...other props<br>    defIdentity():string;<br>}<br><br>class UserAccount implements IUser<br>{<br>    identity: { email: string; phone: string };<br>    role:string;<br><br>    constructor({identity, role}: IUser)<br>    {<br>        this.identity = identity;<br>        this.role = role;<br>    }<br>    defIdentity(): string {<br>        return &#39;email&#39;<br>    }<br>}</pre><ul><li>If you’ve used hooks(i.e., useState) in react, then you know the usefulness of tuples. <strong>Type alias</strong> can be used for declaring type for arbitrary tuples</li></ul><pre>type APair= [number, string];<br>let pair:APair = [1, &#39;101&#39;];<br><br>type ATriple = [boolean, number, string];<br>let triple:ATriple = [true, 1, &#39;101&#39;]</pre><ul><li><strong>interfaces</strong> are open and <strong>type aliases</strong> are closed: interface can be augmented by declaring second time. This is known as <a href="https://www.typescriptlang.org/docs/handbook/declaration-merging.html#merging-interfaces">declaration merging</a>.</li></ul><pre>interface Box {<br>  height: number;<br>  width: number;<br>}<br>interface Box {<br>  scale: number;<br>}<br>let box: Box = { height: 5, width: 6, scale: 10 };</pre><ul><li>To get better error message, using <strong>Interface </strong>is always better. For <strong>type alias, TS </strong>compiler fails to report exact name of types even though it mentions declared line number.</li></ul><pre>type ABird = { wings: number };<br>type Nocturnal = { nocturnal: boolean } &amp; ABird;<br><br> interface Chicken extends ABird {<br>  colourful: boolean;<br>  flies: boolean;<br>}<br><br>let owl:Nocturnal = {nocturnal:true, wings: 2}<br>let chicken: Chicken = {wings: 2, colourful: true, flies: false} <br><br>// Error: Property &#39;nocturnal&#39; is missing in type &#39;Chicken&#39; but required in type &#39;{ nocturnal: boolean; }&#39;<br>owl = chicken; <br>// Error: Type &#39;Nocturnal&#39; is missing the following properties from type &#39;Chicken&#39;: colourful, flies<br>chicken = owl;</pre><p>We can however, always use <strong>Type alias</strong> and <strong>Interface</strong> together for achieving better code implementation clarity:</p><pre>type MyFunctionType = (name: string) =&gt; number;<br><br>interface MyClassProps {<br>    onChange: MyFunctionType;<br>    niceProp: string;<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=650272516a6c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[null as Key in Different Java Maps]]></title>
            <link>https://medium.com/@skull-sage/null-as-key-in-different-java-maps-ad7575909a8?source=rss-6b55f8f694ad------2</link>
            <guid isPermaLink="false">https://medium.com/p/ad7575909a8</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[java-map]]></category>
            <category><![CDATA[null]]></category>
            <dc:creator><![CDATA[Rashed Alam]]></dc:creator>
            <pubDate>Tue, 15 Aug 2023 02:07:23 GMT</pubDate>
            <atom:updated>2023-10-04T14:59:48.337Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*VECF2Hu17Iq17r2MSe_2hQ.jpeg" /></figure><p>In Java, null value is generally used to show absent memory reference by an object. Hence, variable with primitives types can’t be assigned to null at <em>compile time</em>.</p><pre>int i = null; // compile time error<br>Integer objA = null;</pre><p>But this obviously leads to many buggy scenarios such as during unboxing an object reference to its corresponding primitive types: if the object is null it results in NullPointerException during runtime.</p><pre>int anotherInt = objA; // if objA is null then runtime NullPointerException</pre><p>This type of exception pattern is so notorious that developers has to write null checking conditions at the start of almost every business functions. To facilitate with these, helper methods such as <a href="https://docs.oracle.com/javase/8/docs/api/java/util/Objects.html#isNull-java.lang.Object-">isNull, nonNull, requireNonNull</a> have been introduced since Java 8.</p><p>Different implementation of Java Map handle null as key differently. In this article we will discuss this elaborately.</p><h4><strong>Null as key In HashMap and </strong><strong>IdentityHashMap</strong></h4><p>HashMap allows null as key. During HashMap.put operation, the calculated hash is always0. Which means, as the data structure implementation uses <em>bucket array of linked list</em>, the mapped value of null always ends up in bucket 0.</p><p>Allowing null as key helps for the case of default mapping (i.e. the value that should be used if a given key isn’t present):</p><pre>Map&lt;A, B&gt; fooMap = new HashMap&lt;&gt;();<br>fooMap.put(null, defaultValueOfTypeB);<br>// and some more put ops of key =&gt; value :)<br><br>A searchKey;<br>String val = fooMap.containsKey(searchKey) ? fooMap.get(searchKey) : fooMap.get(null);</pre><p>For IdentityHashMap null key mapping works the same way. However, unlike HashMap IdentityHashMap uses reference-equality (objA==objB) in place of object-equality (objA.equals(objB)) when comparing keys and has a simple <em>linear-probe</em> hash table as it’s internal data structure. Hence, it uses a class member constant (created with new Object()) instance’s hashCode() in case of null.</p><h4>Null as key In TreeMap</h4><p><a href="https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/util/TreeMap.html">TreeMap</a> allows null key if a defined comparator allows it: in case of natural ordering, accessing or putting with null key results in NullPointerException. Following example shows null allowing comparator:</p><pre>Comparator&lt;Integer&gt; nullAllowingComparator = Comparator.nullsFirst(Comparator.naturalOrder());<br>NavigableMap&lt;Integer, String&gt; navigableMap =  new TreeMap&lt;&gt;(nullAllowingComparator);<br>navigableMap.put(null, &quot;Unpleasant Null&quot;);<br>navigableMap.put(50, &quot;This is 50&quot;);<br>navigableMap.put(20, &quot;this is 20&quot;);<br>System.out.println(navigableMap);<br>//prints nulls_first: {null=Unpleasant Null, 20=this is 20, 50=This is 50}</pre><h4><strong>Null as key In EnumMap</strong></h4><p>EnumMap strictly requires keys to be a defined enum type, hence it doesn’t allow null as key. <a href="https://medium.com/@skull-sage/a-guide-to-java-enummap-80da7c049aae">EnumMap has effective use cases</a> and allowing null as key would not serve any purpose anyway.</p><h4>ConcurrentHashMap and ConcurrentSkipListMap</h4><p>These two concurrent maps allow null neither as a key nor as a value.</p><p>While it is not clearly described in documentation why null as key is not allowed in these implementations, from their source code, I suspect allowing as such would introduce much more complexity maintaining efficient concurrency aspects against little gain from any kind of default mapping.</p><h4><strong>Conclusion</strong></h4><p>Handling cases for null is going to stay in foreseeable future in programming world. Though as the programming language is evolving new utility types are also being introduced to handle edge cases such as Optional. But for the case of Map implementations, I personally don’t think using/allowing null as key is ever a good idea.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ad7575909a8" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>