<?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[compute and beyond - Medium]]></title>
        <description><![CDATA[A sancturary for destined software Jedi, mastering the Force to create exciting software products. - Medium]]></description>
        <link>https://medium.com/compute-and-beyond?source=rss----c051ff026de1---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>compute and beyond - Medium</title>
            <link>https://medium.com/compute-and-beyond?source=rss----c051ff026de1---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 22:23:59 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/compute-and-beyond" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <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----c051ff026de1---4</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:37:54 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[Kotlin for Java Developers part 3]]></title>
            <link>https://medium.com/compute-and-beyond/kotlin-for-java-developers-part-3-25c168695e90?source=rss----c051ff026de1---4</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----c051ff026de1---4</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----c051ff026de1---4</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:48 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[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----c051ff026de1---4</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----c051ff026de1---4</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----c051ff026de1---4</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>
        <item>
            <title><![CDATA[Understanding Generics Like a cup of Tea Part 1]]></title>
            <link>https://medium.com/compute-and-beyond/understanding-generics-like-a-cup-of-tea-part-1-a38b02731b82?source=rss----c051ff026de1---4</link>
            <guid isPermaLink="false">https://medium.com/p/a38b02731b82</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[generics]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Aelafseged]]></dc:creator>
            <pubDate>Fri, 18 Jan 2019 09:58:14 GMT</pubDate>
            <atom:updated>2019-01-26T19:40:03.340Z</atom:updated>
            <content:encoded><![CDATA[<h3>Understanding Generics Like a Pro Part 1</h3><p>N.B you must a have clear knowledge on both primitive and class data types.🧐At the end of the two parts series, you will be able to read and create Generics codes like the one below.</p><p>Or you can just jump into <a href="https://medium.com/compute-and-beyond/understanding-generics-like-an-oracle-does-part-ii-2dbee57f61a">Part 2</a> for the End Game😉😉😉</p><pre><strong>class Planet&lt;T,S,U&gt;{<br>}<br>//instantiating a generic class<br>Planet&lt;Land,Water&lt;Ocean,Fresh&gt;,Air&lt;Wind,Cloud&gt;&gt; = new Planet&lt;&gt;();</strong></pre><p>Previously I took to the web an article elaborating a portion of the <a href="https://medium.com/compute-and-beyond/working-with-use-case-ln-app-development-ecabd069eacc">Official Android Sample Code on Use Case</a>… it uses rather too much Generics🤓 this is for those who are not fully comfortable with Generics. The very mystery starts with it’s definition.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/1*Xnv0IY8oS2KPtp3aZ8bafg.png" /></figure><h4><strong><em>IT ABSTRACTS TYPES!!! or IT TEMPLATES TYPES!!!</em></strong></h4><p>as much as it’s called <strong>Generics class</strong> or <strong>Generic method</strong> it’s all about <strong><em>fields</em></strong> and <strong><em>argument</em></strong> data types!!! The rest is redundant as a sun rise.</p><p>But what sort of problem gave birth to Generics? you might ask.</p><p>Generics as mentioned above is a template for a type of data!!! On our early lessons of algorithms we used String data type… but real world problems are not only strings. Meaning we have to re-configure our algorithms to allow usage of non-String data.</p><pre><strong>public class MyNonGenericClass {<br>    Object data1;<br>    Object data2;<br>    public Object getData1() {<br>        return data1;<br>    }<br>    public Object getData2() {<br>        return data2;<br>    }<br>      public static void main(String[] args) {<br>        MyNonGenericClass nonGenericClass = new MyNonGenericClass(&quot;dart&quot;,new Integer(12));<br>        Integer result2 = (Integer)nonGenericClass.data2;<br>        String result1 = (String)nonGenericClass.data1;<br>               //no compile time error but runtime error</strong>🧐<strong><br>	Integer resultErr = (Integer)nonGenericClass.data1;<br>	<br>    }<br>}</strong></pre><p>One way was making the class to accept Object type, as every object is a sub-class of an Object class, then after the computation, the result is casted to it’s intended type.</p><p><em>This can bring a compile-time hidden and run-time jumping</em>🐅<em> error</em>.</p><p>The class that is accepting our input have no tools to check for type compatibility (it sees only Object and everything is a type Object)… we can insert a String object then try to cast the output to Integer and still the compiler can not complain!!! which will lead to a horrific run-time error.</p><h4><strong><em>Generics to the rescue:</em></strong></h4><p>Has template on class and assures type of data on object creation.</p><p>It uses delimited parameters types that will be used for the data types of the fields or argument which are waiting to be anointed💦 … when you create an object of that class you need to define the data type then within those angle brackets.</p><pre><strong>Class Air&lt;T&gt;{<br>     T unitMass;<br>}</strong></pre><p>If you have more than one variables to work as generics then add other parameterizd types separated by commas , known as<strong> type variables.</strong></p><pre><strong>class Air&lt;T,S,U,V&gt;{/* rest of the code*/}</strong></pre><p>To create a concrete Air object, we need to assign data type that is going to be used by the unitMass variable, which we picked String type to substitute the generic type, or you can select any other concrete type (no primitive types allowed!!!)</p><pre><strong>// we have created Air Object with an intention of making<br>Air&lt;String&gt; myAir  = new Air&lt;String&gt;();</strong></pre><p>the datatype T is changed into String type.</p><p>after Java 7 the redundancy of &lt;String&gt; the right side of new keyword is deducted into a diamond operator.A technique called inference.</p><pre><strong>Air&lt;String&gt; myAir  = new Air&lt;&gt;();</strong></pre><p>there are two brief categories of generics, class Generics and Method Generics.</p><p>Previously we have a fair grip on Generic Class, let’s switch into Generic Methods.</p><p>It’s a data type template like our generic classes but the template is limited only to a method’s parameters</p><pre><strong>public &lt;E,S&gt; E getElements(E element, S set){<br>    //computation<br>    return element;<br>}</strong></pre><p>the type parameters are E and S, written in angle bracket before the return type, the return type is E .</p><h4><strong>Bounded Type Parameters</strong></h4><p>Next is restricting the type of concrete value we are substituting for the generic type, called Bounded Type Parameters but I call it Racist Type Parameters 😉because it’s kinda is.</p><p>It’s like a bar that allows only White Male or a tennis club that allows only member of xyz Bank.</p><p>You want the field type or argument type to be a sub-class to some class,abstract class or that implements a specific interface. If this is not racist then what isn’t🤣.</p><pre><strong>public &lt;T extends Cat&gt; void runOrJump(T t){<br>}</strong></pre><p>the field must be family of Cat type nothing else is allowed.</p><h4>Multiple Bounds :</h4><p>Restricts the class type to be a sub class of one class and implementer of multiple interfaces, meaning the restriction is by many data types.</p><p>On Job interview, when they don’t want to hire you, the requirements can be a Pilot, a Marine, an MIT graduate, fluent in 5 languages, took a scuba dive on Mariana trench. It’s an example of multiple bound.</p><h4>The Curious Case of Inheritance on Generics</h4><p>In object oriented programming, <strong>“is-a”</strong> relationship is a parent-child relationship; for instance String is an Object(as every class is a subclass of Object class) or Male is a Human (Male class being a sub class of Human class) their fore we can assign any object to it’s parent class reference type.</p><pre><strong>Male person = &quot;Adamu&quot;;<br>Human aHuman = person; // compiles fine</strong></pre><p>BUT for a generic class</p><pre><strong>Planet&lt;Human&gt; planetWithHuman;</strong></pre><p>and</p><pre><strong>Planet&lt;Male&gt; planetWithMale;</strong></pre><p>are <strong>NOT</strong> in any kind of “is-a” relationship</p><p>might look counter-intuitive at first but we can’t make a sub-type relationship based on generic types, meaning we can’t have an “is-a” relationship between two classes just because both classes have fields with same data type, now that in intuitive…. I would hope.</p><p>Stay tuned for part 2. clap👏🏻, comment and share.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a38b02731b82" width="1" height="1" alt=""><hr><p><a href="https://medium.com/compute-and-beyond/understanding-generics-like-a-cup-of-tea-part-1-a38b02731b82">Understanding Generics Like a cup of Tea 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[Working with Use Case ln App Development]]></title>
            <link>https://medium.com/compute-and-beyond/working-with-use-case-ln-app-development-ecabd069eacc?source=rss----c051ff026de1---4</link>
            <guid isPermaLink="false">https://medium.com/p/ecabd069eacc</guid>
            <category><![CDATA[multithreading]]></category>
            <category><![CDATA[generics]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[software-design-patterns]]></category>
            <dc:creator><![CDATA[Aelafseged]]></dc:creator>
            <pubDate>Wed, 14 Nov 2018 05:18:51 GMT</pubDate>
            <atom:updated>2018-11-14T05:18:51.110Z</atom:updated>
            <content:encoded><![CDATA[<h4>Borrowed from Android Architecture Blueprints</h4><p>While refactoring my Android client side code by sneak peaking into Google’s sample apps from the<strong> </strong><a href="https://github.com/googlesamples/android-architecture"><strong>Git Hub</strong></a>…Like many developers do, I learned extensively on using callbacks and abstract classes on usecases, at first I said why all the hassle to just create a class that only calls other classes to do the job…. But then it start to get clearer and clearer to a point I said hell with it… I have got to blog about this![with the British prime minister accent].</p><p>First the definition of <strong>use case</strong> is a list of actions or event steps.</p><p>Back to our first time projects where we write use cases and user stories to understand clearly the system requirements and it’s functionality… yea those are what we are going to discuss using Java.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/882/1*ASbJePwCB3sn_sd7Wj0_-A.png" /><figcaption>Into the the belly of Use Case</figcaption></figure><p>the final result is a <strong>GetUsers</strong> use case, which retrieves data from a resource,could be from a network or database and displaying that result to the presenter.</p><p>We are creating an abstract UseCase class that can have three parameters request, response and callbacks for different kinds of output…</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9a9a04351d7685dc1a79701b8ba053ad/href">https://medium.com/media/9a9a04351d7685dc1a79701b8ba053ad/href</a></iframe><p>Upon scanning the abstract class, the type of request and response objects can be anything from a string to any custom object, thus made Generic; that sub classes <strong>RequestValues</strong> and <strong>ResponseValue</strong> interface. Why having a request field only and why a callback on Response object instead of response field? It’s because Your request is one object, can’t be more than one request but response can appear or can not due resource unavailability or network error or just any bad day. Thus the callback that has success and error methods is there for our own sake.</p><p>Next is the run method that’s accessible to classes not extending the abstract class, as for classes that extends the abstract class there is executeUseCase(Q requestValues) method. After all we are executioning the requestValues</p><p>Let’s extend then…</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/06961f75ec938f57c2d8d1a9ef7627e2/href">https://medium.com/media/06961f75ec938f57c2d8d1a9ef7627e2/href</a></iframe><p>We now have extended our abstract class, within our execute use case we are retrieving a resource and customize the result based on our request object,Look here there is no obeject instantiation on repository object, retrieval just a reference …hence a clean code😎. In our case we are planning on ascend or no ascend scenario but you can come up with more dramatic requests on the result… then put it on to the ResponseValue class. But we can’t display the result yet! Except for the ResponseValue; the requestValues and UseCaseCallback objects are not created yet… only promise methods on their! We haven’t instantiated a class that calls GetUsers class.</p><p>Since it’s our core plan to make the class usable, we can put it in web app, android or even JavaFx based application or that new unnamed programming language around the corner. Meaning framework or library dependent code is detached from our logic… as displayed in our resource retrieval field <strong>mUsersRepository</strong> method… and we just expect result from it’s callbacks 😁.</p><p>Thus we have the <strong>UseCaseHandler</strong> that handles request and send back the result… but while using this class we have multi-threading issue to be handled…as you don’t want to upset your UI to stay hanging while you doing heavy duty network and storage job. As for android we use <strong>ThreadPoolExecutioner</strong>, in your cases it could be other procedures… thus we have an interface that needs implementation by the executioner.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f67a8e1560e235116cfc5970f7fe3bcc/href">https://medium.com/media/f67a8e1560e235116cfc5970f7fe3bcc/href</a></iframe><p>Simple interface with overdecorated Generic make ups.</p><p>And into our Handler</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/78130c10dba63d8932016eaf74d27c93/href">https://medium.com/media/78130c10dba63d8932016eaf74d27c93/href</a></iframe><p>On our execute method of <strong>UseCaseHandler</strong> we have GetUsers object and it’s request object arriving into the handler execute methods separted from it’s GetUsers object s but you can merge them earlier before they are handled to the method. Last is the callback…FINALLY IT’S BEING INSTANTIATED!!! the caller implements this interface as to wait for answers… and respond accordingly.</p><p>Just before handling over our execution to the worker thread… we replicated the callback…then start our execution… as of the result of the execution use case will give result/s to the callback</p><p>remember our two lines of code</p><p>one is</p><pre><strong>Getusers.this.mUseCaseCallback.onSuccess(responseValue</strong>);</pre><p>and the other is</p><pre><strong>Getusers.this.mUseCaseCallback.onError();</strong></pre><p>from out GetUsers concrete usecase class, yea those are the ones that’s calling/refering to the replica UiCallbackWrapper class object. And this very wrapper class is calling the Thread scheduler methods.</p><p>Having a better image of our Handler clas let’s look our Scheduler interface class</p><p>First the interface of the scheduler class.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ad3e6eb2d6b5904eba8b829f7a9d4376/href">https://medium.com/media/ad3e6eb2d6b5904eba8b829f7a9d4376/href</a></iframe><p>Back to the caller of the usecase in our case it’s <strong>THE PRESENTER</strong>…</p><pre><strong>mUseCaseHandler.execute(mGetUsers, requestValue,<br>        new UseCase.UseCaseCallback&lt;GetUsers.ResponseValue&gt;() {<br>            @Override<br>            public void onSuccess(GetUsers.ResponseValue response) {<br>                List&lt;User&gt; users = response.getUsers();<br>                processUsers(users);<br>            }<br>            @Override<br>            public void onError() {<br>               log.d(”oh no... error”);<br>            }<br>        });</strong></pre><p>the UseCaseHandler is requested… where the requested handler execute using T<strong>hreadpoolExecutioner</strong> and respond back using the <strong>UICallbackWrapper</strong>, that was instantiated within the handler,which is the same object instantiated from the presenter side. but the wrapper class in the handler does a the job of communicating with the <strong>UseCaseScheduler</strong> interface implementer, because job done outside UiThread has to be handled using Handler’s method to be displayed onto UiThread.😕 yea that’s how android rolls.</p><p>We could have directly called ThreadPoolExecutioner but our presenter would be bloated with threading codes that is nothing to do with presenting… thus given to the handler.</p><p>well that’s how you handle use cases like a pro. or like the guys in google team.</p><p>Follow me for more of such discussion. Happy handling of codes.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ecabd069eacc" width="1" height="1" alt=""><hr><p><a href="https://medium.com/compute-and-beyond/working-with-use-case-ln-app-development-ecabd069eacc">Working with Use Case ln App Development</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[Architecting a Web Service App using Restify Framework]]></title>
            <link>https://medium.com/compute-and-beyond/architecting-a-web-service-app-using-restify-framework-84e4b5a448fc?source=rss----c051ff026de1---4</link>
            <guid isPermaLink="false">https://medium.com/p/84e4b5a448fc</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[mysql]]></category>
            <category><![CDATA[restify]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[Aelafseged]]></dc:creator>
            <pubDate>Wed, 07 Nov 2018 09:20:11 GMT</pubDate>
            <atom:updated>2018-11-07T09:20:10.583Z</atom:updated>
            <content:encoded><![CDATA[<p>Greetings! If you have planned to use node.js to create web application and RestApi is your priority relative to browser based service. Express.js or Koa frameworks can do the job but Restify is dedicated to RestAPI and RestAPI only. This article is dedicated to not only start and run with Restify but to architect a scalable application. Let’s nose dive in then. It’s the author belief that you have a bit understanding on node.js with or with out any frameworks.</p><p>To Create a node project you can start by opening command line in your favorite directory and typing</p><pre><strong>npm init</strong></pre><p>Wthe rest of instructions are easy to follow and once you are done. You have created the bare bone of a node application, next is importing Restify framework and it’s buddies which are enough to get you started with restify adventure with this line of command.</p><pre><strong>npm install restify restify-plugins restify-errors --save</strong></pre><p>you can check if they are downloaded into your node_modules folder.</p><p>Next is adding folders and *.js files</p><p>we have added three major folders. They are config, models and routes folders</p><pre><strong>MyAPI---<br>        |Config----<br>             config.js<br>    	  |Models--<br>             dao.js<br>             user.js<br>        |node_modules<br>        |routes<br>             home.js<br>             route_index.js<br>             welcome.js<br>        index.js<br>        package-lock.json<br>        package.json</strong></pre><p>this is our target architecture, we could have brought MVC design pattern but we are not dealing with rendering any content as it’s left for the client side. There fore there are only Model, Router and Controller (MRC).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/924/1*z7HuxkURNPIgBvEzAhkPSA.png" /><figcaption>Web service Design</figcaption></figure><p>Let’s begin our journey with the config.js file, each line of codes are self explanatory.</p><pre><strong>module.exports = {<br>    name: &#39;MyAPI&#39;,<br>            env: <em>process</em>.env.NODE_ENV || &#39;development&#39;,<br>            <em>port</em>: <em>process</em>.env.PORT || 3000,<br>            base_url: <em>process</em>.env.BASE_URL || &#39;http://localhost:3000&#39;,<br>};</strong></pre><p>name of your app is <strong>MyAPI</strong></p><p>node&#39;s enviornment, is <strong>development</strong> (does help you out in debugging and other)</p><p>Port: number to it&#39;s <strong>default or 3000</strong></p><p>Base_url: to it&#39;s default or <a href="http://localhost:3000/"><strong>http://localhost</strong></a></p><p>setting the minimum configuration in a different file let&#39;s work on our index.js (our door way to our web app)</p><p>start with importing restify related libraries, reference to the config.js file and routing request to our routes folder files</p><pre><strong>var restify = require(&#39;restify&#39;);<br>var config = require(&#39;./config/config&#39;);<br>const restifyPlugins = require(&#39;restify-plugins&#39;);<br>var route_link = require(&#39;./routes/route_index&#39;);<br>var restify_err = require(&#39;restify-errors</strong>&#39;);</pre><p>then create our restify server...</p><pre><strong>const server = restify.createServer(<br>    {<br>        name: config.name,<br>        <em>version</em>: config.version,<br>    }<br>);</strong></pre><p>by refering name and version from config.js file (version is not manually set therefore it&#39;s implicitly set)</p><p>and setting the parameters for the restify server</p><pre><strong>server.use(restifyPlugins.jsonBodyParser({ mapParams: true }));<br>server.use(restifyPlugins.acceptParser(server.acceptable));<br>server.use(restifyPlugins.queryParser({ mapParams: true }));<br>server.use(restifyPlugins.fullResponse());</strong></pre><p>allowing JSON ,query and response displays are done using restifyPlugins library.</p><p>All are set now, server configuration,server created, and it&#39;s parameters set. Listening to requests is done by listen method</p><pre><strong>server.listen(config.port,function(){<br>    console.log(&#39;%s listening at %s&#39;, server.name, config.base_url);<br>});</strong></pre><p>all is done by running</p><p><strong><em>node index.js</em></strong></p><p><em>We have officially created restify based web server!!!</em></p><p>we could and mostly is seen in many tutorials receiving and responding to requests within the index.js file but</p><p>by sending the entire server object to other file in our case</p><pre><strong>route_link(server);</strong></pre><p>can help us with scaling and many other issues.</p><p>Into the route/route_index.js file where we are receiving the server object.</p><p>Here we can refer to the model object, database object and many other modules with out worrying of the repercussion on the initial set up files we set up earlier.</p><p>Refering to model class</p><pre><strong>var User = require(&#39;../models/user.js&#39;);<br>var dao = require(&#39;../models/dao&#39;);</strong></pre><p>Then</p><pre><strong>module.exports = function(server){<br>};</strong></pre><p>This is where ALL THE REQUESTS arrive jumping from the index.js file</p><p>there are many ways of handling those requests... the traditonal way is...</p><p>withing the enclaving function writing</p><pre><strong>server.get(&#39;/&#39;,(req,res,next)=&gt;{<br>res.send(&#39;inital page here&#39;);<br>});</strong></pre><p>the obvious methods of Restful app are GET, POST,DELETE... they are server object&#39;s methods</p><p>my favorite way of handling is sending the request to other file[hence scalability in practise]</p><pre><strong>var mInitAuth = require(&#39;./authentication.js&#39;);<br>//...<br>module.exports = function(server){<br>server.post(&#39;/&#39;,mInitAuth);<br>};</strong></pre><p>Within our authentication file we can refer to other classes like a database or other resources.</p><p>We start with</p><pre><strong>var mHome = require(&#39;./home.js&#39;);<br>var mWelcome = require(&#39;./welcome.js&#39;);<br>var dao = require(&#39;../models/dao.js&#39;);<br>var init = function(req,res,next){<br>    <br>};<br>module.exports = init;</strong></pre><p>by adding the authentication procedure within init function...</p><pre><strong>dao.auth(req,res,function(err,rows,fields){<br>    if(err&gt;0){<br>        //not autherised<br>        mWelcome(req,res,next);<br>    }else{<br>        mHome(req,res,next);<br>    }<br>});</strong></pre><p>we are further down the path of delegating the task of response to individual classes/files.</p><h4>Working on MySql</h4><p>Our dao.js file is database delegated file... where you do all the CRUD operation.</p><p>Let&#39;s see the initialiazation and implmenting function on it.</p><p>we have imported the mysql by first dowloading the library using</p><pre><strong>npm install mysql --save</strong></pre><p>command then refering the library</p><pre><strong>var mysql = require(&#39;mysql&#39;);<br>    var db = mysql.createConnection({<br>            <em>host</em>:&#39;127.0.0.1&#39;,<br>    		user:&#39;root&#39;,<br>   		password:&#39;123&#39;,<br>   		database: &#39;nodedb&#39;<br>});</strong></pre><p>and setting the required parameters, host of the database: can be in another network or same network as the web server</p><p>user name of the<strong> mysql engine</strong></p><p>password of the<strong> mysql engine</strong></p><p>the specific <strong>database we are using</strong></p><p>N.<strong><em>B </em></strong><em>never use the root user for production stage... always create a user with very few previledges and use that for client purpose!!!</em></p><p>into our auth function with it&#39;s callback functions</p><pre><strong>exports.auth = function(req,res,callback){<br>db.connect(function(err) {<br>if (err) {<br>console.error(&#39;error connecting: &#39; + err.stack);<br>callback(1,0);<br>}<br>console.log(&#39;connected as id auth &#39; + db.threadId);<br>callback(0,1);<br>});<br>}</strong></pre><p>used callbacks to return result from dao class.</p><p>Based on the result of the dao.js auth method we can send the request to either home.js or welcome.js file where routing ends with a <strong><em>RESPONSE</em></strong>!!! YES we let the request pass through chain of modules/files and filtration to give the intended result.</p><p>That&#39;s all folks... You can use the above procedure to work with clear job defined classes that interact with each other with harmony. Hence a clear clear architecture. Cheers and enjoy have fun and rest with Restify ;-)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=84e4b5a448fc" width="1" height="1" alt=""><hr><p><a href="https://medium.com/compute-and-beyond/architecting-a-web-service-app-using-restify-framework-84e4b5a448fc">Architecting a Web Service App using Restify Framework</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>