Thursday, April 14, 2016

QUACK LIKE A DUCK

TYPING PART II

Cbachellam
Atlanta, GA
April  14, 2016

Introduction

Today’s blog post comes with bells, whistles and an announcement that, the underlying theme of all the posts in this blog is: “there is always a chasm between theory and practice, but a well essayed technical work can bridge this gap, and seamlessly connect the two disparate world, though the latter is a precursor”. Now let us get back to science, we are in the continuum of the second part, in the chain of posts about TYPING. (checkout my previous post about TYPING PART I). We left with the need for typing and definition of typing in the previous post. In this post, we plunge into nominal and structural typing.

Nominal-Typing Vs Structural-Typing Alias Duck-Typing

Predominantly all high level compiled languages are baked with the typing feature called as Nominal Typing, which means that -

“a fully qualified unique name/identifier of the class and its contract / interface (which specifies the behavioral features or methods the class ought to implement) are matched/compatible by the name against the instantiated objects”. - cc

This idea or notion of tying down the object instances against the names of class / interface is called Nominal Typing (Object Oriented languages like C#/JAVA/C++). To paraphrase the above definition: Having class names as part of the meaning of objects is called nominality [1]. Also according to Benjamin Pierce [2], “The fact that recursive types come essentially for free in nominal systems is a decided benefit [of nominally-typed OO languages]”. 

On the contrary if the objects are matched against the structural equivalence of the entities in comparison (there by avoiding the fully qualified name / nominal information), then it is called as Structural Typing. Also Structural Typing is commonly called as Duck Typing. 

“If it walks like a duck and quacks like a duck, it must be a duck.” - unknown

- what it means is an object need not be tied down to its class merely by name of its class / interface, rather than, a perfect or close to perfect harmony with its class’s fields / properties and methods is deemed as passable.

TYPESCRIPT Code Snippet for Structural / Duck Typing example


interface IVector2D {
    x: number;
    y: number;
}
interface IVector3D {
    x: number;
    y: number;
    z: number;
}

var vector: IVector2D = { x: 0, y: 10, }
var vector3D: IVector3D = { x: 0, y: 10, z: 20 }
function iTakePoint2D(vector: IVector2D) { /* do something */ }

iTakeIVector2D(vector2D); // exact match okay
iTakeIVector2D(vector3D); // extra information okay
iTakeIVector2D({ x: 0 }); // Error: missing information `y`

References:

  1. Moez A. AbdelGawad.  An Overview of Nominal-Typing versus Structural-Typing in Object-Oriented Programming. 
  2. Benjamin C. Pierce. Types and Programming Languages. MIT Press, 2002.

Tuesday, March 8, 2016

C# Sugary Syntax Rush

 Cbachellam
Tuesday, March 8, 2016
Atlanta, GA.


Setting the stage: 

Today we are satisfying our craving towards sugary syntax for complex structures in asynchrony in C#. Though we have dealt with asynchrony in JavaScript in previous blogpost, this blogpost ignites questions like, why do we need async / await keywords in C#, the genesis or under the hood internals of asynchrony, what are its marked strengths and advantages, also dispel the myth and fallacious thinking etc. These are questions which have been nagging me from the moment I was exposed to asynchrony in C# and hopefully will alleviate pain.

Asynchrony in C#:

Asynchrony has been there from get go(gecko). There is nothing unique about it expect syntactical sugars. In C# any long running activity like reading a large file I/O operation or waiting for high latency network I/O operation can lead to blocking the UI thread and the GUI hangs for the response. This lead to genesis of asynchronous processing; non UI blocking activity, which is the prime driver behind all this invention. We previously had asynchronous operations in Silverlight API’s, like in a real world instance, where the user interacted with the autocomplete suggestion text box which hung up for every alphabet the user typed in, trying to serially process the input and waiting for the response. To get around this, class: HTTPWebRequest’s special asynchronous method BeginGetResponse takes in a callback as a parameter. The callback is fired on successful completion of receiving the response. In other words, the UI thread continues to perform other activity and tangentially fires off the long running network I/O operation and on completion, calls the callback which updates the UI with the response data. This way the non-blocking UI thread is achieved. Please note that I would like to dispel the myth- this doesn’t improve the performance but on the other hand improves the responsive nature of the GUI without blocking the user interaction.
Now how can we connect the dots with async/await keywords in modern C#. Let’s say if we have a chain of asynchronous instructions which gets fired on completion of one after another. The code gets unwieldy, complex and convoluted. Imagine jumping from callbacks to callbacks, which is unreadable and soon becomes a coding nightmare. To get around this, C# came up with a sugary syntax, that kind of eliminated the chafe and logic callback hops that one has to go through in understanding and reading async code. 

Does async / await spawn a thread?

As described in the above discussion, any activity that doesn’t stop or block the main UI thread and fired off tangentially can be boldly claimed as asynchronous. But the question is does this tangential firing, spawn a thread. No it doesn’t. Async code doesn’t create a thread. But on the other hand it uses Thread Pool. 

vis-à-vis JavaScript


This I see a major difference between JavaScript and C# asynchrony. JavaScript is more along the lines of a single thread getting chopped for multiple asynchronous operations. On the other hand, C# async is reusing the threads from thread pool. Both are ultimately syntactic sugars and improve the responsiveness of the UI.

Sunday, January 24, 2016

Digest on TYPE in Programming Languages- Part I

With intrinsic focus on Typescript
CbaChellam - January 24, 2016
Atlanta,Georgia.
Image result for typescript logo
Introduction

Today's blog post takes an aim and breaks down meticulously the TYPE in programming languages. As part of my curious research activities, i delved into a new open source language called as TYPESCRIPT. The more i dwell, i am starting to realize that there is more depth and dimension to it than just as a Transpiler. Please note that though the article talks about TYPE in programming languages in generic, it is also guided by the foundation of typescript.

What is Type in Programming Languages(PL)?

According to computer science, Type in languages means, a metadata that describes the kind of data stored in the designated memory location. This metadata can be of predefined primitive datatypes such as integer/float/string or an object (instance of a class). 

Why do we go for Typing?(Strongly Vs Weakly and Static Vs Dynamic Typed)

Strong typing doesn't allow mixing operations between mismatched data types. This allows to eliminate the runtime errors during static time or compile time. C# and JAVA are languages that support strong typing and hence static type checked. And Javascript is a weakly typed language and hence dynamically type checked. In languages like C#/JAVA a expression like this [1+”1”] yields a static error, pointing out that an explicit casting should fix the expression, like [1+(int)”1”=2]. On the other hand, weakly typed languages like Javascript, expression like [1+”1”] results in implicit casting of the right hand operand to int as 1, and yields a result as 2(integer). Though there are programming languages which have been allowing Gradual Typing, which means, parts of the program allow dynamically typed and other parts allow statically typed to coexist in the same language side by side.Typescript is one such language. Conversely, C# started as a statically typed language, but as of version 4.0 is gradually typed, allowing variables to be explicitly marked as dynamic by using the dynamic type.

Conclusion

Typescript is a superset of Javascript in the sense that the lacuna and frailty of javascript are amended in the super language. Javascript was never intended to be enterprise or industry ready, thats were features like gradual typing can bridge the gap and make it powerful. In the next coming series, we will take a look at Sub Type, Duck Type and Nominal Vs Structural Typing, again in the background of Typescript.

Through coding, we imitate god, which makes us not powerful but humble!

Saturday, August 22, 2015

Code Coverage Can Be Specious

cbachellam
August 22, 2015
code code code..
Dear Readers,
Today is a brand new fresh day and we need to sharpen our brain for another worthwhile reading about the misleading and fallacious reasoning behind code coverage. This blog post debunks the myth that every manager to quality assurance tester and in between, proclaims boldly with seemingly faintest doubt that a 100% coverage means that above par quality standards are achieved. Its not true folks!. Lets dig in and seek the thrill in burning our software dendrites and neurons. 


What is code coverage?

We are in the business or rather precisely, engineering of writing code and propping with unit test case suite(UTC) that vet/verify/validate the intention of code, there are tools out there which takes the UTC and maps or matches against the code in reassuring that the UTC in context has executed the real intention of the code and run/tested through all scenarios. Ultimately all code coverage tool after cranking, throws a percentage number that translates exactly to “How much of code has been tested?”. Like if i say the code coverage is 82%, means 82% of code has been tested and 18% of code roughly are untested.

Meaty part of blog: Why specious?

Why can this figure be misleading? We typically depend on coverage analysis tool that come with our IDEs. These IDEs hide the process and how the coverage percentage is measured.  Now there are numerous measurement points or parameters , just to mention few of them, 
  • Line coverage.
  • Statement coverage.
  • Condition Coverage / Multiple Condition Coverage.
  • Loop Coverage.
  • Path Coverage.
  • Branch Coverage.
  • Function Coverage.

I would disclaim here that this blog post is by no means an exhaustive body of literature on metrics and measurement and takes no attempt to describe every engineering key words. Hence the juicy part is: 

“ Lets take if we go by the line coverage of a function with 10 lines and UTC has tested all 10 lines- the downside would be: there are languages which has more than one statement per line.In that case 100%  line coverage can be totally misleading if the UTC fails to execute and skips statements that are ensconced or nested inside one line[ for e.g.:10 lines = 20 statements]. OR lets take an instance if we go by condition coverage: has each Boolean sub-expression evaluated both to true and false? -for e.g. pseudo logic : if a and b then, here  a=true/b=false and a=false/b=true would yield me 100% coverage; again misleading” 

I don't want to stress more on this as it has become explicit now that, what kind of metrics and measurement point/parameters we choose accentuates validity or factuality of the coverage percentage. It would be enlightening to mention here that, one particular third party code coverage tool takes this measurement a notch up by measuring the sequence point which are like drilling down further into statements and going to fine grained intermediate instructions set level and there by measuring code coverage percentages. 

Conclusion

Next time when anybody claims 100% coverage report, question the validity and the measurement points that was employed in the process.  Because you know it can be fallacious reasoning. 


Lets Build a Better World through Better Software!.

Tuesday, February 24, 2015

Subtly “ASYNC”

Warm-up
The much talked about in recent technology diaspora is async! It came with a flurry and still remains fuzzy to all of us, including me, until I recalibrated by research antenna up towards it. I come from primarily a web development platform and this article talks about async in client and server languages that I have predominantly used. This blog post expounds the theory behind asynchrony in modern languages like C# and JavaScript framework like Nodejs.

Short Sprint
Historically we have always dealt with predictable sequence of instructions that flows in certain predetermined order with its logical & control structures in place. Async is disrupting this. How? When single thread is assigned for the completion of a software program then it is synchronous operation. This way the thread in context is quasi utilised (or most of the times it’s just waiting for an I/O operation to complete). This is not the economical way of exploiting the precious thread execution time.



Figure 1 : Synchronous Operation



Figure 2: Asynchronous Operation


The downside of the above execution approach is the thread which performs execution of the three tasks (refer Figure 1) in certain order has to wait for the I/O operations and walk through a sequence in spite of lag or lull. On the other hand if one thread performs concurrently all the above three instruction (task) sets by efficient context switching like in the above figure (2), then its asynchronous operation.

Finish Line

There are multitudes of technologies out there and there is no unique tool which is sharp enough to solve all the real world problems out there. Likewise asynchronous techniques are suited to chop the thread execution time and switch between tasks when there is a lull due to I/O lag. This is suited for web related problems but not for high intensive processor heavy lifting tasks. And that’s where precisely my previous blog post kicks in <>.

Thursday, February 5, 2015

Joy of Parallelism: Am I a Work Pirate (Stealer)?

Rise of Parallelism:

We are already well ahead of the curve that transformed single processor machines into multi core revolution in hardware. This transformation has not yet fully been exploited by, ordinary to critical applications running on current hardware. Thanks to Microsoft for helping even the masses to unleash the power of parallelism. This post after a long hiatus from my side, comes with a bang about the nuances that drive the parallelism into the fore of technology world. This post talks about the coveted and cool algorithm that takes the multicore machines and turns into a massive cruncher.

The Crux of Parallelism:

The CPU intensive iterative/routine/concurrent tasks(fine grained language instruction sets) need to be treated as chunks (partitioned) that run on various multi core processors simultaneously and thereby after completion, consolidate the results of individual iterations(that run on respective processors) and present it to caller. These are not I/O intensive tasks, but these are processor intensive.

Guts of Work Stealing Algorithm:

That said, work stealing algorithm efficiently deals with optimally assigning and exploiting the power of unused /idle processors and, also balances the overall load amongst the processors. How? Each processor has a special abstract data structure, double ended queue called as deque. This is a structure where one can push and pop on both the ends. There is a private deque assigned to each processor and also global deque common to all the processors.  As when a task is spawned or forked (remember how a task is spawned in UNIX), that task is assigned/pushed to the local deque of the respective processor and it pops from bottom of deque and the processor monitors it by context-switching if there are more than one tasks in its deque. During execution of a single task in a given processor, it can lead to spawning of multiple tasks which are pushed into the local (private) deque. The interesting part here is if the processor happens to run out of tasks to execute or in other words- idle, then that processor in context can steal tasks from other processor’s deque (private) or global deque, keeping them busy. Now you see why the word stealing is there in its name.    

Conclusion:

Existing popular solutions in multi core parallelism advocates a shared memory concept rather than private memory. The latter part comes with a drawback of data synchronization cost. On the other hand work stealing algorithm which when leveraged in solving the parallel conundrum, helps to optimally use the idle processor without the cost of accessing the public memory share but with private memory fenced deque.

Reference:


[1] Scheduling Parallel Programs by Work Stealing with Private Deque. (Arthur Chargueraud, Umut A. Acar and Mike Rainey).

Wednesday, November 27, 2013

No Silver Bullet in Software

Today's post is not so technical but still talks about the software existential philosophy in an informal manner. I remember when I was an amateur, was fixated/obsessed on every cool software ideology. It’s like having a spanner/fix and trying to apply that on every single bolt/problem I came across. This is quite common in early stages of any profession, where the pursuer doesn't have a big picture about domain of interest, and hence doesn't have judgement or acumen to weigh pros and cons of an approach. On turning back, one realizes how naive we have been. Time has come now that, we see panoramic view of the software domain (relatively speaking), we laugh at ourselves and it’s quite a revelation too.


Now, how does above story fit into software story? One learns hard way that architectural / design principles and concepts are not silver bullet, in the sense that, they cannot be applied like the spanner on every bolt we come across. We need to consciously and meticulously weigh and factor the advantages and disadvantages in a disinterested/unbiased fashion. Like if you take, one shouldn't be fanatical on principle - "flexibility of code" and apply in every scenario, region, routine and sub routine of code. This on the other hand obfuscates things and becomes a maintenance nightmare. One should use his/her best judgment in applying these principles. This can arise only by experience and experiments.