<?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 Aelafseged on Medium]]></title>
        <description><![CDATA[Stories by Aelafseged on Medium]]></description>
        <link>https://medium.com/@aelafted?source=rss-a8d60de601bc------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*tfnM8L00wBZuipD0.jpg</url>
            <title>Stories by Aelafseged on Medium</title>
            <link>https://medium.com/@aelafted?source=rss-a8d60de601bc------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 22:04:11 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@aelafted/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[Double Dispatch — Part 2: Visitor Pattern in Action]]></title>
            <link>https://medium.com/@aelafted/double-dispatch-and-visitor-design-pattern-7b8d531e0032?source=rss-a8d60de601bc------2</link>
            <guid isPermaLink="false">https://medium.com/p/7b8d531e0032</guid>
            <category><![CDATA[software-design-patterns]]></category>
            <category><![CDATA[double-dispatch]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[visitor-pattern]]></category>
            <dc:creator><![CDATA[Aelafseged]]></dc:creator>
            <pubDate>Thu, 05 Mar 2026 19:41:13 GMT</pubDate>
            <atom:updated>2026-03-05T19:44:41.553Z</atom:updated>
            <content:encoded><![CDATA[<p>In <a href="https://medium.com/compute-and-beyond/java-method-dispatch-part-1-static-vs-dynamic-be0634439edd">Part 1</a> we saw how method call works in most simplest form. As the vtable concept is a good starting point.</p><p>We already got the foundation that java’s dynamic dispatch is single dispatch: the JVM picks which method to run based on the runtime type of one single instance — the receiver object.</p><pre>Animal a = new Dog();<br>a.speak();   // at runtime → Dog → Dog::speak()</pre><p>The receiver is dynamic. But the method argument… not so</p><p><strong><em>The Method argument types are resolved at compile time, based on their declared(static) type — NOT their runtime type.</em></strong></p><p>Tha’ts the java’s limitations. And it matters the moment you need the method selection to depend on both the receiver and the argument type at runtime, aka <strong>Double Dispatch</strong>, and java doesn’t support it natively. Let’s say we have Two instances of Printer and Papers</p><pre>Printer (abstract)<br>├── PdfPrinter<br>└── InkjetPrinter<br><br>Paper (abstract)<br>├── A3Paper<br>└── LetterPaper</pre><p>our goal is when we are calling printer.print(paper) it should behave differently depending on <strong>which concrete printer</strong> and <strong><em>which concrete paper</em></strong> we are dealing with at runtime.</p><pre>class PdfPrinter {<br>    public void print() {<br>        System.out.println(&quot;PDF: default print&quot;);<br>    }<br><br>    public void print(Paper paper) {<br>        System.out.println(&quot;PDF: generic paper&quot;);<br>    }<br><br>    public void print(A3Paper paper) {<br>        System.out.println(&quot;PDF: A3 paper — large format render&quot;);<br>    }<br>}</pre><p>and we go straight into this trap:</p><pre>main() {<br>  PdfPrinter printer = new PdfPrinter();<br>  Paper paper = new A3Paper();   // declared as Paper, of instance A3Paper<br><br>  printer.print(paper);          // Output: &quot;PDF: generic paper&quot;  ← !!<br>                                 // Not A3Paper<br>}</pre><p>The compiler sees the declared type Paper and statically locks in print(Paper) at compile time. At runtime, it does not matter if the actual object is A3Paper — nothing changes at runtime for the argument!</p><p>The one ugly fix is — instanceof chains</p><pre>// please avoid this if you can<br>// — it breaks Open/Closed Principle and grows ugly fast<br>public void print(Paper paper) {<br>    if (paper instanceof A3Paper) {<br>        System.out.println(&quot;PDF: A3 paper — large format render&quot;);<br>    } else if (paper instanceof LetterPaper) {<br>        System.out.println(&quot;PDF: Letter paper render&quot;);<br>    }<br>    // Every new Paper subclass means editing this method<br>}</pre><p>Yes in java 17+ we have pattern matching in switch, that can make it slightly better, but the structural problem remains. <em>For every new Paper type we have to add a new branch in the method of Printer.</em></p><p><strong>Then comes — The visitor Pattern</strong> ( with Dramatic entrance of course)</p><p><strong><em>Because java can dispatch dynamically on the receiver(caller object). We turn the argument to become the receiver.</em></strong></p><p>Instead of printer figuring out what paper it got inside it’s method, we are asking<strong> the paper to accept a visit from the printer. </strong>This is the part we need to comfrotablly understand!</p><p>First we create the visitor that sits between the two objects</p><pre>// The Visitor — knows how to visit specific printer types<br>interface PrinterVisitor {<br>    void visit(PdfPrinter printer);<br>    void visit(InkjetPrinter printer);  // one method per concrete printer<br>}<br><br>// The Visitable — any paper that can accept a printer visitor<br>interface Paper {<br>    void accept(PrinterVisitor visitor);<br>}</pre><p>then the former printer argument which is Paper implements the accept method</p><pre>class A3Paper implements Paper {<br>    @Override<br>    public void accept(PrinterVisitor visitor) {<br>        visitor.visit(this);   // &#39;this&#39; is A3Paper — compiler knows the exact type here<br>    }<br>}<br><br>class LetterPaper implements Paper {<br>    @Override<br>    public void accept(PrinterVisitor visitor) {<br>        visitor.visit(this);   // &#39;this&#39; is LetterPaper<br>    }<br>}</pre><p>Very important point is, Inside A3Paper::accept, the compiler knows this is A3Paper — not just Paper type. Hencevisitor.visit(this) resolves to visit(A3Paper) statically.</p><blockquote><strong>The printer is the visitor, good way to remember this is, the orginal receiver becomes the visitor, after all we were navigating in it’s old method using if else chain. and the callee is the one that accepts the visitation as it was a former argument</strong>.</blockquote><pre>// a former method argument becomes the visitor&#39;s host<br><br>interface Paper {<br>    void accept(Printer printer);<br>}<br><br>//we have changed the Visitor interface to Printer and visit method to printOn, feels more natural,<br>// often name should define it&#39;s purpose, visitor and visit are too generic ;)<br>interface Printer {<br>    void printOn(A3Paper paper);<br>    void printOn(LetterPaper paper);<br>}<br><br>// === Paper types ===<br><br>class A3Paper implements Paper {<br>    @Override<br>    public void accept(Printer printer) {<br>        printer.printOn(this); // &#39;this&#39; = A3Paper, resolved at compile time<br>    }<br>}<br><br>class LetterPaper implements Paper {<br>    @Override<br>    public void accept(Printer printer) {<br>        printer.printOn(this); // &#39;this&#39; = LetterPaper, resolved at compile time<br>    }<br>}<br><br>// === Printer types === the visitor<br><br>class PdfPrinter implements Printer {<br>    @Override<br>    public void printOn(A3Paper paper) {<br>      //can use A3Paper object and deal with it<br>        System.out.println(&quot;PdfPrinter → A3: vector render, large format&quot;);<br>    }<br><br>    @Override<br>    public void printOn(LetterPaper paper) {<br>        System.out.println(&quot;PdfPrinter → Letter: standard PDF layout&quot;);<br>    }<br>}<br><br>class InkjetPrinter implements Printer {<br>    @Override<br>    public void printOn(A3Paper paper) {<br>        System.out.println(&quot;InkjetPrinter → A3: ink spread compensation, large&quot;);<br>    }<br><br>    @Override<br>    public void printOn(LetterPaper paper) {<br>        System.out.println(&quot;InkjetPrinter → Letter: standard inkjet layout&quot;);<br>    }<br>}<br><br>// === Main ===<br><br> main() {<br>        Printer printer = new PdfPrinter();<br>        Paper paper = new A3Paper();<br><br>        paper.accept(printer);<br>        // Output: &quot;PdfPrinter → A3: vector render, large format&quot;<br><br>        paper = new LetterPaper();<br>        paper.accept(printer);<br>        // Output: &quot;PdfPrinter → Letter: standard PDF layout&quot;<br><br>        printer = new InkjetPrinter();<br>        paper = new A3Paper();<br>        paper.accept(printer);<br>        // Output: &quot;InkjetPrinter → A3: ink spread compensation, large&quot;<br>    }<br></pre><p>Let’s look at the two dispatch hops we did. Let’s ruminate over this for a bit.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/839/1*nN4KgS93veQ9oWpSKtl70w.png" /><figcaption>double dispatch hop</figcaption></figure><p>Let’s expand the pattern which is what’s it’s often intended to do,</p><p>we can add different kinds of printers, we can just implement Visitor interface add all those visit() methods with the paper instances, and no extra changes needed on older implementations</p><p>Adding new paper type, we create a new class that implements the accept(Printer printer). then add the visit method on old implementations of the printers. a mini trade-off as we need to touch slightly a bit in here.</p><p>Yet each printer and paper are self contained, and they don’t need to know with eachother. where the visitor is the split or the bridge which every way you see it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/447/1*ErGugb7SnPACpB2O7sdgHg.png" /></figure><p>we are intentionally splitting it!</p><blockquote>“To release the power of the sea. One must divide.”</blockquote><blockquote>Pirates of the Caribbean: Dead Men Tell No Tales</blockquote><p>this pattern is very famous in collection in such fashion as well.</p><pre>List&lt;Paper&gt; printQueue = List.of(new A3Paper(), new LetterPaper(), new A3Paper());<br>Printer printer = new PdfPrinter();<br><br>for (Paper paper : printQueue) {<br>    paper.accept(printer);   // each paper routes itself correctly<br>}</pre><p>Why this pattern is slightly odd for many people at first sight(it certainly was for me). in my humble opinon here are two reasons</p><ol><li>Many java materials are shy of pointing out the java’s limitations with double dispatch and just go straight to the the pattern implementation.</li><li>why not use instanceof ? then it will require editing all classes that have those chains and test cases.</li></ol><p>To recap</p><p>in <a href="https://medium.com/compute-and-beyond/java-method-dispatch-part-1-static-vs-dynamic-be0634439edd">Part 1</a>. we saw java dispatch- where java picking method based on one receiver’s runtime type, while arguments stays at compile time.</p><p>in this part, the java’s limitations revealed itself when we needed runtime behaviour to depend on two types simultaneously. we avoided the instanceof and implemented the Visitor Pattern by chaining two single dispatches- one on the visited object, one on the visitor — simulating double dispatch in java ;).</p><p><em>Thank you for reading. give your thoughts on the comment. </em><a href="https://medium.com/compute-and-beyond/java-method-dispatch-part-1-static-vs-dynamic-be0634439edd"><em>Part 1</em></a><em> is here</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7b8d531e0032" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Java Method Dispatch — Part 1: Static vs Dynamic]]></title>
            <link>https://medium.com/compute-and-beyond/java-method-dispatch-part-1-static-vs-dynamic-be0634439edd?source=rss-a8d60de601bc------2</link>
            <guid isPermaLink="false">https://medium.com/p/be0634439edd</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-design-patterns]]></category>
            <category><![CDATA[visitor-pattern]]></category>
            <category><![CDATA[jvm]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Aelafseged]]></dc:creator>
            <pubDate>Tue, 24 Feb 2026 10:30:44 GMT</pubDate>
            <atom:updated>2026-03-05T19:46:53.729Z</atom:updated>
            <content:encoded><![CDATA[<p>O que isso?</p><p>When we call a method in Java, the JVM has to decide which version of this method should run. That decision process is called <strong>method dispatch. </strong>It sounds simple but this mechanism the backbone for polymorphism, inheritance and design patterns like Visitor ( will be in <a href="https://medium.com/@aelafted/double-dispatch-and-visitor-design-pattern-7b8d531e0032?postPublishedType=repub">Part 2</a>).</p><p>We have two type. <strong>Static dispatch</strong>(resolved at compile time) and <strong>dynamic dispatch</strong>(resovled at runtime)</p><p><strong>Static Dispatch — Straight forward, decided before your code even runs</strong></p><p>The compiler already knows exactly which method to call. There’s no ambiguity, no runtime lookup, it’s wired in at compile time using <strong>direct linking</strong>.</p><p>this applies to</p><ul><li>private methods</li><li>static methods</li><li>final methods</li><li>Constructors</li></ul><pre>class MathUtils {<br>    // Static method, compiler knows exactly which method this is<br>    public static int add(int a, int b) {<br>        return a + b;<br>    }<br><br>    // Overloaded method, resolved at compile time by argument type<br>    public void print(String message) {<br>        System.out.println(&quot;String: &quot; + message);<br>    }<br>    <br>    public void print(int number) {<br>        System.out.println(&quot;Int: &quot; + number);<br>    }<br>}<br><br>public class Main {<br>    public static void main(String[] args) {<br>        MathUtils.add(2, 3);       // Direct call<br><br>        MathUtils utils = new MathUtils();<br>        utils.print(&quot;hello&quot;);      // Compiler picks print(String) <br>        utils.print(42);           // Compiler picks print(int)   <br>    }<br>}</pre><p>we can see the compiler picks the right one based on the declared type of the arguments, and also static dispatch</p><p><strong>Dynamic Dispatch — The JVM Decides at Runtime</strong></p><p>Here we have inheritance, when you override a method in a subclass, which version runs depends on the <strong>actual object at runtime</strong>, not the reference type used to call it. also known as<strong> late binding</strong> or <strong>runtime binding</strong>.</p><blockquote>Method arguments will be discussed in<a href="https://medium.com/@aelafted/double-dispatch-and-visitor-design-pattern-7b8d531e0032?postPublishedType=repub"> part 2</a>*</blockquote><pre>class Animal {<br>    public void speak() {<br>        System.out.println(&quot;...&quot;);<br>    }<br>}<br><br>class Dog extends Animal {<br>    @Override<br>    public void speak() {<br>        System.out.println(&quot;Woof!&quot;);<br>    }<br>}<br><br>class Cat extends Animal {<br>    @Override<br>    public void speak() {<br>        System.out.println(&quot;Meow!&quot;);<br>    }<br>}<br><br>public class Main {<br>    public static void main(String[] args) {<br>        Animal a = new Dog();   // Reference type: Animal<br>        a.speak();              // Output: Woof!  runtime decides<br><br>        a = new Cat();<br>        a.speak();              // Output: Meow!  runtime decides<br>    }<br>}</pre><p>The reference is typed as <em>Animal</em>, but the jvm looks a what the variable <strong><em>a </em></strong>actually points to and dispatches based on it. which is <strong>polymorphism </strong>at it’s heart.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*ACXNxcYRL4WgGPMLeW757A.jpeg" /></figure><p><strong>How the hell does the JVM do this? — The Virtual Table(vtable)</strong></p><p>Under the hood, JVM uses a datastructure called a virtual table. Every class that has a vtable, even the ones with no methods have a vtable (inherited from Object class)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/947/1*fLRku-SibZZvmc1NxnqJOw.png" /><figcaption>JVM Dynamic Dispatch (Runtime)</figcaption></figure><p>when you call a.speak(): the jvm follows the vtable pointer,looks up for the method in that object’s vtable then goes to the correct implementation.</p><p>The dog’s vtable pint to AnimalDog::speak(), the cat’s vtable points to AnimalCat::speak(). The reference type (Animal) is irrelevant for dispatching— the object itself carries the map to its own methods.</p><p>The compiler handles the easy cases statically, the JVM handles the rest at runtime through the vtable mechanism.</p><p>This foundation is important because<a href="https://medium.com/@aelafted/double-dispatch-and-visitor-design-pattern-7b8d531e0032?postPublishedType=repub"> Part 2 </a>builds directly on it: we will see what happens and java’s limitations for dispatch across two objects simultaneously — that will be handled by double dispatch techinque and vistor design pattern.</p><p><a href="https://medium.com/@aelafted/double-dispatch-and-visitor-design-pattern-7b8d531e0032?postPublishedType=repub"><em>Part 2</em></a><em>: Will drop in a week — covering double dispatch and visitor design pattern. Drop a comment and follow for more.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=be0634439edd" width="1" height="1" alt=""><hr><p><a href="https://medium.com/compute-and-beyond/java-method-dispatch-part-1-static-vs-dynamic-be0634439edd">Java Method Dispatch — Part 1: Static vs Dynamic</a> was originally published in <a href="https://medium.com/compute-and-beyond">compute and beyond</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Spiderman — No way Home… a story of second chance]]></title>
            <link>https://medium.com/@aelafted/spiderman-no-way-home-a-story-of-second-chance-a424bc813c4a?source=rss-a8d60de601bc------2</link>
            <guid isPermaLink="false">https://medium.com/p/a424bc813c4a</guid>
            <category><![CDATA[spider-man]]></category>
            <category><![CDATA[marvel]]></category>
            <category><![CDATA[marvel-cinematic-universe]]></category>
            <dc:creator><![CDATA[Aelafseged]]></dc:creator>
            <pubDate>Sun, 16 Jan 2022 12:15:30 GMT</pubDate>
            <atom:updated>2022-01-16T12:15:30.449Z</atom:updated>
            <content:encoded><![CDATA[<h3>Spiderman — No way Home… a story of second chance</h3><p>… Spoiler alert ahead !</p><p>Spiderman… a story of a teenager co-created by late Stan Lee has inspired young and old, across the world and possibly throughout the possible multiverse. Skipping the introduction story, the latest movie was one of the finest movie releases after a near disappointment Venom and Eternals… personally I found it an insult to our friendly neighbour to write about those movies here, thus just Spidey only!</p><p>Spider man the youngest avengers who manages to stand shoulder to shoulder with gods and galaxies bad asses and fought space monsters, was the only super hero who had the courage to mock Thanos while punching him left and right in his own planet. Also recently after his bleep he again pissed off Thanos by running away with his only gauntlet, then after the demise of Thanos he had to face much complicated challenges after defeating Mysterio in his Euro-trip where he was black mailed as the bad guy.</p><p>And the world was quick to judge this poor kid, and worst part is that, not a single super hero came to help him( that’s a thing with solo hero movies right?) well except for Dr. Strange… as for this version of Spiderman he was not bestowed upon the wisdom of “with great power comes great responsibility”🙈 … yet, so he made a horrible teenage choice to make a quick fix, a demand of erasing the memory of the entire planet of the knowledge of Peter Parker as spider man.</p><p>As for our amazing Dr. Strange, he owe him his life as he was once saved by this kid from overly powerful supervillain by interrupting an extremely sophisticated torturing device(I’m sure some world dictators were taking a note and passing it their henchman scientist to replicate it ) by coming up with an idea of the 80’s movie, Alien! and to the surprise of everyone including the guy who got killed himself, Thanos lost his favourite henchman and scientist.</p><p>As anyone would have guessed, doing anything challenging be it giant magic spell or even coming up with 90’s jokes in front of a teenager is always a disaster and yes it brought havoc to space time continuum... The Wizard as always is full of ego and yes to please this kid which goes against what the ancient one has seen in this guy, end up brining all the major super villains from other multiverses. Doctor Oc iconic line was dropped, except he was easily overpowered by spidey nanotech suite, Dr. Strange went fully Trumpized. He wanted to make the MCU universe great again by sending everyone back where they came from, starting with a filthy dungeons in his HQ basement. Bringing Dr Osborn tend to be a very huge take, the rest brought some fancy fights but all ended up in the dungeons.</p><p>As for Dr. Osborn his good sides already made a good friend with his Spidey auntie and suddenly conquered the kid’s heart. He is old, lost was still trying to be the good guy, especially when he broke his silly mask and went off everyone was cheering, and the kid was suddenly in odd with our wizard, beat him in geometry fight and trapped him in few minutes of fighting in his own mirror dimension. We should give some credit to this kid right? In Civil war he single handedly kick both Winter Soldier and Falcon and made an amazing fight with Captain Steve. Now his latest victim of his fast thinking and fighting skill was our Dr Strange a guy who once saved our planet from Dormamu with ingenious plan and also saved the entire universe by outsmarting Thanos.</p><p>The kid was so naïve he brought the entire supervillains to his aunties boyfriends place with sheer belief that no one would double cross him, Dr Osborn start having an episode, and he managed to do beyond horrible, in a very unexpected turn of event our beloved aunt May lost her life but she managed to throw the most iconic Spiderman line. Maybe we were getting used to the death of uncle Ben or not sure but this particular death scene should put her right onto the Oscars queue. Added to this was Willem Dafoe acting skills he just added fuel to the dramatically heart wrenching moment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/768/1*cPX3a0_LlWTlg4GmwM5LHA.jpeg" /></figure><p>At this point everything was beyond sad… Peter was on verge of turning dark when his best friend and MJ accidentally brought both spider men from the other universes. The cinema reaction was Avengers level insane. The teaming up those three characters should be recorded as one of the most satisfying moment in recent cinema history! kids as young as 10 were cheering with same enthusiasm as adults in their late 30’s. We are living in time people in 20’s that haven’t watched or even heard about Titanic😳.</p><p>The three heroes had to put up a fight while creating a fix to all the supervillains, that’s what superheroes do right? some villains (ex-villains ) on their sides they had to make an incredible fight, MJ had a huge fall, almost identical to Gwen Stacy … and had a remarkable scene which lit the cinema to the roof 🤩.</p><p>They saved all the villains, the spell was overridden to fix the old spell where everyone forgets him and the heroes had their kumbaya moments before going back to their own universes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WSn8hHY-ZfyilgnGYPuA2Q.jpeg" /></figure><p>In the end our hero end up alone which gives us such heart breaking moment as this kid is going through a lot.</p><p>It was by far an extremely befitting ending chapter for our Spiderman franchise, it managed to bring decades old characters, hope and despair, frustrations and excitements to one grandeur finale and gave almost everyone a second chance to undo things perhaps if undoing is not possible then coming in peace with what has befallen, honestly this is a life lesson we all need to find either as adults or just teenagers trying to figure the world by their own eyes or a senior citizen who needs to accept the unforgiving wrath of time.</p><p>Until next time✌🏾</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a424bc813c4a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kotlin for Java Developers part 3]]></title>
            <link>https://medium.com/compute-and-beyond/kotlin-for-java-developers-part-3-25c168695e90?source=rss-a8d60de601bc------2</link>
            <guid isPermaLink="false">https://medium.com/p/25c168695e90</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[kotlin-beginners]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Aelafseged]]></dc:creator>
            <pubDate>Tue, 11 Feb 2020 10:43:11 GMT</pubDate>
            <atom:updated>2020-02-11T10:43:11.762Z</atom:updated>
            <content:encoded><![CDATA[<p>This is the final part of three parts series of introduction to kotlin for java developers, which can be found <a href="https://medium.com/compute-and-beyond/kotlin-for-java-developers-part-1-dff945127885">here- part 1 </a>and <a href="https://medium.com/compute-and-beyond/kotlin-for-java-developers-part-2-17085477d8ad">here- part 2</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*PPf2L1xPRoUztGQfFAi8HA.jpeg" /><figcaption>Kotlin dominating java?</figcaption></figure><blockquote>1. Interface</blockquote><p>Similar to java they are used as a contract for classes to be implemented, they have default methods, and also properties that functions in a limited way… it’s a huge step from what java’s no fields or properties stance. Let’s discuss on this unique feature. You can’t have properties declared within primary constructor, nor can’t you have constructor in interface( which is understandable).</p><p>The class that is going to implement the interface need to implement the methods(dah!!!) and also provide value to the properties, I prefer adding the properties inside the primary constructor and use the implemented methods within the body of the class (the java way… somehow)</p><pre><strong>interface  MyInterface{<br>    val name: String // a property that need to be overridden<br>    fun execute(sum:Int) // a member function to be overriden<br>    fun excuteSthElse(){ // a default method<br>        <em>println</em>(&quot;default method...&quot;)<br>    }<br>}</strong></pre><p>the above interface can be implemented by a class as follows</p><pre><strong>class MyClass( override val name: String): MyInterface{<br><br>    override fun execute(sum: Int) {<br>        <em>println</em>(&quot;overriding the interface method...&quot;)<br>    }<br>}</strong></pre><ul><li>the implements keyword is replaced by :</li><li>the property is overriden by the inline constructor value prefixed by the keyword override</li><li>so does goes for the function that need to be overrriden by the implementing class, (with a keyword override not annotation)</li></ul><blockquote>2. Lambda, higher order function</blockquote><p>My first few hours of reading it made met thought it was the next tough subject in programming next to generics or multithreading… but what it really need is if you had played with f(g(x)) in highschool math then you are all good to go with it. that is is!! it’s just function accepting function.</p><p>“<strong><em>This is a place where you treat a function as a variable</em></strong>”. Same as there is a class type, we have function type in kotlin. It can be a parameter variable or a returnee from a function. Meaning you can send a function to a function, also a function can return a function as a returnee<strong><em> 😉 </em></strong>It took me quite a while to come around with the concept. And here is how it works. I will try my best to explain it in few min… let’s start with a a simple function</p><pre><strong><em>f(x) //here the function f has an input variable of x,<br>// then taking this to a higher order function<br>f(g(x)) ==&gt; the function takes g(x) as an input variable</em></strong></pre><p>now let’s see a function that takes a function as an input parameter</p><pre><strong>fun killSth(exercise:()-&gt;Unit){<br>    exercise()<br>}</strong></pre><p>left side from the colon which is the variable <strong>exercise ☝️</strong>refers to the incoming function, the right side ()-&gt;Unit is a function type; this one expects a function with no parameter that returns nothing(Unit). Let’s see ways how function call can be done.</p><blockquote>1. Variable way</blockquote><p>declaring a variable to be a function type,</p><pre><strong>val dosth:() -&gt; Unit={<br>    <em>println</em>(&quot;do sth...&quot;)<br>}</strong></pre><p>Here we have defined our function which is referenced by a variable <strong>dosth </strong>as a lambda function. we have no <strong>fun </strong>keyword and no <strong>function name.</strong> we can pass this variable to the function <strong>killSth</strong></p><pre><strong>killSth(dosth)</strong></pre><p>mathematically it is f(g(x)) … BUT unlike math where the result of g(x) is passed on to the function of f(?). It is the killSth function that calls doSth function in it’s closure using the reference variable <strong>exercise() … yes with brackets.</strong></p><blockquote>2. Function Referencing way</blockquote><p>Instead of being referenced by a variable the function is declared ordinarily then we pass it to the killer function</p><pre><strong>fun doSth(){<br>    <em>println</em>(&quot;do sth..&quot;)<br>}<br>killSth(::<em>doSth</em>)</strong></pre><p>it’s similar to java’s method reference, here there is nothing behind the double colon; because the function is within the same package/module.</p><blockquote>3. Lambda and Anonymous way</blockquote><p>Taking the function as parameter bit further, instead of declaring the function with <strong>variable reference or not</strong> we can directly pass functions as an expression… turning the function into lambda function…</p><pre><strong>val doSth ={<br>    <em>println</em>(&quot;do sth...&quot;)<br>}</strong></pre><p>we can call the killer function with the lambda function from above</p><pre><strong>killSth({<em>doSth()}</em>)</strong></pre><p>let’s start working with parameters… here work function is going to be an input.</p><pre><strong>fun workFunction(job:String) {<br>    <em>println</em>(&quot;working on $job&quot;)<br>}</strong></pre><p>and it can be converted into lambda as the following</p><pre><strong>{job:String -&gt; println(&quot;working on $job&quot;)}</strong></pre><p>let’s make an enclosing function that takes a function as a parameter.</p><pre><strong>fun doExecute(act:(job:String)-&gt;Unit){<br>      act(&quot;coding&quot;)// here we are calling the function,<br>      // that arrived as a parameter and execute the body<br>// by applying &quot;coding&quot; for the string parameter of the            // enclosed function<br>}</strong></pre><p>unlike our math world, the enclosing function passes the parameter data to the enclosed function by calling it… now we have lambda function and enclosing function. let us call the <strong>doExecute </strong>function</p><pre><strong>doExecute({job:String -&gt; <em>println</em>(&quot;working on $job&quot;)})</strong></pre><p>upon this call the outer function(<strong>doExecute</strong>) calls the inner method by the variable <strong>act </strong>and send paramter value of “coding” to the lambda function… the lambda function will complement the variable with it’s content to display the result <strong>working on coding</strong></p><p>All this function within functions came with a bonus, unlike java the lambda expression/anonymous function can access the enclosing function variables, or its closure (the technical term). In java the variable had to be final or effectively final.</p><blockquote>3. with and apply</blockquote><p>They allow us to perform multiple operations on same object without the headache of calling the object name. But coming from java you might think of builder pattern, but please DO NOT !!! You do realize that the lines of code you need to write for the builder class and all the repeating fields and individual methods…😡 I had one article <a href="https://medium.com/compute-and-beyond/understanding-builder-pattern-like-a-snack-14b7ec03333d">here</a>. where were you kotlin? when i was writing hundreds lines of code!</p><p>lets start with — <strong>with</strong></p><pre><strong>val dartObject = Dart()<br><em>with</em>(dartObject){<br>   </strong>//have access to the dartObject properties, member <br>//functions without referencing the object explicitly<br> //<strong>dartObject </strong>becomes the receiver object<strong><br>}</strong></pre><p>also our <strong>apply </strong>function does what <strong>with </strong>does plus it returns the receiver object, so you can chain call</p><pre><strong><em>apply</em>(dartObject){<br>//same as similar object<br>}.create()</strong></pre><p>Yeap these extension functions makes java’s builder pattern a caveman drawing yea you heard me “cave builder”</p><blockquote>4. Generics … invariance Vs. covariance</blockquote><p>since i have written about java generics <a href="https://medium.com/compute-and-beyond/understanding-generics-like-a-cup-of-tea-part-1-a38b02731b82">here</a> and <a href="https://medium.com/compute-and-beyond/understanding-generics-like-an-oracle-does-part-ii-2dbee57f61a">here</a>, i wouldn&#39;t repeat what’s in java but rather what’s not in it.</p><pre><strong>class Human{}<br>class Student extends Human{}<br>Human someStudent = new Student();</strong></pre><p>Back in java if two classes have parent child relationship then, it was acceptable to write child class as a type of the parent… polymorphism, same works with kotlin…</p><p>but you can’t do it with Generics! because … let’s take a moment</p><pre><strong>open class Solid(val name: String){<br>    }<br>class Rock(override val name:String) : Solid(name){<br>    }<br>//having  a polymorphic object is valid as follows<br>val  rock : Solid = Rock(&quot;granite&quot;)</strong></pre><p>we have two parent and child classes, let’s make one generic class</p><pre><strong>class GenericMatter&lt;T&gt;(val someField:T){<br>}</strong></pre><pre><strong>val genericRock: GenericMatter&lt;Solid&gt; =<br> GenericMatter&lt;Rock&gt;(Rock(&quot;sedimentary&quot;))</strong></pre><p>here is a catch!!! the GenericMatter containing a rock, and another GenericMatter expecting a solid, doesn’t bring the parent child relationship to the containing class. Two childhood friends living in two different countries does not make the two countries friends/partners. 👏👏 This is by far the best explanation i can come up with Generic polymorphic paralysis — oh look i just invented really fancy phrase. or the real word is <strong>invariant</strong> [it’s no medical term… it does sound cool, and understandable 🤔]</p><p>But kotlin didn’t give up like java did, it prefixed the keyword <strong>out </strong>before the Type variable in the generic class declaration as to artificially preserve the relationship of the classes in the generic level…. now it has became <strong>covariant</strong></p><pre><strong>class GenericMatter&lt;out T&gt;(val someField:T){<br>}</strong></pre><p>and you are good to go.</p><p>thank you for staying with me in the three parts series of introduction to kotlin… I hope you found it informative… looking forward to hear you experience in kotlin and java, 13 and 14 hopefully. and as always clap👏👏, comment and share so it can reach other developers.</p><p>Happy coding and will come back with more coding topics</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=25c168695e90" width="1" height="1" alt=""><hr><p><a href="https://medium.com/compute-and-beyond/kotlin-for-java-developers-part-3-25c168695e90">Kotlin for Java Developers part 3</a> was originally published in <a href="https://medium.com/compute-and-beyond">compute and beyond</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kotlin for Java Developers part 2]]></title>
            <link>https://medium.com/compute-and-beyond/kotlin-for-java-developers-part-2-17085477d8ad?source=rss-a8d60de601bc------2</link>
            <guid isPermaLink="false">https://medium.com/p/17085477d8ad</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[Aelafseged]]></dc:creator>
            <pubDate>Tue, 04 Feb 2020 14:19:43 GMT</pubDate>
            <atom:updated>2020-03-03T12:17:42.129Z</atom:updated>
            <content:encoded><![CDATA[<p>Greetings again. in our <a href="https://medium.com/compute-and-beyond/kotlin-for-java-developers-part-1-dff945127885">part 1</a> we delved into the basics of kotlin. in this part we will try to cover functions and half of object oriented concepts in comparison to java.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/405/0*vG2mC0J2j6XUnAl0.jpeg" /></figure><blockquote><em>1. Basic Functions</em></blockquote><p>functions in kotlin are much more than functions we knew in java. It can be declared inside a class — <strong>member functions </strong>or outside any classes, thus becoming equally important as a class can be. In kotlin you can create a file and have plenty of classes and functions — all looking at each other shoulders 😎</p><pre><strong>fun funName(inpu:&lt;parameterType&gt;):&lt;return type or Unit&gt;{<br>  return inpu<br>}</strong></pre><p>function return type is written far to the right, for a function that returns nothing, you type <strong>Unit (</strong>i don’t know why they have throw away void for this unusual keyword<strong>) </strong>or you can just type nothing 🖐</p><p>we can condense some functions to this level, it took lambda expression one level further</p><pre><strong>fun addNumbers(a:Int, b:Int)= a+b</strong></pre><blockquote><em>2. Default Arguments and Named parameters</em></blockquote><p>this is the way kotlin throwing away java’s functions overloading(same function names with different parameters). default value can be added to function’s signature’s parameter. first let’s explore default arguments.</p><pre><strong>fun callHome(header: String=&quot;Hello&quot;, body:String=&quot;Dear Home&quot;){}</strong></pre><p>here we have a function called callHome, and we are giving our function caller the flexibility to call this method in such a ways</p><pre><strong><em>callHome</em>() // can call with empty parameters <br><em>callHome</em>(&quot;Olla&quot;) // can call with only the first parameter <br><em>callHome</em>(&quot;Selam&quot;,&quot;Dear family&quot;)//all the parameters</strong></pre><p>i know … 😁 function overloading with one function. i think python has such feature too but not java. it will get even better with named parameters.</p><p>It gives the default parameter feature a ➕, in typing the parameter values the caller can pinpoint which argument is she/he is referring to.</p><pre><strong><em>callHome</em>(body=&quot;ahlen jemea&quot;,header = &quot;merhaba&quot;)</strong></pre><p>here the function caller knows clearly what parameters are being referred by the calls. I think this is the last innovation programming languages can innovate on function calls.</p><blockquote><em>3. Variable Number of Arguments</em></blockquote><p>Back in java we used to have <strong>functionName(int… input) </strong>to receive arbitrary number of parameters but in kotlin we have <strong><em>vararg </em></strong>keyword. meaning <strong>functionName(vararg input :Int) </strong>but the way we call this methods needs bit work, to send array we need to prefix it with * (spread operator) some says it lets the contents within the array object to spread their wings…(or is it?!)</p><pre><strong>val inp = <em>arrayOf</em>(1,3,4,5)<br>  //with the spread operator we are adding a method <br>  //that fix the type mismatch from Array&lt;Int&gt; into IntArray    <br>  <em>displayData</em>(*inp.<em>toIntArray</em>())fun displayData(vararg  input: Int){ <br>    for (temp in input) <em>println</em>(temp)<br>}<br>//apart &quot;vararg&quot;keyword it&#39;s a normal function</strong></pre><p>honestly I am bit disappointed on this part of dealing with type conversion methods! seriously kotlin!!! an array of integer has to be an array of integer SIMPLE!!! 😠 Array&lt;Int&gt; Vs. IntArray</p><blockquote><em>4. Extension Functions</em></blockquote><p>Here comes one of my favorite kotlin features. In java when we want to extend a class functionality we</p><ol><li>either extend that class, then override it’s methods,</li><li>or if we have access to it we can add functions into it</li><li>i’m sorry there is no third option in java 😆 yea just those two, if you are thinking of Utility class with bunch of methods… well that is considered cheating.</li></ol><p>In kotlin we can write a simple functions(like the ones above 👆) and make them extend our intended classes including the java classes 😲. Let’s see how we can add functionality to a String class.</p><p><strong>receiver type</strong>- the class we are adding the functionality on</p><p><strong>receiver object- </strong>this is the instance of that type, which we will tweak with our extension function</p><pre><strong>fun String.punch(arg: Int): String{<br>    return &quot;$this  punched $arg -- people&quot;<br>}</strong></pre><p><strong>String </strong>is the the receiver type and <strong>$this </strong>is the instance of the String type , this function has integer input, and returns String object. the function name is punch. it can be used by any String object!!! the magic is in the function name [<strong>String.punch</strong>] the function punch extending the String class.</p><pre><strong>val name= &quot;Joe&quot;<br>name.punch(2) // and the output is as follows <br>&gt;  Joe punched 2 -- people</strong></pre><blockquote><em>5. Infix functions</em></blockquote><p>Back in datastructure and algorithm courses, we had this infix(a+b), prefix(+ab), and postfix(ab+) operators. kotlin is bringing a simple way of calling functions in infix way. for instance if we have a function <strong>punch(count: Int){} </strong>then calling this function can go as the following</p><p><strong>Object.punch(200) // </strong>object calling a member function with parameter</p><p>that’s all we know how to call a function from epoch of time</p><p>Let’s declare the infix function</p><pre><strong>infix fun String.punch(arg: Int): String{<br>    return &quot;$this punched -- $arg times&quot;<br>}</strong></pre><p>Yes you need to add <strong>infix </strong>keyword to make it <strong>infixable </strong>😉</p><p>then</p><pre><strong>val dude= &quot;Agent Ethen&quot;<br>dude <em>punch 12 // object - method - parameter </em></strong>👌<strong><em><br>the output is &gt; Agent Ethen punched 12 times</em></strong></pre><p>simple ha?! even second grader can understand this code, dude punched 12 times</p><p>we got few caveat though</p><ol><li>Only one parameter is accepted … i know … hiding your parameters in arrays and send it using expand operator won’t work either 😑</li><li>nor it accepts named parameters</li><li>the function must be either an extension function like the one we did above OR member function(after all an object of some type need to call it)</li></ol><p>the rules are pretty strict but it brings some degree of flexibility</p><blockquote><em>6. Operator Overloading</em></blockquote><p>in our part 1 article we mentioned how kotlin do not allow simple concatenation between numeral and string because it deals with higher level of sophistication that java hasn’t … yet.</p><p>they are <strong>specialized built-in functions</strong> you integrate into your object’s classes: in two ways</p><ol><li>if you have a custom class you can just override those methods in your liking</li><li>or if you don’t own the object’s type or the class, you make extension function</li></ol><p>let’s try the second way… we overload a function prefixed with <strong>operator </strong>keyword and we call the appropriate operator on that object</p><pre><strong>operator fun Int.plus(str: String)= this.toString() + str</strong></pre><p>this extension function is overloading a unique function named <strong>plus</strong>, which takes one object as parameter, and it’s up to you to come up with it’s functionality, 👆 we just concatenate the integer with string.</p><pre><strong>var firstName = &quot;Aelaf&quot;<br>var age = 31<br><em>println</em>(age+firstName) // we are overloading the + operator</strong></pre><p>there are more than a dozen operator overloading functions available <a href="https://kotlinlang.org/docs/reference/operator-overloading.html">here</a> . this is kotlin implementing polymorphism for operators not only in classes methods; we will deal with method polymorphism in the next part.</p><blockquote><em>7. Class</em></blockquote><p>By a definition it is a template by which all object oriented programming begins with. It is combination of data(fields) and methods that manipulate the data and possibly interact with other classes.</p><p>In java creating a simple Human class with two fields is as follows</p><pre><strong>class Human{<br>    private final String fullName;<br>    private String placeOfOrigin;<br>    public  Human(String name, String origin){<br>        this.fullName = name;<br>        this.placeOfOrigin = origin;<br>    }</strong></pre><pre><strong>    public String getFullName() {<br>        return fullName;<br>    }</strong></pre><pre><strong>    public String getPlaceOfOrigin() {<br>        return placeOfOrigin;<br>    }</strong></pre><pre><strong>    public void setPlaceOfOrigin(String placeOfOrigin) {<br>        this.placeOfOrigin = placeOfOrigin;<br>    }<br>}</strong></pre><p>with a constructor and good old getters and setters methods</p><p>Now let’s see and falls in love with how Kotlin creates a class, which is my favorite way of declaring a class.</p><pre><strong>class Human(name: String, place:String){<br>    val fullName = name<br>    var placeOfOrigin = place<br>    init {<br>        //place to initialize fields/properties<br>    }<br>}</strong></pre><p>while declaring the class you can have the constructor signature in one line.The two properties are being assigned value straight from the constructor’s parameters. they do have getters and setters in background. The <strong>init </strong>block is similar to TypeScript and other languages, since the constructor don’t have body, this is where you <strong>optionally </strong>write your initialization code; also you can have plenty of init blocks.</p><pre><strong>val human = Human(&quot;Thor&quot;, &quot;Asgard&quot;)<br>human.placeOfOrigin = &quot;Norway&quot;</strong></pre><p>on creating an instance, we don’t use <strong>new </strong>keyword. and also do notice the <strong>val </strong>and <strong>var </strong>keywords prefixing the properties.</p><blockquote><em>8. Constructors</em></blockquote><p>Yes we can still have overloaded constructors, but not using the <strong>class names </strong>but using the keyword <strong>constructor </strong>and any amount parameters</p><pre><strong>var characterAge : Int = 0<br>constructor(name:String, place:String, age:Int):this(name,place){<br>    characterAge = age<br>}</strong></pre><p>yes it’s nothing similar to what constructor overloading is done in java, we will come across <strong>interfaces </strong>and <strong>super classes </strong>but this constructor is extending the parent constructor. Kotlin has a thing on chunking code on the declaration part, 🤔 wouldn’t you agree?!</p><blockquote><em>9. Inheritance</em></blockquote><p>As much as the syntax looks a bit like javascript and loose and all, All classes and methods are by default final… they can not be extended. Thus if you need this feature you need to prefix the class with <strong>open </strong>keyword. Let’s create the parent class</p><pre><strong>open class Person(name: String){<br>     var fullName = name<br>     open fun walk(){<br>         <em>println</em>(&quot;$fullName is walking&quot;)<br>         }<br>     }</strong></pre><p>then you extend this parent class as follows</p><pre><strong>class Student(name:String ,age:Int):Person(name){<br>     val studentAge = age<br>     fun study(){<br>         <em>println</em>(&quot;${this.<em>fullName</em>} age is $studentAge&quot;)<br>         }<br>     }</strong></pre><p>the student class extends the person class by calling the primary constructor in it’s declaration, thus the student object have reference to it’s parent’s method( notice we prefixed it with <strong>open </strong>keyword too).</p><pre><strong>val stud = Student(&quot;Joe&quot;, 22)<br> stud.walk()<br> stud.study()// student object can walk and study</strong></pre><p>the parent’s class method can be effectively overridden like java… in the child class we can have a walk method with override keyword (in java it was optional to add @override annotation )</p><pre><strong>override fun walk(){<br>     super.walk()<br>     <em>println</em>(&quot;${this.<em>fullName</em>}dub step to school&quot;)<br>     }</strong></pre><p>we are calling the parent’s method with super keyword then inside the print statement calling the parent’s property using child’s object reference.</p><p>to block further inheritance chain down to the grandchild, and great grandchild we can add <strong>final </strong>keyword on the member function or class of the extending child. Meaning no more inheritance below that child. 😐</p><blockquote><em>10. Upgrading constructor</em></blockquote><p>in the earlier kotlin classes ☝️ we were declaring properties separately then it was assigned from the constructors parameter values… but we can also make the constructors parameters “the properties”</p><pre><strong>class People(val name:String, var place:String){<br>     }</strong></pre><p>all you need is prefixing the parameter variables with <strong>val</strong>(for immutable values) and <strong>var</strong>(for mutable values)… then you have properties.</p><blockquote><em>11. from POJO TO POKO or Data classes?</em></blockquote><p>In java pojo(plain old java object) we basically deals with data that is retrieved and send to a repository. The main job is computation on list or array of the objects for holding the data. For such tasks the two methods that instantly comes to our mind are <strong>equal()</strong> and <strong>hashcode()</strong> methods</p><pre><strong>@Override<br> public int hashCode() {return super.hashCode();}<br> <br> @Override<br> public boolean equals(Object obj) {return super.equals(obj);}</strong></pre><p>Because our business demands is much different from default implementations, we need to change it… first using java then kotlin then in the end abandoning them in kotlin 😎</p><pre><strong>@Override<br> public int hashCode() {return this.fullName.hashCode();}//1<br> @Override<br> public boolean equals(Object obj) {<br> if(obj instanceof Human){//2<br> return this.fullName.equalsIgnoreCase(((Human) obj).fullName);<br> }<br> return false;<br> }</strong></pre><p>//1 we are creating hash value for the objet’s property(fullName)</p><p>//2 we check if the object being passed in is type Human and do our comparison (after explicitly casting it to Human type)</p><p>nothing new in it. now let’s see how kotlin does it</p><pre><strong>override fun hashCode(): Int {return Objects.hash(name)} //like java<br> override fun equals(other: Any?): Boolean {//1🤔<br> return other is People &amp;&amp; name == other.name //2🤔🤔<br> }</strong></pre><p>//1 in kotlin the super type is <strong>Any </strong>unlike <strong>Object …</strong>(the ? allows null as parameter)</p><p>//2 the code <strong>other is People</strong> checks if the object is type People and cast it to type People — check type and casting in one shot! then ask for boolean expression by checking if the current instance name and the other name are equal then return the result.</p><p>all the above code can be eliminated using kotlin’s data class feature, where the hashcode/ equals/ toString() methods don’t need to be implemented. It’s a similar fate to getters and setters methods where properties are used in stead).</p><p>property that is assigned in the primary constructor only will be used by the above mentioned background methods. no more boilerplate code 😃</p><pre><strong>data class Alien(val name: String){<br>    var age:Int =1800<br>}</strong></pre><p>Kotlin got your back by generating <strong>hashcode</strong>, <strong>equal</strong>, <strong>toString </strong>methods using <strong><em>name </em></strong>property of the Alien class.</p><p>12. object construct in stead of Static keyword</p><p>There is no static type in kotlin, in stead you create a utility block of code prefixed with <strong>object </strong>keyword and you are allowed to create a singleton object within that object. For a start it’s a bit work, but as long as kotlin don’t have much restrictions on where you write your classes in what files, it brings modularity and a possible flexibility as you can hoard your singleton creation in one place.</p><pre><strong>class Dart(val name:String)<br>object Util{    <br>    fun getDart():Dart{<br>        return Dart(&quot;olla&quot;)<br>    }<br>}</strong></pre><p>I bet i will see you in the next part… make sure you clap as always, 👏 👏 and share your favorite and worst feature you experienced in kotlin.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=17085477d8ad" width="1" height="1" alt=""><hr><p><a href="https://medium.com/compute-and-beyond/kotlin-for-java-developers-part-2-17085477d8ad">Kotlin for Java Developers part 2</a> was originally published in <a href="https://medium.com/compute-and-beyond">compute and beyond</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kotlin for Java Developers — part 1]]></title>
            <link>https://medium.com/compute-and-beyond/kotlin-for-java-developers-part-1-dff945127885?source=rss-a8d60de601bc------2</link>
            <guid isPermaLink="false">https://medium.com/p/dff945127885</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Aelafseged]]></dc:creator>
            <pubDate>Fri, 31 Jan 2020 12:20:47 GMT</pubDate>
            <atom:updated>2020-03-03T12:00:23.576Z</atom:updated>
            <content:encoded><![CDATA[<h3>Kotlin for Java Developers — part 1</h3><p>Hello fellow developers, it has been few years that the glittering stage of java is being shared by Kotlin.. no doubt about. I think I am one of the late comers to the kotlin world, who for a reason so funny didn’t embarked on it. Hey Better be late than never. So let’s look the most iconic feature of kotlin in respect to Java.</p><blockquote>1. Good bye Primitive types</blockquote><p>Yea remember all the gang of 8 primitive types we play with (or the joke was on us😠)in java, with their cavemen rituals of using Utility methods, and other stone age techniques to do simple task... they are all upgraded into objects in kotlin. Those primitive types were the reason java was called <strong>“An almost”</strong> object oriented language. So wrapping a primitive type with object to upgrade it to object level is a thing of a past🖐. We can do dozens of operation on those type by calling their methods.</p><p>we have plenty of methods as you can see in the image below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*M1J7ROaSiImZ7oJr5XnpSw.png" /><figcaption>all variables have object types</figcaption></figure><blockquote>2. When declaring a variable flip data type to the other side</blockquote><pre><strong>int javaVar = 12; // data type comes first</strong></pre><pre><strong>var age: Int = 30 // variable then datatype(optionally😉) and no semicolon😍</strong></pre><p>In java we start with the data type then the variable name; and we can or not initialize the variable. But in kotlin much emphasis is made on the actual variable not it’s type, additionally it has smart data type inference feature, java considers such attempt as <strong><em>“prohibidato”</em></strong>- I know it’s Spanish. It’s exotic but gets you compile time error.</p><p>will explain about the <strong><em>var </em></strong>variable few lines later</p><blockquote>3. finally … <strong>final </strong>is gone!</blockquote><p>In java to make variable immutable we uses <strong>final </strong>keyword. But in kotlin we start declaring either with var (for mutable ones) and val (for immutable variables). It’s always recommended to start with val. No fear of having unintended value changes somewhere in your project just declare your variable with val.</p><pre><strong>var age: Int = 30<br>val name: String = &quot;Africa&quot;</strong></pre><p>One must consider the variables holding arraylist can add or remove values within the arraylist object, while still being declared as an immutable variable.</p><blockquote>4. working with Numerals</blockquote><p>Yea the name is unusual for java developers; but here they refer to long, double, float and integers, all types are objects therefore no more having those helper util static methods to handle operations, as they are thought on history class of “kotlin’s parents”. We can directly refer to methods of those numeric variables. as depicted on point number 1☝️</p><p>Also widening conversion is not implicit as it is in java. you need to do this 👇Everything is object, thus you need to respect them as one.</p><pre><strong>val salary: Double = 2000.20<br>val newSalary: Float = salary.toFloat() // need to call out //                                        method<br>//but in java implicit casting was available</strong></pre><blockquote>5. Characters</blockquote><p>Like it’s distant cousins (numerals ) character is also an object. Manipulating character is just one . operator away. We have almost enough of built in methods to do the basic tasks and more.</p><pre><strong>val alpha: Char = &#39;k&#39;<br>alpha. // try out the methods</strong></pre><blockquote>6. Array</blockquote><p>We java developers have to deal with unusual “choice pause” of coding convention of<strong> int[] a</strong> or<strong> int a[]</strong> and the unwieldy instantiation issues we have to deal with.</p><p>But in kotlin we have few decent built in methods to instantiate an array, empty or with values. If you are comfortable with generic type( if you are not, you need to!), you will love what kotlin does with array, it’s an art.</p><pre><strong>val arr  = <em>arrayOfNulls</em>&lt;String&gt;(12) // type inference<br>arr[0] = &quot;Aelaf&quot; // adding appropriate data type value</strong></pre><blockquote>7. String</blockquote><p>In java this is the only data type that has escaped the primitive infection and lived to tell the tale. But in addition to what java did, kotlin make few adjustments like concatenating with numerials with “+” is not allowed😱 . yea it’s considered too primitive. Because all things are objects, and you need object methods to turn a numeric value to a string. You have triple quote delimiter to ease the indentation and new line issue on long string .</p><pre><strong>val converse: String =&quot;&quot;&quot;<br>   Mr X: This is the end of wakanda<br>   Ms Y: It will be a glorious end <br>&quot;&quot;&quot;<br><em>println</em>(converse)</strong></pre><p>My personal favorite is that String has iterators for each characters, yea remember the days you had to convert a string into array and iterate over it 😠although we have stream on java 8 , kotlin has made it much much simpler</p><pre><strong>converse.<em>forEach </em>{ x-&gt; <em>println</em>(x)} // prints every character in the //                                   string object</strong></pre><p>Similar to other languages like typescript kotlin has string composition where you can add a variable into a string with out the madness of adding + operator left right🤪, to make things more insanely awesome kotlin added template expression and calling a function within is possible. Amazing ha?!</p><pre><strong><em>print</em>(&quot;hey $converse and also boolean result ${1&gt;2}&quot;)</strong></pre><blockquote>8. For loop</blockquote><p>All java developers have his/her own experiences with the decades old for loop construct. Agreed; java has come a long way in improving it like <strong>foreach </strong>and <strong>java 8 constructs</strong>. But kotlin has pushed it to near perfection😍. By completely ditching the <strong>for(int i = 0; i&lt;10; i++) </strong>to</p><pre><strong>for (temp in converse){   //string can be iterated over<br>    <em>println</em>()<br>}</strong></pre><p>It also has a method called <strong>rangeTo()</strong> to handle ranges within which loop executes</p><blockquote>9. If else construct</blockquote><p>It works similar to java’s if construct, but only “similar!”. In kotlin we can assign the result of if else construct to a variable. Insane ha! Meaning we are ditching the ternary operator to it’s funeral ☠.</p><pre><strong>val x = if(1&gt;2){<br>    &quot;somthe&quot;<br>}<br>else{<br>    &quot;try more&quot;<br>}</strong></pre><blockquote>10. Exception Handling</blockquote><p>Remember java… we all were forced to add either throws on the method or putting our code inside a try catch basket for methods that has checked exceptions or you will have compile time error. That wasJDK fearing your code can throw up checked exception all over you studio. Kotlin got some Good news… all exceptions in kotlin are unchecked. writing <strong>try catch</strong> is an option. It’s like listening emergency instruction on your flights becomes optional. Bit of risks with plenty of amazing view over an airplane window</p><blockquote>11. Null pointer Exception</blockquote><p>I believe the biggest selling point of Kotlin was making null pointer exception a thing of a past. we all java developers have dreaded memories of null pointer exceptions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GQ21Tf-0BY4Kptx5ciU4mQ.jpeg" /><figcaption>What a battle it was</figcaption></figure><p>It starts by not allowing you to have your variable refer to null. You just can’t but if you really beg for it… upon declaring a variable with it’s data type you add “?” saying this variable can refer to a null value. And you take all the risk of handling a null pointing variable. With bit sophisticated way of handling it too.</p><pre><strong>var arr: Array&lt;Int&gt;? // then it&#39;s your job to handle null issues<br>// kotlin can have old way and new way of checking of null value<br>if(arr!=null){<br>    arr.<em>forEach </em>{i-&gt; <em>print</em>(i) }<br>}<br><br>arr?.<em>forEach </em>{ i-&gt;<em>print</em>(i) } // sick! right?!😉</strong></pre><blockquote>12. When construct</blockquote><p>some calls it a switch statement on a steroid, and having too much caffeine.(in a good way)</p><pre><strong>val age : Int  = 90<br><br>var ageDescription = when (age) {<br>    18 -&gt; &quot;teen&quot;<br>    21,22,23,24-&gt; &quot;early twenties&quot;<br>    90 -&gt; &quot;You have lived&quot;<br>    4 -&gt; &quot;Wednesday&quot;<br>    else -&gt; &quot;some number&quot;<br>}</strong></pre><p>you don’t need <strong>break </strong>statements, which has been the cause of many ills in java. instead of default we have else. and like the if construct it can assigned to a variable or if you opt not simple method calls or print statements can be used. Also the comparison is not limited to integer types only.</p><p>These are some of the basics of kotlin… stay tuned for the <a href="https://medium.com/compute-and-beyond/kotlin-for-java-developers-part-2-17085477d8ad?source=collection_home---4------1-----------------------">second part</a>… very soon.</p><p>make sure you declare claps👏👏👏 so many times and write your comments on who is winning the minds and hearts of developers? Thank you for your time</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dff945127885" width="1" height="1" alt=""><hr><p><a href="https://medium.com/compute-and-beyond/kotlin-for-java-developers-part-1-dff945127885">Kotlin for Java Developers — part 1</a> was originally published in <a href="https://medium.com/compute-and-beyond">compute and beyond</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Late winter tips for Software Developers]]></title>
            <link>https://medium.com/@aelafted/late-winter-tips-for-software-developers-e2092363a9b8?source=rss-a8d60de601bc------2</link>
            <guid isPermaLink="false">https://medium.com/p/e2092363a9b8</guid>
            <category><![CDATA[advice]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Aelafseged]]></dc:creator>
            <pubDate>Thu, 09 Jan 2020 13:34:22 GMT</pubDate>
            <atom:updated>2020-01-09T13:34:22.354Z</atom:updated>
            <content:encoded><![CDATA[<p>This new decade has plenty of treasures in the realm of development — software. The list is getting ever larger, in short every major tech companies are releasing their “best ever” programming languages, frameworks, plugins, hardware devices, operating systems, A.I and ML research, cloud services, data sciences, certifications… the list goes on.</p><p>Honestly no one can predict how the evolution will play out in the next few years let alone plan out for the next decade. I think this is the very reason the famed Nostradamus himself had to dodge the topic of software dependent world. The competition is intense; the rate of producing output is incredibly amazing.</p><p>But what does this mean to us the developers who have different levels of skill sets working in different technology stack? If we just consume ourselves in studying ever new languages, frameworks, protocols… we can eventually burn out. But this is very important; we can manage to make a decent work and life balance by following the following tips or similar ones.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6AtRGmPFASvdGS9XxYpO6w.jpeg" /><figcaption>work hard, work together</figcaption></figure><h4>0. Why do you even want to be a developer?</h4><p>You need to have genuine and long lasting reason; in short the reason/s must be beyond money, fame, followers and power. In my case I believe the reason is because I enjoy learning and implementing it. The pursuit of knowledge and its implementation to make the world a better place — could be the most overused word for the past decades but as long as it’s genuine it will be your life’s calling.</p><h4>1. Get in control of your social media</h4><p>They are the most addictive time consuming piece of technology… as much as they are important for myriad of reasons they can equally consume your time, stick with very few… leave some old social media groups, un-follow some frivolous pages or posts, unfriend or block people who posts things that drain your energy. I guarantee you that there are at least more than 5 mail subscriptions you never opened email of… so get rid of them.</p><h4>2. Take time to read books even better are poems, and reduce TV time</h4><p>There are <a href="https://experteditor.com.au/blog/brain-books-benefits-reading/">some studies that a show reading improves our way of life</a>. As developers our daily lives is filled with technical problems and advantages of books should not be seen lightly. And poems have a side bonus to improve your romantic relationships, I hope by now life is not just 0s and 1s but whole mix of rational and irrational numbers. And Poems are like mathematical tools that describe nature non-numerically but “verbally”.</p><p>The volume of tv shows, music and movies are …well “got no words”. I have almost completely stopped watching series movies except for blockbusters like Avengers and such. You can save hundreds of hours of your valuable time.</p><h4>3. Learn in different ways- honestly you don’t have a choice</h4><p>Few decades back let alone centuries. Understanding how a specific machines or tools work could guarantee you a life time career, like a train conductor or typewriter. All you need was few years of studies. But the changes are now way too complicated. You can literally be required to learn a new language and build something of it. The old ways of reading books back to back by taking a note, then trying to apply the new skill are no more effective. Get yourself a decent internet with a controlled urge to respond to your social media notifications of course. My favorite is look through a crash course of the technology which can be an hour or around, get a top rated video tutorial from reputed sites, recommended books and start learning by working on personal projects.</p><h4>4. Does your project have real value?</h4><p>You have struggled through colleges/ or just mastering the discipline then got yourself a decent set of skills then you are jumping into a project, you just dived and submitted it in months or something. Does the product add real value to the society? Is your inner voice shouting out? or something is wrong with the way it’s been consumed by users. We developers have societal responsibilities that we must honor and respect. Yes money can be made out of it. Users data, preferences and addresses can be manipulated in a myriad of ways. In short don’t code what your mom wouldn’t approve.</p><h4>5. Learn the basics of computer science</h4><p>The basics of computer science, which are mainly Data structure and Algorithms has improved but they haven’t changed much since the Second World War. We are still using math of Sumerians. As long as quantum computer don’t hit the market the math and algorithm of cold war era will set you in excellent ground. I do blog in those topics, because those are the topics I suffered a lot due to my semi- substandard education ;-) and lack of mentor in my town. Continually improve your craft with those tools.</p><h4>6. Programming Language is no religion</h4><p>It’s not like your parents baptized you butt ass nude with one and only one language… the landscape is continually changing… as long as you have a firm ground on the basics you can navigate through new territories, learn new languages and implement product using them. Yes the industry might demand 21 years old programmer who have developed using java since 1995 at one time and the next morning they might require a Kotlin developer who developed in it since 1984.</p><h4>7. Software development is not just about programming language</h4><p>It is a collection of skill sets, some skills can be inevitably be obsolete and some can out stay your life span [Yea I’m looking at you prime numbers]. Programing language is just one part of it. You have</p><p>- Design Pattern</p><p>- Software development management methodologies like agile</p><p>- Communication protocols — SOAP, RestApi, GraphQL</p><p>- Data storage, database, file system, cloud</p><p>- Data science, machine learning</p><p>- Communication and presentation skills</p><p>- Techprenurship</p><p>- And many others</p><h4>8. Learn about Management and Finance</h4><p>Only very few privileged kids might have the early advantages of financial know how but you can still make a good progress as the internet has democratized information (for most part ;-))</p><p>Working on active and passive incomes… take courses on business related topics. Look beyond your development studio…</p><h4>9. Do not lose your childhood’s awe and wonder</h4><p>Such curiosity can be part of a source of purpose to your software development and personal life, explore other topics at your spare time and even if it fails try to correlate it with development. Don’t let the information bubble controls your thoughts and see different perspectives. Listens to others and collaborate.</p><p>Let me know if you can add more points.</p><p>Cheers and Happy starting a new decade.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e2092363a9b8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Observable Design Pattern Using YouTube subscription as an example]]></title>
            <link>https://medium.com/compute-and-beyond/understanding-observable-design-pattern-using-youtube-subscription-as-an-example-10c99db2ba31?source=rss-a8d60de601bc------2</link>
            <guid isPermaLink="false">https://medium.com/p/10c99db2ba31</guid>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Aelafseged]]></dc:creator>
            <pubDate>Sat, 21 Sep 2019 06:39:55 GMT</pubDate>
            <atom:updated>2019-09-21T06:43:15.701Z</atom:updated>
            <content:encoded><![CDATA[<p>It’s one of the most essential design patterns, also it is a prequel to RxJava. <strong><em>More than one object is notified when data/state of an object is modified.</em></strong> The word Observable will not leave us any time sooner, so let’s get started.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*KNfEab78dm9ZKxdH" /><figcaption>One Observable with many Observers</figcaption></figure><p>In a nutshell in observable design pattern there are two distinct objects one is a <strong>Observable</strong> and the second one is at least one O<strong>bserver</strong> object. There are plenty of scenarios that we can come up with. First the relationship between Observable and observer is 1 to many or<em> 1 — — — *</em> relationship. For an instance a YouTube subscription scenario can be played out… Whenever a user clicks the subscription button she/he is been registered as an observer. The YouTube channel is the subject/Observable and whenever a new video is uploaded, the video is send to all subscribed users (who happen to be the observers).</p><p>Let’s Create the two classes then</p><p>The youtubeChannel class has the following fields</p><pre><strong>List&lt;Subscriber&gt; subscriberList; // holds list of subscribed users<br>List&lt;String&gt; videoTitles; // list of videos subscribers wait for</strong></pre><p>When YouTube object is created this two fields are being initialized, we can optionally initialize the videoTitles field with data from database or network resource. there are three essential methods. One <strong>attach subscriber</strong> to this youtube channel by hoarding subscriber objects references into list of subscribers,</p><pre><strong>public void attachSubscribers(Subscriber subscriber){<br>    subscriberList.add(subscriber);<br>}</strong></pre><p>The other update the data of <strong>videoTitles field</strong>, this method calls the <strong>broadcasting method</strong> that will broadcast to all previously attached subscribers.</p><pre><strong>public void addVideo(String title){<br>    videoTitles.add(title); //updating the videoTitle field<br> </strong>   //broadcast to all subscribers<strong><br>    broadcastToSubscribers();<br>}</strong></pre><p>The broadcasting method just loop through the list of individual subscribers and calls the intended method/s of the subscribers.</p><pre><strong>public void broadcastToSubscribers(){<br>    for (Subscriber sub :<br>            subscriberList) {<br>        sub.getUpdate();<br>    }<br>}</strong></pre><p>Now we are almost done with our YouTube class let’s work on our Observer/Subscriber class</p><p>We have two options of creating the subscriber class.</p><p><em>To Abstract or to Interface is the question?!?! ;-)</em></p><p>1.Create an <em>abstract Observer class</em> with field of YouTubeChannel and an abstract method of getUpdate() method, then concrete classes will extend it. The YouTubeChannel class will use type of this abstract class to interact with the subclasses As seen below.</p><pre><strong>public abstract class Observer {<br>    public YouTubeChannel youTubeChannel;<br>    public abstract void getUpdate();<br>}</strong></pre><p>2. The other one is an<em> interface</em> with one method which is implemented by all the subscribing concrete classes</p><pre><strong>public interface Subscriber {<br>    void getUpdate();<br>}</strong></pre><p>We will use the second method. I do harbor a bit of affinity towards interfaces rather than abstract class. But I hope you will try abstract way too.</p><p>On the constructor of one of the subscribing class we are sending Youtube object as parameter, this insures there is a communication between the two classes and eventually the created objects will reference each other. Then We are attaching the subscriber to the Youtube channel.</p><pre><strong>public ConcreteSubscriber(YouTubeChannel youTubeChannel) {<br>    this.youTubeChannel = youTubeChannel;</strong><br>    //whenever new subscriber object is being created<br>    // it&#39;s reference is collected by the youtube channel&#39;s <br>    //subscriberList field<br> <strong>   this.youTubeChannel.attachSubscribers(this);<br>}</strong></pre><p>We are calling the youtube’s method attach by sending the subscriber&#39;s object… on Youtube the subscriber is being collected</p><pre><strong>public void attachSubscribers(Subscriber subscriber){<br>    subscriberList.add(subscriber);<br></strong>// subscribers are being added to arraylist<strong><br>}</strong></pre><p>After creating one YoutubeChannel object, we pass the youtube object to all Subscribers constructors, then whenever we are adding new video to the youtube channel all the subscribers get notified and they will act on the intended action.</p><pre><strong>YouTubeChannel youTubeChannel = new YouTubeChannel();<br><br>   new GenericSubscriber(youTubeChannel);<br><br>   new PremiumSubscriber(youTubeChannel);<br><br>   youTubeChannel.addVideo(&quot;End Game&quot;);</strong></pre><pre><strong>   System.out.println(“ new video added…”)<br><br>   youTubeChannel.addVideo(&quot;White Phoneix&quot;);</strong></pre><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ff0139b50581cbf39317bc73d6aa651d/href">https://medium.com/media/ff0139b50581cbf39317bc73d6aa651d/href</a></iframe><p>That’s it… this is the basic of Observer Pattern… try experimenting on different ways, which are adding new level of abstraction to the Observable class or making a chain of Observes , or one subscriber attached to two different Observable, or the other way round the possibilities are many and you will be solving problems in different ways. I hope you enjoyed the few minutes journey.</p><p>P.s I heard clapping keeps kitten safe and more developers will find this article. If not for developers do it for cats;-)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=10c99db2ba31" width="1" height="1" alt=""><hr><p><a href="https://medium.com/compute-and-beyond/understanding-observable-design-pattern-using-youtube-subscription-as-an-example-10c99db2ba31">Understanding Observable Design Pattern Using YouTube subscription as an example</a> was originally published in <a href="https://medium.com/compute-and-beyond">compute and beyond</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Working with HTTP INTERCEPTORS angular]]></title>
            <link>https://medium.com/compute-and-beyond/working-with-http-interceptors-angular-31067ffaeb2f?source=rss-a8d60de601bc------2</link>
            <guid isPermaLink="false">https://medium.com/p/31067ffaeb2f</guid>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[angular2]]></category>
            <dc:creator><![CDATA[Aelafseged]]></dc:creator>
            <pubDate>Wed, 17 Apr 2019 05:16:47 GMT</pubDate>
            <atom:updated>2019-04-17T05:16:47.028Z</atom:updated>
            <content:encoded><![CDATA[<p>Greetings I am recently working on a client side using android and angular… i’m very much new to angular and I love it🤓🎆… it has flexibility and many other features google promised of which I agree. Like any other frameworks it has it’s own learning sharp curves but it’s worth it….</p><p>As I was expecting the backend team for authentication features to be added on the server side I came across with one blog on Http Interceptors and I am sharing that experience… i’m sure this is one of the many of usages of http intereceptors.</p><p>and best of all is updating your request with all the authentication data before farewelling it.</p><h4>You can use<em> multipe interceptors</em> similar to Linux pipe on commands; chain of interceptors.</h4><p>First let’s see the basics</p><p>client send request ➡ then server upon receiving the request process it and ⬅send response. Simple ha!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/623/1*wX8duPb_STDfrdqHIH_oew.png" /><figcaption>http intereceptor</figcaption></figure><p>The http intereceptors jump right in the middle. Yea! Understanding this feature is a must to develop market acceptable application.</p><p>How does the Angular send http request then</p><pre><strong>//import<br>import { HttpClient } from &#39;@angular/common/http&#39;;</strong></pre><p>then on the class inject the httpClient object within the constructor… meaning the httpClient object is available to make network related calls</p><pre><strong>constructor(private http: HttpClient) { }</strong></pre><p>this is cooler way handling injection (constructor based independency injection),make sure you at least skim the basic methods of the http object.</p><p>For instance</p><pre><strong>this.http.get&lt;any&gt;(&#39;localhost:4040/users/&#39;);</strong></pre><p>the method get makes network call,…. this is where the interceptor does what it names says…</p><p>Let’s intercept the request then</p><p>* Interceptors are configured at module level… if you have multiple modules you can set interceptors for those different modules.</p><p>In our case we opened the app.module.ts file and within the Providers array we are adding the interceptors</p><pre><strong>import { FakeBackEnd } from &#39;./helpers/fake-back-end&#39;;<br>//...<br>        @NgModule({<br>        declarations: [<br>//ALL THE COMPONENTS YOU HAVE CREATED IN YOUR MODULE<br>        ],<br>        imports: [<br>//ALL MODULES THAT ARE BEING USED BY THIS MODULE<br>        ],<br>        providers: [<br>//OUR INTERCEPTOR<br>// WHAT IT PROVIDES<br>// THE CLASS THAT PROVIDES THE SERVICE<br>        {<br>        provide: HTTP_INTERCEPTORS,<br>        useClass: FakeBackEnd,<br>        multi: true<br>        },<br>//OTHER INJECTABLE SERVICES<br>        ProductService<br>        ],<br>//THE INITIAL COMPONENT THAT WILL BE RENDERED TO BE BOOTSTRAPED<br>        bootstrap: [AppComponent]<br>        })</strong></pre><p>The comment sections does tell the details of it.</p><p>Opening our <strong><em>fake-back-end.ts</em></strong> does</p><pre><strong>@Injectable()<br>export class FakeBackEnd implements HttpInterceptor {<br>intercept(req: HttpRequest&lt;any&gt;, next: HttpHandler): Observable&lt;HttpEvent&lt;any&gt;&gt; {<br>}</strong></pre><p>the class is an ordinary <strong>injectable</strong> service that implements the HttpInterceptor interface,… the <em>method intercept</em> thus must be implemented. It has request and handler objects as parameters.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f29abfff6a0deb44bc6b963ba6116a9c/href">https://medium.com/media/f29abfff6a0deb44bc6b963ba6116a9c/href</a></iframe><p>the request object basically the url, body and headers information, it’s immutable so you must clone it if you want to change this object. Java’s string object is immutable meaning editing object creates a brand new string object but is being referenced by the old variable that was referencing the old string object.</p><p>The handler object tells what we are doing with the request object.</p><p>Here we interecept the request, can make a clone of it then edit it’s header or other objects and send it down, or block the request based on many kinds of criteria.</p><p>For instance within the interecept method</p><pre><strong>// making any kind of adjustments<br>        newReq = request.clone();<br>        request.setheaders//<br>        if (request.method === &#39;POST&#39;) {<br>//check if the request is a post method<br><br>        return throwError({ status: 401, error: { message: &#39;Unauthorised&#39; } });<br><br>        }<br>        return next.handle(request);</strong></pre><p><em>post method is not authorized</em> else the request is <em>cascaded down the network calls</em>, that’s how you manage the work. In the next tutorial we will be discussing rxjs based response handling… as the <em>interecept</em> action is dual direction. Will catch you very soon. enjoy coding.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=31067ffaeb2f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/compute-and-beyond/working-with-http-interceptors-angular-31067ffaeb2f">Working with HTTP INTERCEPTORS angular</a> was originally published in <a href="https://medium.com/compute-and-beyond">compute and beyond</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Generics Like an Oracle does(Part II)]]></title>
            <link>https://medium.com/compute-and-beyond/understanding-generics-like-an-oracle-does-part-ii-2dbee57f61a?source=rss-a8d60de601bc------2</link>
            <guid isPermaLink="false">https://medium.com/p/2dbee57f61a</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[generics]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Aelafseged]]></dc:creator>
            <pubDate>Sat, 26 Jan 2019 19:15:37 GMT</pubDate>
            <atom:updated>2019-01-26T19:15:37.540Z</atom:updated>
            <content:encoded><![CDATA[<p>In the<a href="https://medium.com/compute-and-beyond/understanding-generics-like-a-cup-of-tea-part-1-a38b02731b82"> previous article-part 1 </a>we covered the basics of generics, now we will discuss a more advanced parts of it.</p><h4>Type Inference:</h4><p>It’s when compiler tries to figure out the data type in place of the generic type.</p><p>It’s<em> “Dude, don’t bother!!!” algorithm of java</em> compiler that figure out the generic type by the input data in methods and generic class field instantiations in classes.</p><p>In Generic class instantiation</p><pre><strong>ArrayList&lt;String&gt; myList = new ArrayList&lt;String&gt;();<br></strong>//is changed into <strong><br>ArrayList&lt;String&gt; myList = new ArrayList&lt;&gt;();</strong><br>//diamond operator or empty type parameters on the constructor //side is added after java7</pre><p>Unlike the constructor with a diamond operator above, in methods you don&#39;t need to explicitly have to call out for generic,</p><p>if we have the following method</p><pre><strong>static &lt;T,S&gt; cageFight(T t,S s){}</strong></pre><p>then calling it using this</p><pre><strong>ClassName.&lt;String,String&gt;cageFight(“x-men”, “y-men”);</strong><br>// the type parameter is redundant</pre><p>also known as <em>type wittness </em>is not needed, instead do the following</p><pre><strong>ClassName.cageFight(“x-men”, “y-men”);</strong><br> //compiler can tell what data type of arguments are being set</pre><p>Thus no need to state them.</p><h4>WildCard:</h4><p>This is where an alphabet is being substituted for a question mark&lt;?&gt;. It can be considered as top level Object class status for generic classes</p><pre><strong>Planet&lt;?&gt; unknowPlanet</strong></pre><blockquote>can be used for parameters, fields or return type.</blockquote><blockquote>BUT it cannot be used in generic methods as type argument and generic class instantiation.</blockquote><h4>Upper Bounded WildCard</h4><p>Similar to our previous article&#39;s upper bound, meaning any class that is either the <strong>BoundingClassType</strong> or a<strong> sub child the bounding classtype</strong>, but in a format of this.</p><pre><strong>&lt;? extends BoundingClassType&gt;</strong></pre><h4>Lower Bounded WildCard</h4><pre><strong>&lt;? super BoundingClassType&gt;</strong></pre><p>Any class that is either the <strong>boundingClassType</strong> itself or <strong>super class of the bounding classType</strong>. It looks up the relationship path.</p><h4>Sub typing in generics:</h4><p>In our previous article we mentioned that just because there is an <strong>is-a relationship</strong> for variables between a generic classes doesn’t make them fit to be a generic sub-typing. We have concrete relationship on classes as seen below.But we can have such features using two ways.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*qqh_UBfZlaAiAkhgnhhdog.png" /><figcaption>Figure 1. Non Generic class relationships</figcaption></figure><blockquote><strong>1. using a consistence relationship on generic level</strong></blockquote><p>We have a generic Human Interface that extends all the Animals. Then a concrete Male and Female generic classes that implements the generic Human interface</p><pre><strong>public   interface Animal&lt;T&gt;{}<br>public  interface Human&lt;T&gt; extends Animal&lt;T&gt;{}<br>public static class Female&lt;T&gt; implements Human&lt;T&gt;{}<br>public static class Male&lt;T&gt; implements Human&lt;T&gt;{}</strong></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*Ho4Z9AC3W0G3iOZuaLBPfA.png" /><figcaption>Figure 2. Generic classes relationships</figcaption></figure><p>this way we created the previously unachieved <strong><em>“is-A” relationship</em></strong></p><blockquote><strong>2 using wildcard’s Upper and Lower Bound</strong></blockquote><p>We have Human, Female and Girl classes;</p><pre><strong>class Human{/**/}<br>class Female extends Human{/**/}<br>class Girl  extends Female{/**/}</strong></pre><p><strong>Planet&lt;?&gt; </strong>is the super type, because the planet class can have any kind of data. In real world scenario it’s a Planet that can house anything. Let’s create the relationship using Upperbound as seen on the right circled relationship on Figure 3</p><pre><strong>Planet&lt;? extends Human&gt;</strong></pre><p>Means a planet that can house anything that is a either Human or child of Human.<em> Female and Girl classes are valid</em>.</p><pre><strong>Planet&lt;? extends Female&gt;</strong></pre><p>Means a planet that can house anything that is Female or sub-child of Female. <em>Girl class is valid.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/650/1*EGHlqhERcfiHZfx9h8Ur9w.png" /><figcaption>Figure 3. Generic Wild Cards Creating relationships using bound on non generic classes</figcaption></figure><p>Now let’s use the lower bound wild card, as in the left circled relationship of Figure 3</p><pre><strong>Planet&lt;? super Girl&gt;</strong></pre><p>a planet that can house Girl or super class of Girl; any class above Girl class. <em>Female and Human classes are the subtype</em>.</p><pre><strong>Planet&lt;? super Female&gt;</strong></pre><p>a planet that can house Female or super class of Female; <em>Human class is a subtype</em></p><p>Hope the two parts series was informative, fairly palatable… thank you for your time, do the three magic stunts[clap, comment and share] so many can learn and build better softwares.</p><p>Follow me for more articles.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2dbee57f61a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/compute-and-beyond/understanding-generics-like-an-oracle-does-part-ii-2dbee57f61a">Understanding Generics Like an Oracle does(Part II)</a> was originally published in <a href="https://medium.com/compute-and-beyond">compute and beyond</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>