Sunday, May 3, 2020

We continue with the discussion on Kotlin versus Java:

Kotlin provides features for introspecting the structure of our own program at runtime. It makes functions and properties first class citizens in the language so that their type or name can be looked up.  

The runtime reference to a Kotlin class is one of the best examples of reflection. This reference is a type and is different from the Java referenceThe Kotlin class corresponding to a Java class can be obtained with the   .Kotlin property.  

Since the reference is a type, it allows us to use them for instantiation.  There are several callable references that have a common supertype. 

Function references can be called directly. They can also be called with their reference type using the ‘::’ notation. 

The method reference can also be stored in a variable with a specified type. This gives us the ability to provide the necessary context when appropriate. 

Function composition is another use for reference types. By defining the operation on types, we can use the composition function itself on desired operands that are callable references. 

The :: operator can be used for properties of first class. Property objects are of type KProperty<Intand mutable properties are of type KMutableProperty<Int>. A property reference is a convenience over single generic parameter function. 

Kotlin allows operator overloading just like other languages with a binary or unary associativity, precedence and fixed symbolic representation or  name. The operator implementation is usually a member function or an extension function.  

Certain types of operators can be overloaded while others cannotAll arithmetic operators can be overloaded. Equality and comparision operators can also be overloaded but not identity operators. Custom inflix operators can be simulated using function callsInflix is a keyword and is used with functions that take a single parameter without a default value. Influx functions require both the receiver and function parameter to be specified.  

Friday, May 1, 2020

Kotlin vs Java continued...
Kotlin code is multiplatform code and yet it allows common code to depend on platform specific invocations. Usually, a set of interfaces is defined in the common code but and they are implemented in platform specific modules. Kotlin does away with this approach because it is not ideal. Interfaces is rather limiting and is not the only approach
Instead Kotlin provides expected and actual declarations. A common module can define expected declarations and the platform module can provide actual declarations. The actual declarations correspond to the expected ones.
The class declarations in these modules bear the keywords expect and actual. The compiler ensures that all platform modules have implementations corresponding to the expected declarations. This works with generics and type alias also.
Kotlin provides features for introspecting the structure of our own program at runtime. It makes functions and properties first class citizens in the language so that their type or name can
be looked up.
The runtime reference to a Kotlin class is one of the best examples of reflection. This reference is a type and is different from the Java reference. The Kotlin class corresponding to a Java class can be obtained with the   .Kotlin property.
Since the reference is a type, it allows us to use them for instantiation.  There are several callable references that have a common supertype.
Function references can be called directly. They can also be called with their reference type using the ‘::’ notation.
The method reference can also be stored in a variable with a specified type. This gives us the ability to provide the necessary context when appropriate.
Function composition is another use for reference types. By defining the operation on types, we can use the composition function itself on desired operands that are callable references.
The :: operator can be used for properties of first class. Property objects are of type KProperty<Int> and mutable properties are of type KMutableProperty<Int>. A property reference is a convenience over single generic  parameter function.

Thursday, April 30, 2020

Common issues encountered during longevity tool development include:
1. Test configuration loads only one assertion and skips over others.
2. Other assertion definitions are not clean
3. TestConfiguration and TaskConfiguration are not distinct
4. TestConfiguration parameters are not all honored.
5. TaskConfiguration parameters have a lot of copying and are not predictable with overlapping overwrites
6. TestConfiguration specifies payload but it is not exercised in the code
7. The starting parameters for position in the stream belong to the taskConfiguration
8. The streampolicies are not propagated to the Pravega controller
9. The eventTypes are not valid
10. The numReaders and numWriters are not strictly enforced
11. The different types of readers have different semantics
12. The assertions don’t all run, some are invalid
13. The custom configuration does not work as intended
14. The TestRuntime results are not all accurate
15. The TestRuntime performance counters are not invoked in all cases
16. The exception handling gets broken in a few cases as changes are scattered.
17. The unexpected exceptions appear in some cases when the controller is unavailable
18. The logging goes missing in a few cases such as in the TestRuntimeManager
19. The configuration picked up by the tool may be different from the tests
20. The configuration changes are not logged by the tool and it is hard to tell what changed
21. The reconfiguration of the tool redeploys the readers and writers but it is not visible
22. The tool does not exercise all the needed codepaths and are some are left out
23. The tool may not leverage all the policies and parameters available for configuring readers and writers on stream
24. The tool does not separate out the results for configuration on a one-on-one basis.
These are just some of the issues encountered in longevity tool development.

Wednesday, April 29, 2020

We were discussing Kotlin versus Java coroutines:


Coroutines are functions that enables asynchronous programming by launching and waiting for another code to execute. For example, we can make a request for a token and wait for it. This token can then be used to make a web-request for an item and process it. The processing can be done with threads.


the call to get a token can wait indefinitely in a blocking manner. When this occurs on numerous control threads, it hinders scalability. Instead this waiting can be avoided with a callback. the request for token is made asynchronous and the callback is invoked when done. Each of the methods such as getting a token, making a request to an item with the token and processing the item can now be asynchronous and involve a callback.


This benefit comes at the cost of exception handling within callbacks.  Instead Futures and Promises come to the rescue.  A future is an asynchronous call with a registered callback.  The Promise is the future result which in this case is the token.  When making a request for an item with the token in the form  of a future, the result of the post webrequest is returned immediately as a promise.


Promise avoids the nesting hell of callback by flattening and sequential logic. We can write requestTokenAsync().thenCompose { token -> createPostAsync(token, item) }.thenAccept { post -> processPost() }
This form composes and propagates exceptions with no nesting indentations but it introduces all those combinators in the form of thenSomething and thenSomethingElse ...
Kotlin coroutines rescues from this mode of programming by avoiding async and await and introducing a far simpler notion of suspend.
suspend fun requestToken(): Token {
       return token
}
And similarly,
suspend fun createPost(token: Token, item: Item): Post { … }
Fun processPost(post: Post) {…}
Suspend fun postItem(item: Item) {
      val token = requestToken()
      val post = createPost(token, item)
      processPost(post)
}
Exception handling and higher-order functions can continue to work like they did for regular functions
Even lambda’s can be suspended.





Tuesday, April 28, 2020

Kotlin versus Java continued:

We were discussing Kotlin versus Java. Kotlin brings a ton of new features over Java such as Lambda expressions, extension functions, smart casts, String templates, primary constructors, first-class delegation, type inferences, singletons, range expressions, operator overloading, companion objects and coroutines. 

We now discuss coroutines.
Coroutines are functions that enables asynchronous programming by launching and waiting for another code to execute. For example, we can make a request for a token and wait for it. This token can then be used to make a web-request for an item and process it. The processing can be done with threads.

the call to get a token can wait indefinitely in a blocking manner. When this occurs on numerous control threads, it hinders scalability. Instead this waiting can be avoided with a callback. the request for token is made asynchronous and the callback is invoked when done. Each of the methods such as getting a token, making a request to an item with the token and processing the item can now be asynchronous and involve a callback. 

This benefit comes at the cost of exception handling within callbacks.  Instead Futures and Promises come to the rescue.  A future is an asynchronous call with a registered callback.  The Promise is the future result which in this case is the token.  When making a request for an item with the token in the form  of a future, the result of the post webrequest is returned immediately as a promise.

Promise avoids the nesting hell of callback by flattening and sequential logic. We can write requestTokenAsync().thenCompose { token -> createPostAsync(token, item) }.thenAccept { post -> processPost() } 

This form composes and propagates exceptions with no nesting indentations but it introduces all those combinators in the form of thenSomething and thenSomethingElse ...

Kotlin coroutines rescues from this mode of programming by avoiding async and await and introducing a far simpler notion of suspend. 
suspend fun requestToken(): Token { 
       return token
}

#codingexercise
List <String> mapByLookupHostname(List <String> resources) { 
Return resources.stream () 
             . map( x ->getHostname(x)) 
              .collect (Collectors.toList ()); 

} 

Monday, April 27, 2020

Kotlin versus Java continued:

We were discussing Kotlin versus Java. Kotlin brings a ton of new features over Java such as Lambda expressions, extension functions, smart casts, String templates, primary constructors, first-class delegation, type inferences, singletons, range expressions, operator overloading, companion objects and coroutines. 

Lambda expressions are just like functions. Kotlin functions are first class which allow them to passed like parameters.  A function that receives such parameters is a higher order function. A Lambda function can be instantiated within a function literal. An anonymous function has no name.  Function types can be instantiated by callable reference. 

Together lambda expressions and inline controls provide highly performant control structures. Next, even a class can be extended without having to inherit or using a decorator. This is done via extensions. The Extension functions are easy to spot with the ‘this’ parameter passed in. They are dispatched statically. 
The compiler can infer the function types for variables. A function type can be invoked the invoke operator. Inline functions provide flexible control.

Type safety for generics can be enforced as compile time with Kotlin, while at runtime instances of the runtime holds no information. The compiler prohibits type conformance where type erasure may occur.  

String literals are another useful feature for Kotlin. A String literal may contain template expression which involves a piece of code usually beginning with a dollar sign.  

Kotlin does not support checked exceptions. Many believe that checked exceptions lead to decreased productivity with no significant improvement to code quality. In fact, some call it an outright mistake

The above comparison makes it equally easy to enumerate what Java has that Kotlin does not. These include checked exceptions, primitive types that are not classes, static members, non-private fields, wildcard types and ternary operator.  

#coding exercise
Gray code is also known as reflected binary code since the 0 and 1 sequence in a bit position is reflected during single bit changes between numbers leading up to the given number.
To convert to gray code, we write the number in its binary notation first. Say 9 is 1001.
the digits d1, d2, ... dn. If the dn-1 is 1 then substitute dn with 1-dn and proceed forward to dn-1 otherwise leave it unchanged and proceed forward. The resulting number is the binary reflected Gray code. 9's gray code is 1101.
The reverse conversion from a Gray code (g1, g2, .. gn-1) to the binary notation for a number is done by calculating
Sum(n) = (Sum 1 <= i <= n-1 (gi)) (mod 2)
If this computes as 1, then replace gn by 1-gn, otherwise leave it unchanged.
        public static string GrayCode(string number)
        {
            char[] binary = number.ToCharArray();
            for (int i = binary.Length - 1; i > 0; i--)
            {
                if (binary[i - 1] == '1')
                {
                    binary[i] = binary[i] == '1'  ? '0' : '1'; // set 1-x
                }
            }
            return new String(binary);
        }