Skip to main content

Posts

Showing posts from May, 2022

Jsonview in Spring boot

Introduction There are scenarios where we have a DTO or a model class that contains a collection of properties and there might be some endpoints that require a subset of them and some other endpoint that might need all of them. Example: Consider a scenario where we need a list of Categories in a dropdown and we have an API that gets all the categories from the static masterdata and need to send to the UI in response to an API call. Problem Statement  We might choose to use a `Map` data type so that we send out the key-value pairs to the database or to choose to build a custom DTO with only the Id, name of the categories. In a longer run, if we opt to use multiple DTO in the source, sooner there will be a very large collection of DTO classes that represent subset of a static data. Solution Rather than ending up with a large number of such DTO classes, we can use a JSON View. This helps us have a single class and control which fields are part of which view.  Example: We can have a dropd

Handling exceptions in the Executor service threads in Java

Introduction This is a continuation post on the exception handling strategies in the threads in Java. For Introduction, please read this post The second post is available here This post addresses the problem statement "How to use the exception handlers in the threads spawned by the Executor Service in Java?" Not all times, we will be using Thread  classes to run our threads because we have to manage a lot of the underlying logic for managing threads. There is ExecutorService in Java which comes to the rescue for the above problem. In the previous posts, we have discussed on how to handle the exceptions in plain threads. However, when using executor service, we do not create / manage threads, so how do we handle exception in this case. We have a ThreadFactory   as an argument which can be used to customize the way threads are created for use within the ExecutorService . The below snippet of code leverages this feature to illustrate the exception handling, wherein we create a

Handling exceptions at thread level in Java

Introduction This is a continuation to the post on exception handling on threads. For those interested in the background, please visit this link This post discusses on the topic "Can I use separate exception handlers for threads performing mission critical tasks vs non trivial tasks?" Per-Thread Exception Handler Let's us assume that we built a handler that wants to notify the support team that something has gone wrong in some special thread processing, like the one below (not really notifying anyone but helps correlate the context) class SupportNotificationExceptionHandler implements Thread . UncaughtExceptionHandler { @Override public void uncaughtException ( Thread t, Throwable e) { notifySupport (t, e); } private void notifySupport ( Thread t, Throwable e) { System . out . println ( "Notified support team on: " + e. getMessage () + " raised from : " + t. getName ()); } } Let us now apply the above special handle

Handling Exceptions in Threads in Java

Introduction Exception handling is very critical to any application and any language that was used to develop. This helps the following stakeholders Stakeholders End-User: A graceful message that indicates that something has gone wrong in the system due to some wrong input or due to some internal fault Developer A clean way to get to know which line of code caused the exception and the stack trace that can help us reach to the points impacted Support Team A helpful hint that they can try to verify and resolve if it is something within their reach or to escalate to the product team SRE (Site Reliability Engineering) An indication of how far the application is performing w.r.to being reliable to the end-users and how faults are handled or tolerated etc.. Problem Statement When we use threads to get the job done for performing some intensive task (computation or Network intensive tasks), it becomes difficult to track down on the exceptions. This post is one in a series of posts that will

reified type in Kotlin

Introduction In Java, we have a type erasure problem where the runtime will not be able to preserve the type of the generic type that was intended and that will result in many times we having to pass the name of the class like Class<clz> ..  to provide the context information to perform the operations in generics. Type Erasure fun < T > getOnlyInts ( list : List < Any >): MutableList < T > { var result : MutableList < T > = mutableListOf () for ( item in list ) if ( item is T ) { result .add( item ) } return result } The above snippet of code illustrates the problem of type erasure where the type information for T is lost at runtime. this results in the type check failure in the line item is T Since the type data is erased , the runtime cannot figure out if it is performing the right type check. Hence the compilation fails. reiefied In Kotlin, we have the reified types which helps us to preserve the type information

sequences in Kotlin

Introduction Sequences in Kotlin are similar to that of the stream s in Java, where in the evaluation happens lazily and the volume of data processed in each step in the chain are reducing based on the met criteria. Sample Let us consider the below given sample data class data class Car ( val model : String , val year : Int ) We can create a collection of cars so that we can evaluate both and understand the difference between collections and sequence   in Kotlin var cars = listOf ( Car ( "Toyota" , 2021), Car ( model = "Tesla-S" , 2022), Car ( "Mercedes - Maybach" , 2022) ) Sequence In the below given snippet of code, we are performing the filtering of cars by name and then printing the year println ( cars . asSequence (). filter { it . model == "Toyota" } . map { it . year } This produces the output as given below kotlin.sequences.TransformingSequence@b97c004a This is because the sequence is lazy and is not evaluated as there is

when blocks in Kotlin

when This post shows multiple ways in which we can use the when  block in Kotlin We can start with a typical use of when (like in switch statements) enum class Season { SPRING , SUMMER , FALL , WINTER } To execute logic based on the season, we write the below snippet of code when ( timeOfYear ) { Season . SPRING -> println(" Flowers are blooming") Season . SUMMER -> println("It's hot!") Season . FALL -> println("It's getting cooler") Season . WINTER -> println("I need a coat") } In case we wanted to get the value rather than print based on the timeOfYear, we can use the below snippet of code, where we return the value and it can be returned in the overall when block val str = when ( timeOfYear ) { Season . SPRING -> "Flowers are blooming" Season . SUMMER -> "It's hot!" Season . FALL -> "It's getting cooler" Season . WINTER -> { "

Destructuring in Kotlin

Introduction This is a process in which we can be able to extract properties of interest from an object  / collection. We have been used to using destructuring in javascript and other functional languages whereas in Java / C# we have not been able to do this. However, kotlin has added the functionality to destructure classes by properties, collections, maps etc. Destructuring classes To enable a class to be destructured, should we do anything in kotlin? The answer is yes and no.. looks puzzling ain't it. Destructuring a class Below is a regular class (non data class) which needs implementation to allow it to be destructured class User ( var mail : String , var deptId : Long ) { operator fun component1 () = mail operator fun component2 () = deptId } Destructuring a data class Below is a declaration of a data class which comes with the support for destructuring for free as like toString, hashcode etc.. data class CompanyUser ( var mail : String , var deptId : Long ) Now that

enum in kotlin

ENUM Enums help us in defining like a fixed key-value pairs and then use them. These are to be used like fixed pairs and need not be stored in database or be something that shows up dynamically. These are mostly fixed entries. enum class ProductCategories ( val cat : String , val id : Int ) { ELECTRONICS ( "Electronics" , 0), ACCESSORIES ( cat = "Computer Accessories" , 1), PHERIPHERALS ( cat = "Computer Pheripherals" , id = 2); //This is a mandatory semi-colon fun getEnumId () = id fun categoryName () = cat } fun main (){ println ( ProductCategories . ACCESSORIES .categoryName()) println ( ProductCategories . PHERIPHERALS .categoryName()) }

anonymous objects in Kotlin

Anonymous Objects The benefit of using the anonymous objects is that they can be used to simplify usage rather than creating classes and then instantiating them and then consuming the functions. In this post, we are taking a simple interface and the interface is being used as an argument in a function. When we need to consume the method, we are required to create objects that are created from the classes that implement the interfaces. interface IPowerOfTwo { fun getPowerOf2 ( no : Int ): Int } fun printPowerOf2 ( powerOf2 : IPowerOfTwo ) { println ( "The value ^ 2 is : ${ powerOf2 .getPowerOf2(20) } " ) } Rather than creating the classes and instances, we can create an object on the fly and pass it as an argument to the function. fun main () { //The below method uses an anonymous object that has no class, yet implements the interface and gets the method ready for use printPowerOf2 ( object : IPowerOfTwo { override fun getPowerOf2 ( no : Int ) = no * n

Factory design pattern in Kotlin with companion objects

Factory Pattern The factory pattern helps the user to create the objects based on the inputs, so that the caller does not know how the object instances are created, instead focus on what are required to get me an instance of a given type. We start with a regular product, which has a constructor that takes the arguments and allows anyone to create the objects by invoking the appropriate constructor class RegularProduct { var skuId : String constructor ( sId : String ) { skuId = sId } constructor ( sId : String , upperCase : Boolean ) { skuId = if ( upperCase ) sId . toUpperCase () else sId . toLowerCase () } } //The private primary constructor restricts instantiation by any means other than factory class ProductWithFactory private constructor ( val sid : String ) { companion object { //Acts as a factory fun getProduct ( sid : String ): ProductWithFactory { return ProductWithFactory ( sid ) } fun getProduct ( si

Operations on Collections in Kotlin

Collections This post provides some of the operations that can be done in the collections using kotlin The below is the base type definitions that will be used in the below collection queries data class Shop ( val name : String , val customers : List < Customer >) data class Customer ( val name : String , val city : City , val orders : List < Order >) { override fun toString () = " $ name from ${ city . name } " } data class Order ( val products : List < Product >, val isDelivered : Boolean ) data class Product ( val name : String , val price : Double ) { override fun toString () = "' $ name ' for $ price " } data class City ( val name : String ) { override fun toString () = name } Operations on collections // Return a list of customers, sorted in the descending by number of orders they have made fun Shop. getCustomersSortedByOrders (): List<Customer> = this .customers.sortedByDescending( { it -> it.order