Showing posts with label z9890| Best Practice. Show all posts
Showing posts with label z9890| Best Practice. Show all posts

Exception Example

scala> :paste
// Entering paste mode (ctrl-D to finish)

// Best Practice : Exceptions are NOT recommended in Scala
// Might need to use when we are dealing with Java APIs
//#Programming Scala:83
//psn > a30 > a50
//Example : Identifying the file size
import scala.io.Source
import scala.util.control.NonFatal
object ReadFile {
  def main(args: Array[String]) = {
    args.foreach{ arg =>
                  println(s"arg -> $arg")
                  countLineSize(arg)  
                }
  }
  
  // Count no of lines in the given File
  def countLineSize(fileName: String) = {
    println("Inside countLineSize()")
    var source: Option[Source] = None
    try {
      source = Some(Source.fromFile(fileName))
      val size = source.get.getLines.size
      println(s"file $fileName has $size lines")
    }catch {
      //*** Instead of using Separate Catch Clause to handle
      //    every exception type, we can use pattern matching
      case NonFatal(x) => println(s"Non fatal exception -> $x")
    }finally {
        // Extract 'Source' from 'Option'
        for (s <- source) {
            println(s"Closing file $fileName...")
            s.close
       }
    }
  }
  
}

// Exiting paste mode, now interpreting.

import scala.io.Source
import scala.util.control.NonFatal
defined module ReadFile

scala>  ReadFile.main(Array("./testfile.txt"))
arg -> ./testfile.txt
Inside countLineSize()
Non fatal exception -> java.io.FileNotFoundException: ./testfile.txt (No such file or directory)

Ways to call a method with Empty argument list

scala> //#PS:72

scala> //psn > a30 > a30

scala> class MyClass(val myStr:String) {
     |   // Example : A method that has an empty argument List
     |   //           **Round brackets are NOT used
     |   def  firstPrint = println(myStr)
     |   // Example : A method that has an empty argument List
     |   //          **Round brackets are used
     |   def secondPrint():Unit = println(myStr)
     | }
defined class MyClass

scala> 

scala> val obj = new MyClass("This is a demo")
obj: MyClass = MyClass@2b6dbbd1

scala> // Round brackets is not used

scala> obj.firstPrint
This is a demo

scala> // This do not work as we have defined this method

scala> // with no round brackets

scala> obj.firstPrint()
<console>:10: error: Unit does not take parameters
              obj.firstPrint()
                            ^

scala> // Round brackets is NOT used

scala> obj.secondPrint
This is a demo

scala> // Round brackets is used

scala> obj.secondPrint()
This is a demo

Best Practice

It has been a convention to define an Empty argument List method without Brackets, when that method has no side effect(Example "mydata".size)