<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>Forem: Saurabh Kishore Tiwari</title>
    <description>The latest articles on Forem by Saurabh Kishore Tiwari (@saurabh975).</description>
    <link>https://forem.com/saurabh975</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F992818%2Fc462e153-c3f7-41ca-a20d-b5a27006f1db.jpg</url>
      <title>Forem: Saurabh Kishore Tiwari</title>
      <link>https://forem.com/saurabh975</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://forem.com/feed/saurabh975"/>
    <language>en</language>
    <item>
      <title>Observer Pattern in Scala</title>
      <dc:creator>Saurabh Kishore Tiwari</dc:creator>
      <pubDate>Sun, 30 Apr 2023 14:48:15 +0000</pubDate>
      <link>https://forem.com/saurabh975/observer-pattern-in-scala-5fgj</link>
      <guid>https://forem.com/saurabh975/observer-pattern-in-scala-5fgj</guid>
      <description>&lt;p&gt;Observer pattern has two main components — Subject and Observer. All observers subscribe to the subject, and in case of any kind of change, the subject is responsible for propagating that information to all observers. As you may have guessed, it sounds like a one-to-many dependency between objects. Let’s have a look at the UML diagram to get a better understanding.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--6f9AKGAH--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_66%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9bcruw6l3rottbh2jm4a.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--6f9AKGAH--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_66%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9bcruw6l3rottbh2jm4a.gif" alt="Image description" width="615" height="243"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Let’s breakdown the structure now
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Subject&lt;/strong&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Maintains a collection of all the observers.&lt;/li&gt;
&lt;li&gt;Provides an interface to attach and detach the observers.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Observer&lt;/strong&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Defines an updating interface for objects that should be notified of changes in the subject.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;ConcreteSubject&lt;/strong&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Stores the state of interest to ConcreteObserver.&lt;/li&gt;
&lt;li&gt;Sends a notification to its observers when it’s state changes.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;ConcreteObserver&lt;/strong&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Maintains a reference to ConcreteSubject.&lt;/li&gt;
&lt;li&gt;Might store state that should stay consistent with the subject’s state.&lt;/li&gt;
&lt;li&gt;Implements the Observer updating interface to keep its state consistent with the subject.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  Implementation
&lt;/h2&gt;

&lt;p&gt;Consider a stock company that tells its users the real-time value of all the stocks. The subject will be the stock company, and all the users who subscribe to it will be its observers.&lt;/p&gt;

&lt;h2&gt;
  
  
  CODE
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;User.scala&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;sealed trait Observer {
  def publishUpdate(stocks: mutable.Map[Int, Stock]): Unit
}

case class User(name: String, uuid: String) extends Observer:
  def publishUpdate(stocks: mutable.Map[Int, Stock]): Unit =
    println(name + " " + stocks.values.map(x =&amp;gt; x.name + " " + x.price))

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;StockCompany.scala&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;case class Stock(id: Int, name: String, price: Double)

sealed trait Subject {
  def registerNewUser(user: User): Unit
  def notifyUser(): Unit
  def deleteUser(user: User): Unit
  def registerStocks(stock: Stock): Unit
  def updateStockPrice(stock: Stock): Unit
}

object StockCompany extends Subject:
  private val stocks = mutable.TreeMap[Int, Stock]()
  private val users = mutable.TreeMap[String, User]()

  def registerNewUser(user: User): Unit =  // Attach
    users.put(user.uuid, user)
    user.publishUpdate(stocks)             // As soonas a user registers they get the live prices

  def notifyUser(): Unit =                 // Notify
    users.foreach(_._2.publishUpdate(stocks))

  def deleteUser(user: User): Unit =       // Detach
    users.remove(user.uuid)

  def registerStocks(stock: Stock): Unit =
    stocks.put(stock.id, stock)
    notifyUser()

  def updateStockPrice(stock: Stock): Unit =
    stocks.put(stock.id, stock)
    notifyUser()
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;MainRunner.scala&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;object MainRunner:
  def main(args: Array[String]): Unit =
    val user1 = User("user1", "ADBPR4561E")
    val user2 = User("user2", "BFTPD3461S")

    val stock1 = Stock(1, "stock1", 23.42)
    val stock2 = Stock(2, "stock2", 34.53)
    val stock3 = Stock(3, "stock3", 45.64)

    StockCompany.registerStocks(stock1)
    StockCompany.registerStocks(stock2)

    StockCompany.registerNewUser(user1)
    Thread.sleep(1000)
    StockCompany.registerNewUser(user2)
    Thread.sleep(1000)
    StockCompany.registerStocks(stock3)
    Thread.sleep(1000)
    StockCompany.updateStockPrice(Stock(3, "stock3", 123.45))

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Known Uses and Related Patterns
&lt;/h2&gt;

&lt;p&gt;This pattern can be used in any scenario, when the user has to be notified in case of any event/change occurs, like:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Mobile app for weather update&lt;/li&gt;
&lt;li&gt;Stock Prices getting updated live on WebPages&lt;/li&gt;
&lt;li&gt;Ticket confirmation&lt;/li&gt;
&lt;li&gt;Notification from any application&lt;/li&gt;
&lt;li&gt;Following a user on Instagram 😂&lt;/li&gt;
&lt;li&gt;“Notify me” when available on e-commerce sites&lt;/li&gt;
&lt;li&gt;Event listener on a button&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Now, if you give it a thought, the StockCompany has to take care of a lot of things. If we can somehow segregate the task and add another layer of abstraction (say a PriceManager) which will take care of notifying all the users, the stock company will just have to produce the prices to Price Manager and users will subscribe to Price manager while the Price manager orchestrates everything. This is kind of like a Publisher-Subscriber model(can be called a mediator model too based on the implementation)&lt;/p&gt;

</description>
    </item>
    <item>
      <title>Comma OK in GO</title>
      <dc:creator>Saurabh Kishore Tiwari</dc:creator>
      <pubDate>Mon, 19 Dec 2022 17:36:19 +0000</pubDate>
      <link>https://forem.com/saurabh975/comma-ok-in-go-l4f</link>
      <guid>https://forem.com/saurabh975/comma-ok-in-go-l4f</guid>
      <description>&lt;p&gt;Have you ever come across a statement like this?&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;func main(){
  i:= "hello world"
  n, ok := i.(int)
   if ok {
    fmt.Println("n :", n)
   } else {
    fmt.Println("not an int")
   }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Well, there’s no Try Catch block in Go. Coming from Java/Scala background, it felt weird at first but then GO grows on you, and then voila…you’re handling errors like a pro.&lt;/p&gt;

&lt;p&gt;Comma ok is one such way of error handling. It’s used in 4 different scenarios:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Test for error on a function return&lt;/li&gt;
&lt;li&gt;Testing if a key-value item exists in a Go map&lt;/li&gt;
&lt;li&gt;Testing if an interface variable is of a certain type&lt;/li&gt;
&lt;li&gt;Testing if a channel is closed&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Let’s have a look at each one with an example&lt;/p&gt;

&lt;h2&gt;
  
  
  1. Test for error on a function return
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;func main() {
 if ok, err := isEven(3); ok {
  fmt.Println("it's an even number")
 }else{
  fmt.Println(err)
 }
}

func isEven(n int)(bool, error){
 if n &amp;amp; 1 == 1{
  return false, fmt.Errorf("it's an odd number")
 }
 return true, nil
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The function isEven() takes an integer as input and checks if it’s even or not. The return type of isEven() is boolean and error. We store the boolean value in ok and use it in conditional statements.&lt;/p&gt;

&lt;h2&gt;
  
  
  2. Testing if a key-value item exists in a Go map
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;func main(){
   var stocks map[string]float64
   sym := "TTWO"
   price := stocks[sym]
   fmt.Printf("1. %s -&amp;gt; $%.2f\n", sym, price)

   if price, ok := stocks[sym]; ok {    // using comma ok to check if key exists
    fmt.Printf("2. %s -&amp;gt; $%.2f\n", sym, price)
   } else {
    fmt.Printf("2. %s not found\n", sym)
   }

   stocks = make(map[string]float64)   // It's importatnt to initialize the map before adding values. Else it's a panic situation
   stocks[sym] = 123.4
   stocks["APPL"] = 345.6

   if price, ok := stocks[sym]; ok {
    fmt.Printf("3. %s -&amp;gt; $%.2f\n", sym, price)
   } else {
    fmt.Printf("3. %s not found\n", sym)
   }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;OUTPUT:
1. TTWO -&amp;gt; $0.00
2. TTWO not found
3. TTWO -&amp;gt; $123.40
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Let’s understand what’s happening in the code.&lt;/p&gt;

&lt;p&gt;At first, we declare a map stocks with (key, value) type as (string, float). We try to get the value for key=TTWO, as there’s no key that matches TTWO, the default value of float, i.e. 0.00 is returned.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Note that there’s no error that was returned. We actually don’t know if 0.00 is the assigned value or the default value.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;This is where comma ok comes to the rescue. GO compiler is smart enough to understand what to return when the comma ok is added so in the line price, ok := stocks[sym], ok is assigned false, helping us with the dilemma.&lt;/p&gt;

&lt;h2&gt;
  
  
  3. Testing if an interface variable is of a certain type
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;func main(){
  i := "hello world"
  if n, ok := i.(int); ok{
    fmt.Println("It's an int")
  }else{
    fmt.Println("Not an int")
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This is just a slightly modified version of the code you saw above, to match the pattern we are following. That’s all 😉.&lt;br&gt;
Notice how intelligent the GO-compiler is? It knows in what context the comma ok is being used.&lt;/p&gt;
&lt;h2&gt;
  
  
  4. Testing if a channel is closed
&lt;/h2&gt;

&lt;blockquote&gt;
&lt;p&gt;GO channel is a medium through which a goroutine communicates with another goroutine and this communication is lock-free&lt;br&gt;
&lt;/p&gt;


&lt;/blockquote&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;func main() {
 ch := make(chan string)    //initializing a channel
 go func() {
  for i := 1; i &amp;lt;= 3; i++ {
   msg := fmt.Sprintf("Current num is #%v", i)
   ch &amp;lt;- msg
  }
  close(ch) //closing the channel lets range know exactly ho much data is there
 }()

 for msg := range ch {
  fmt.Println("received message : ", msg)
 }

 msg := &amp;lt;-ch
 fmt.Printf("Message from a closed channel : %#v\n", msg)

 msg, ok := &amp;lt;-ch  // recieving value through a channel with comma ok
 fmt.Printf("Message : %#v, (was it closed? -&amp;gt; %#v)\n", msg, !ok)
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;OUTPUT : 
received message :  Current num is #1
received message :  Current num is #2
received message :  Current num is #3
Message from a closed channel : ""
Message : "", (was it closed? -&amp;gt; true)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We create a go routine, which pushes 3 integers into the channel ch and closes it before exiting the routine. The for loop consumes the data from channel ch. Then we try to assign the next message in the channel to msg. Since it’s empty we get the output as an empty string.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Channels don’t run into the panic situation if there's nothing to consume. They simply return a default value. But you cannot add any value into a closed channel. It gives rise to a panic situation.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;We don’t really know if the value being consumed is the actual value or the default value. This is where comma ok comes to the rescue.&lt;/p&gt;

</description>
      <category>errors</category>
      <category>go</category>
      <category>commaok</category>
    </item>
    <item>
      <title>The Legends of GoRoutines — Parallelism and Concurrency</title>
      <dc:creator>Saurabh Kishore Tiwari</dc:creator>
      <pubDate>Mon, 19 Dec 2022 11:58:17 +0000</pubDate>
      <link>https://forem.com/saurabh975/the-legends-of-goroutines-parallelism-and-concurrency-1n8k</link>
      <guid>https://forem.com/saurabh975/the-legends-of-goroutines-parallelism-and-concurrency-1n8k</guid>
      <description>&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fbdhi09ix0v6xfqg640y4.jpeg" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fbdhi09ix0v6xfqg640y4.jpeg" alt="parallelism and concurrency"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Well, the clock speed of consumer CPUs has been constant to a few GHz for some years now. The obvious solution was to start gluing multiple CPU cores on top of each other to provide more processing power. This allowed for more available compute cycles.&lt;/p&gt;

&lt;p&gt;This is an excellent approach if you want to run a lot of non-intensive CPU programs. The CPU scheduler works like a charm and distributes individual tasks over available CPU cores. But let’s say, we have just one job and wish to distribute it over multiple cores. This is where the design of the program and algorithm comes into the picture.&lt;/p&gt;

&lt;p&gt;GO was designed for multitasking. There was so much importance given to multitasking that to start a parallel process in GO, you just need to start your statement with go. Take a look at the example below&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

func main(){
  for i := 1; i &amp;lt;= 3; i++{
    go func(n int){                // Parallel task is being created
      fmt.Printf("i : %d\n", n)
    }(i)
  } 
  time.Sleep(5 * time.Millisecond) // A sleep timer of 5 sec
}


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;&lt;code&gt;Output:&lt;br&gt;
i : 3&lt;br&gt;
i : 1&lt;br&gt;
i : 2&lt;br&gt;
&lt;/code&gt;&lt;br&gt;
Three parallel tasks are created and the user has no control over which one will execute first. Each parallel task is called a &lt;strong&gt;&lt;em&gt;goroutine&lt;/em&gt;&lt;/strong&gt;&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;If you don’t add a sleep timer, you probably won’t get any output because the execution won’t wait for a goroutine to complete. But adding a sleep timer isn’t a good idea, because the execution of routines isn’t something that can be predicted. A better way is to use &lt;a href="https://gobyexample.com/waitgroups" rel="noopener noreferrer"&gt;sync.Waitgroup&lt;/a&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;strong&gt;GoRoutines Behind the Curtain&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F4iq256qywrk6bnfvuheg.jpeg" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F4iq256qywrk6bnfvuheg.jpeg" alt="Go Scheduler in action"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;All goroutines are first pushed into a GRQ(Global Run Queue). Each Logical CPU has its OS Thread with its LRQ(Local Run Queue). Go Scheduler takes a routine from GRQ and randomly places it in any LRQ. Which is then picked up by the respective core and executed. This ensures Concurrency and Parallelism.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;If you are from the distributed systems world like me, doesn’t it feel like the Go Scheduler is like the YARN scheduler in HADOOP ???&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;strong&gt;&lt;em&gt;Special Cases (which are NOT so Special)&lt;/em&gt;&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;System calls(like I/O operations) are special cases where the execution of the program is suspended till the required operation is completed. If the routine stays in the LRQ till the operation is completed, a lot many CPU cycles will be wasted so a pretty decent solution is applied. Take an example of a single LRQ.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fja6g7mcbi98uhz7b8a5p.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fja6g7mcbi98uhz7b8a5p.png" alt="routine parking"&gt;&lt;/a&gt;&lt;br&gt;
Say goroutine G7 encounters a syscall. So, instead of waiting, it’s sent to a place where it can stay till the syscall is over. It's a Parking space for goroutines which are&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Sending and Receiving on Channel&lt;/li&gt;
&lt;li&gt;Network I/O&lt;/li&gt;
&lt;li&gt;System Call&lt;/li&gt;
&lt;li&gt;Timers&lt;/li&gt;
&lt;li&gt;Mutexes&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Once ready for execution, G7 is sent to the LRQ again.&lt;/p&gt;

</description>
      <category>go</category>
      <category>parallelism</category>
      <category>goscheduler</category>
    </item>
  </channel>
</rss>
