Latest Entries »

AngularJS Services

Introduction

Probably because there are so many ways to create services and differences in the various techniques can appear subtle, developers sometimes get confused by the various options. We’ll look at all the different ways we can create our own services in Angular.

Creating our own services is great, but we also need to understand how to properly use them.

Throughout the post, we’ll be adding features to a very simple app I’ve named Book Logger. The idea behind this is that it allows students to be able to use to log what books they read, and for how long they read them. We’ll add enough features to allow the adding and editing of books and the viewing of basic information about the readers in the app. I’ve tried to keep the app and the code required to run it as simple as possible. The one requirement is that you have NodeJS installed on your machine.

Why Services?

Services are a large a part of an Angular application. Constructing robust Angular services and taking full advantage of the various built-in services are vital abilities for any Angular Developer.

Developing super Angular apps means making the maximum of the built-in services. It means to take an app from simplistic to state-of-the-art.

The framework consists of lots of brilliant capability to assist us with networking, caching, logging, promises, and plenty extra. Writing our very own services is a great way to put in force reusable code and a good way to capture the logic unique to our application. Organizing our code into services leads to cleaner, better-defined components, which means we finish our project with more maintainable code.

Services Overview

There are five functions that are used to create an Angular service. The most fundamental service creation function is the provider function. Creating services with it allows us to explicitly create a configurable provider object.

The provider knows how to create the resulting service. Three of the remaining four functions all internally call the provider function. The first of those wrapper functions is the factory function. It’s a very easy to use wrapper around provider, and will probably become our primary service creation function.

The next service creation function is actually named service and is just a simple wrapper around the factory function. When we call the service function, it will internally call the factory function, which will then call the provider function. They are each small abstraction on top of one another.

Similarly, the fourth function i.e. the value function is just a thin wrapper around the factory function. We use it in much the same way we use the constant service which is the fifth function available for service creation. Value and constant look similar, but actually behave fundamentally different in a couple of important ways. The constant function is the one function in the list that’s quite different from all the rest. It doesn’t call the factory function or even a provider function. It is its own unique kind of service. It’s very simple but quite useful.

Provider Function

Services are designed to be injected into the other components in the application, therefore, their creation is very much a part of Angular’s dependency injection system. Objects that know how to create injectable services are known as providers, so before a new service can be created there must first be a provider that knows how to create that service. It’s the $provide service that we use to do that. It’s one of the services that ships with Angular as denoted by the leading $ in its name. It has several methods that register components with the Angular injector. Once registered, the injector knows how to find the correct instance and pass it as a parameter to other components needing it. All of that largely happens behind the scenes once we have created a service using one of the five methods discussed in this module. The basic process is that the $provide service creates a provider which contains a function that is used to create a service. The first function on the &provide service we’ll look at is the provider function. It’s the most fundamental way to create a service. All of the other methods of creating services which we’ll see are just wrappers around the provider function. The constant function, again, is the one exception. To use the provider function directly, we simply call the function and pass it a name and a function that will define the underlying provider. The provider created for each service, regardless of the technique we use, will be given a name that is the name we specify for the service with the word provider appended to it. So in this example, the name of the service we will ultimately inject into our other components, will be ‘books’, and the name of the provider will be booksProvider. The number one rule for using a provider function is that the function we pass to it must contain a property named $get. The function assigned to that property is the function that will be called by Angular to create our service. The service will then be represented by the return value of that function. Creating services with the provider function is a little more complicated than the other techniques we’ll look at. The benefit it offers in exchange for that added complexity is the ability to configure the underlying provider for our service. None of the other service creation functions allow us to do this. Let’s see how to create and configure a service with the provider function in a demo.


(function() {
var app = angular.module('app', []);
app.config(function($provide)){
$provide.provider('books',function(){
this.$get=function(){
var appName = 'Book Logger';
var appDesc = 'Track which books you read';
return {
appName: appName,
appDesc: appDesc
};
};
});
});
}());

view raw

app.js

hosted with ❤ by GitHub

Factory Function

Using the factory function on the provide service is usually a much simpler option than using provider, if we don’t need to configure the underlying provider object. All it really does is call the provider function and assign the function we pass to the factory function as the value of the get property on the provider.

To use the factory function, we just pass it a name as the first parameter, like we did with the provider function, and the second parameter is a function that will return an object that represents the service instance. If we don’t need to configure the provider, like we did in the last demo, then using the factory function will be a much simpler and readable way to create our services.


(function() {
angular.module('app')
.factory('dataService', dataService);
function dataService(logger) {
return {
getAllBooks: getAllBooks,
getAllReaders: getAllReaders
};
function getAllBooks() {
logger.output('getting all books');
return [
{
book_id: 1,
title: 'Harry Potter and the Deathly Hallows',
author: 'J.K. Rowling',
yearPublished: 2000
},
{
book_id: 2,
title: 'The Cat in the Hat',
author: 'Dr. Seuss',
yearPublished: 1957
},
{
book_id: 3,
title: 'Encyclopedia Brown, Boy Detective',
author: 'Donald J. Sobol',
yearPublished: 1963
}
];
}
function getAllReaders() {
logger.output('getting all readers');
return [
{
reader_id: 1,
name: 'Marie',
weeklyReadingGoal: 315,
totalMinutesRead: 5600
},
{
reader_id: 2,
name: 'Daniel',
weeklyReadingGoal: 210,
totalMinutesRead: 3000
},
{
reader_id: 3,
name: 'Lanier',
weeklyReadingGoal: 140,
totalMinutesRead: 600
}
];
}
}
dataService.$inject = ['logger'];
}());

view raw

dataService.js

hosted with ❤ by GitHub

Service Function

It’s just a thin wrapper around the factory function. The only difference is that the function we passed to the service method will be treated as a constructor function and called with the JavaScript “new” operator.

It uses the instantiate method of the injector to call the function we pass to the service method. The instantiate method will then use the “new” operator to execute the function that creates the service. We would use the service method instead of the factory method if we specifically needed our function to be treated as a constructor and called with the “new” operator. There are several reasons why we may want that behavior. One is if we have defined an inheritance hierarchy in our code. Creating an instance with “new” will make sure that our instantiated object properly inherits from its prototypes. Let’s now go add two new services using the factory and service functions to the bookLogger app.


(function() {
angular.module('app')
.service('logger', BookAppLogger);
function LoggerBase() { }
LoggerBase.prototype.output = function(message) {
console.log('LoggerBase: ' + message);
};
function BookAppLogger() {
LoggerBase.call(this);
this.logBook = function(book) {
console.log('Book: ' + book.title);
}
}
BookAppLogger.prototype = Object.create(LoggerBase.prototype);
}());

Value and Constant Functions

The two remaining service types are value and constant services. They look alike and are the two simplest types of services. The syntax for both types of services is very similar and straightforward.

The value function is just shorthand for calling the factory function with no parameters. If we don’t need to inject anything into the factory function, we can use the value function instead.

The constant function is not a shorthand version of anything. It allows us to register an object literal function or some other constant value with the injector, but it doesn’t call the service, factory or provider methods behind the scenes.

A value service can’t be injected into a module configuration function, but a constant service can.


(function () {
angular.module('app')
.value('badgeService', {
retrieveBadge: retrieveBadge
});
function retrieveBadge(minutesRead) {
var badge = null;
switch (true) {
case (minutesRead > 5000):
badge = 'Book Worm';
break;
case (minutesRead > 2500):
badge = 'Page Turner';
break;
default:
badge = 'Getting Started';
}
return badge;
}
}());

The final difference is related to decorators, which we’ll cover in the last module of the course. Decorators are a way to modify or override the behavior of an existing service.

Value services can be overridden by decorators, but constant services can’t as we wouldn’t be able to change the behavior of something created as a constant.


(function () {
angular.module('app')
.constant('constants', {
APP_TITLE: 'Book Logger',
APP_DESCRIPTION: 'Track which books you read.',
APP_VERSION: '1.0'
});
}());

So basically, with regard to Angular Services there are different ways we can create our own services. Some of them may look similar, but there are very good reasons for using each of them. Understanding how and why to use each of the available techniques will allow us to implement the best design possible in your application. I think it’s helpful to think of these functions, and really any API, like a set of tools. Before we can choose the best one for the job, we need to understand all of our tools and how to use them.

Java 8.0 What’s New

Programming Language

Lambda expression -Adds functional processing capability to Java

MathOperation addInt = (int a , int b) -> a+b;

Method references -Referencing functions by their names instead of invoking them directly. Using functions as parameter

testMe.operate(20,7,addInt);

Default method -Interface to have default method implementation

public interface Printer {
default void print(){
System.out.println("I am default printer");
}
}

Static method –Interface can have static method.
This is in addition to default method

public interface Printer {
static int printerId(){
System.out.println(“1");
}
}

Annotations -ability to apply the same annotation type more than once

@Retention( RetentionPolicy.RUNTIME )
public @interface Accounts {
AccountType[] value() default{};
}
@AccountType("Savings")
@AccountType("Current")
@AccountType("Priority")
@AccountType("NRI")
public interface Account {
}
@Repeatable(value = Accounts.class )
public @interface AccountType {
String value();
};

Annotations –applying annotation anywhere

List<@NotNull String> Strings;

Tools

New tools -New compiler tools and utilities are added like ‘jdeps’ to figure out dependencies

Nashorn, JavaScript Engine -A Java-based engine to execute JavaScript code in Java and vice versa. ‘jjs’ is used to invoke the Nashorn engine

Other Features

Stream API -New stream API to facilitate pipeline processing

long empCount = emps.stream().filter( emp-> emp.startsWith(“A")).count();

Date Time API -Improved date time API following good things from Joda library

LocalDate today = LocalDate.now();

Optional class -Emphasis on best practices to handle null values properly

Integer a = null;Optional x = Optional.ofNullable(a).isPresent(); //false

Concurrency –Aggregate operations support based on streams and lambda expressions using ForkJoinPoolclass. Best example is

parallelSort() method in java.util.Arrays

used for parallel sorting of large array elements.

ForkJoinPoolpool = new ForkJoinPool(5);

Variables passed in Java

One of the most simple yet confusing sometimes in programming world is when we deal with Strings. The below code fragment makes the comment much more interesting.

public static void main(String[] args) {
String x = new String("ab");
myMethod(x);
System.out.println("Value in main " + x);
}

public static void myMethod(String x) {
x = "cd";
System.out.println("Value in myMethod " + x);
}

Output:

Value in myMethod cd

Value in main ab

It creates a new String and stores it in the local variable ‘x’. The reference outside the method is not changed by this.

The key point here is that:

In Java, all method arguments are passed by value.

Methods have a local stack where all their data is stored, including the method arguments.

When we assign a new object to a variable that was passed into a method, we are only replacing the address in the local stack, with the address of the new object created unless we are returning from the method. The actual object address outside of the method remains the same.

 

da281aejpeg

 

So in the the above case,when the string “ab” is created, Java allocates the amount of memory required to store the string object. Then, the object is assigned to variable x, the variable is actually assigned a reference to the object. This reference is the address of the memory location where the object is stored.

The variable x contains a reference to the string object. x is not a reference itself. It is just a variable that stores a reference(memory address). Since,Java is pass-by-value.So when x is passed to the myMethod() method, a copy of value of x (a reference) is passed. The method myMethod() creates another object “cd” and it has a different reference. It is the variable x that changes its reference(to “cd”), not the reference itself.

Searching Algorithms in Java

  1. Linear Search
  2. Binary Search

 

Linear Search

Linear Search is the simplest search algorithm that consists of checking every one of its elements, one at a time and in sequence, until the desired one is found. It doesn’t require the collection to be sorted.

For a list with n items, the best case is when the value is equal to the first element of the list, in which case only one comparison is needed. The worst case is when the value is not in the list (or occurs only once at the end of the list), in which case n comparisons are needed.

It is having timing complexity with is O(n)


public int linerSearch(int[] data, int key){
         
        int size = data.length;
        for(int i=0;i<size;i++){
            if(data[i] == key){
                return i;
            }
        }
        return -1;
    }

 

Binary Search

Binary Search or half-interval search requires the array to be sorted and it can only be applied to a collection that allows random access (indexing)

Binary search works by comparing an input value to the middle element of the array. The comparison determines whether the element equals the input, less than the input or greater. When the element being compared to equals the input the search stops and typically returns the position of the element. If the element is not equal to the input then a comparison is made to determine whether the input is less than or greater than the element. Depending on which it is the algorithm then starts over but only searching the top or bottom subset of the array’s elements.

If the input is not located within the array the algorithm will usually output a unique value indicating this. Binary search algorithms typically halve the number of items to check with each successive iteration, thus locating the given item (or its absence) in logarithmic time.

It is having timing complexity with

Worst case performance: O(log n)

Best case performance: O(1)

Divide and Conquer Approach

public int binarySearch(int[] data, int key) {
		
        int start = 0;
        int end = data.length - 1;
        while (start <= end) {
            int mid = (start + end) / 2;
            if (key == data[mid]) {
                return mid;
            }
            if (key < data[mid]) {
            	end = mid - 1;
            } else {
            	start = mid + 1;
            }
        }
        return -1;
    }

Recursive Way

public int recursiveBinarySearch(int[] sortedData, int start, int end, int key) {
         
        if (start < end) {
            int mid = start + (end - start) / 2;  
            if (key  sortedArray[mid]) {
                return recursiveBinarySearch(sortedData, mid+1, end , key);
                 
            } else {
                return mid;   
            }
        }
        return -(start + 1);  
    }

A sorting algorithm is an algorithm that puts elements of a list in a certain order. The most-used orders are numerical order and lexicographical order. Efficient sorting is important for optimizing the use of other algorithms such as search and merge algorithms, which require input data to be in sorted lists; it is also often useful for canonicalizing data and for producing human-readable output.

  1. Bubble Sort
  2. Selection Sort
  3. Insertion Sort

 

Bubble Sort

Bubble sort is notoriously slow, but it’s conceptually the simplest of the sorting algorithms, and for that reason is a good beginning for our exploration of sorting techniques.

It is having timing complexity with

Best case performance O(n)
Average case performance O(n2)
Worst case performance O(n2)

Let us look how bubble sort works by taking a scenario of sorting a Cricket Players according to their height. Assume that a selector is nearsighted so that he can see only two of the players at the same time, if they’re next to each other and if he stand very close to them. Given this situation, imagine how would he sort them? Let us assume there are N players, and the positions they’re standing in are numbered from 0 on the left to N–1 on the right. We start at the left end of the line and compare the two players in positions 0 and 1. If the one on the left (in 0) is taller, we swap them. If the one on the right is taller, we don’t do anything. We then move over one position and compare the players in positions 1 and 2. Again, if the one on the left is taller, we swap them.
Here are the rules we’re following:
1.Compare two players.
2.If the one on the left is taller, swap them.
3.Move one position right.

public int[] bubbleSort(int[] data) {

 int lengthArray = data.length;
 int temp = 0;
       for(int i=0;i< lengthArray;i++) {  
          for(int j = lengthArray-1; j >= i + 1; j--) {
	      if (data[j] < data[j - 1]) {
	          temp = data[j];
                  data[j] = data[j - 1];
	          data[j - 1] = temp;
	       }
           }
        }
       return data;
 }

Selection Sort

Selection sort is popular for its non-complex structure, and it has performance advantages over more complicated algorithms, it offers a significant improvement for large records that must be physically moved around in memory and improves on the bubble sort by reducing the number of necessary swaps.

It is having timing complexity with

Best case performance O(n2)
Average case performance O(n2)
Worst case performance O(n2)

Let us look at the same scenario but this time we use Selection Sort Here we again start with the players from the left side and record the leftmost player’s height in a notebook . Then compare the height of the next player to the right with the height in the notebook. If this player is shorter, we strike off the height of the first player, and record the second player’s height instead. We Continue down the row, comparing each player with the minimum and change the minimum value in our notebook, whenever we find a shorter player. When we’re done, the height on the notebook will be the height of the shortest player. We now swap this shortest player with the player on the left end of the line. We’ve now sorted one player and made N–1 comparisons, but only one swap.
Here are the rules we’re following:
1.Compare two players.
2.If the one on the left is shorter, we note the height.
3.Move one position right.
4.Compare them and note the shortest of them and continue
5.Swap the shortest with the leftmost.
On the next pass, we do exactly the same thing, except that we can completely ignore the player on the left, because this player has already been sorted.

public int[] selectionSort(int[] data) {

  int lengthArray = data.length;
  int key = 0;
  int temp = 0;

	for (int i = 0; i < lengthArray; i++) {
	       key = i;
	       for (int j = i; j  data[j],j++) {
                     if(data[key] > data[j]){
			key = j;
		      }
		}
		temp = data[i];
		data[i] = data[key];
		data[key] = temp;
	}

	return data;
}

 

Insertion Sort

Insertion sort is also not too complex and is one of the best of the elementary sorts.It’s about twice as fast as the bubble sort and somewhat faster than the selection sort in normal situations. It’s often used as the final stage of more sophisticated sorts, such as quicksort.

It is having timing complexity with

Best case performance O(n2)
Average case performance O(n2)
Worst case performance O(n2)

Lets us take a new and more simple example,sorting a pack of cards

Insertion sort works the way we generally sort a hand of playing cards. We start with an empty left hand and the cards face down on the
table. We then remove one card at a time from the table and insert it into the correct position in the left hand. To find the correct position for a card, we compare it with each of the cards already in the hand, from right to left. At all times, the cards held in the left hand are sorted, and these cards were originally the top cards of the pile on the table.
Here are the rules we’re following:
1.Compare two cards.
2.If the one on the left is smaller, we note the number.
3.Insert the number in the correct position.
4.Continue with the next number.

 public int[] insertionSort(int[] data) {
   int lengthArray = data.length;
   int key = 0;
   int i = 0;
       for (int j = 1; j < lengthArray; j++) {
            key = data[j];
            i = j - 1;
              while (i >= 0 && data[i] > key) {
                 data[i + 1] = data[i];
                 i = i - 1;
                 data[i + 1] = key;
              }
       }
        return data;
  }

Love Story of Narayana Murthy (Infosys Founder) and Sudha (From Sudha’s Autobiography)

It was in Pune that I met Narayan Murty through my friend Prasanna who is now the Wipro chief, who was also training in Telco(TataMotors). Most of the books that Prasanna lent me had Murty’s name on them which meant that I had a preconceived image of the man. Contrary to expectation, Murty was shy,bespectacled and an introvert. When he invited us for dinner. I was a bit taken aback as I thought the young man was making a very fast move. I refused since I was the only girl in the group. But Murty was relentless and we all decided to meet for dinner the next day at 7.30 p.m .. at Green Fields hotel on the Main Road ,Pune.

The next day I went there at 7′ o ! clock since I had to go to the tailor near the hotel. And what do I see? Mr. Murty waiting in front of the hotel and it was only seven. Till today, Murty maintains that I had mentioned (consciously!) that I would be going to the tailor at 7 so that I could meet him… And I maintain that I did not say any such thing consciously or unconsciously because I did not think of Murty as anything other than a friend at that stage. We have agreed to disagree on this matter.

Soon, we became friends. Our conversations were filled with Murty’s experiences abroad and the books that he has read. My friends insisted that Murty as trying to impress me because he was interested in me. I kept denying it till one fine day, after dinner Murty said, I want to tell you something. I knew this as it. It was coming. He said, I am 5’4″ tall. I come from a lower middle class family. I can never become rich in my life an! d I can never give you any riches. You are beautiful, bright, and intelligent and you can get anyone you want. But will you marry me? I asked Murty to give me some time for an answer. My father didn’t want me to marry a wannabe politician, (a communist at that) who didn’t have a steady job and wanted to build an orphanage…

When I went to Hubli I told my parents about Murty and his proposal. My mother was positive since Murty was also from Karnataka, seemed intelligent and comes from a good family. But my father asked: What’s his job, his salary, his qualifications etc? Murty was working as a research assistant and was earning less than me. He was willing to go dutch with me on our outings. My parents agreed to meet Murty in Pune on a particular day at10 a. m sharp. Murty did not turn up. How can I trust a man to take care of my daughter if he cannot keep an appointment, asked my father.

At 12noon Murty turned up in a bright red shirt! He had gone on work to Bombay , was stuck in a traffic jam on the ghats, so he hired a taxi(though it was very expensive for him) to meet his would-be father-in-law. Father was unimpressed. My father asked him what he wanted to become in life.

Murty said he wanted to become a politician in the communist party and wanted to open an orphanage. My father gave his verdict. NO. I don’t want my daughter to marry somebody who wants to become a communist and then open an orphanage when he himself didn’t have money to support his family.

Ironically, today, I have opened many orphanages something, which Murty wanted to do 25 years ago. By this time I realized I had developed a liking towards Murty which could only be termed as love. I wanted to marry Murty because he is an honest man. He proposed to me highlighting the negatives in his life.. I promised my father that I will not marry Murty without his blessings though at the same time, I cannot marry anybody else. My father said he would agree if Murty promised to take up a steady job. But Murty refused saying he will not do things in life because somebody wanted him to. So, I was caught between the two most important people in my life.

The stalemate continued for three years during which our courtship took us to every restaurant and cinema hall in Pune. In those days, Murty was always broke. Moreover, he didn’t earn much to manage. Ironically today, he manages Infosys Technologies Ltd., one of the world’s most reputed companies. He always owed me money. We used to go for dinner and he would say, I don’t have money with me, you pay my share, I will return it to you later. For three years I maintained a book on Murty’s debt to me.. No, he never returned the money and I finally tore it up after my wedding.

The amount was a little over Rs 4000. During this interim period Murty quit his job as research assistant and started his own software business. Now, I had to pay his salary too! Towards the late 70s computers were entering India in a big way.

During the fag end of 1977 Murty decided to take up a job as General Manager at Patni computers in Bombay .. But before he joined the company he wanted to marry me since he was to go on training to the US after joining. My father gave in as he was happy Murty had a decent job, now.

WE WERE MARRIED IN MURTY’S HOUSE IN BANGALORE ON FEBRUARY 10, 1978 WITH ONLY OUR TWO FAMILIES PRESENT.I GOT MY FIRST SILK SARI. THE WEDDING EXPENSES CAME TO ONLY RS 800 (US $17) WITH MURTY AND I POOLING IN RS 400 EACH..

I went to the US with Murty after marriage. Murty encouraged me to see America on my own because I loved travelling. I toured America for three months on backpack and had interesting experiences which will remain fresh in my mind forever. Like the time when the New York police took me into custody because they thought I was an Italian trafficking drugs in Harlem . Or the time when I spent the night at the bottom of the Grand Canyon with an old couple. Murty panicked because he couldn’t get a response from my hotel room even at midnight. He thought I was either killed or kidnapped.

IN 1981 MURTY WANTED TO START INFOSYS. HE HAD A VISION AND ZERO CAPITAL…initially I was very apprehensive about Murty getting into business. We did not have any business background … Moreover we were living a comfortable life in Bombay with a regular pay check and I didn’t want to rock the boat. But Murty was passionate about creating good quality software. I decided to support him. Typical of Murty, he just had a dream and no money. So I gave him Rs 10,000 which I had saved for a rainy day, without his knowledge and told him, This is all I have. Take it. I give you three years sabbatical leave. I will take care of the
financial needs of our house. You go and chase your dreams without any worry. But you have only three years!

Murty and his six colleagues started Infosys in 1981,with enormous interest and hard work. In 1982 I left Telco and moved to Pune with Murty. We bought a small house on loan which also became the Infosys office. I was a clerk-cum-cook-cum-programmer. I also took up a job as Senior Systems Analyst with Walchand group of Industries to support the house.

In 1983 Infosys got their first client, MICO, in Bangalore . Murty moved to Bangalore and stayed with his mother while I went to Hubli to deliver my second child, Rohan. Ten days after my son was born, Murty left for the US on project work. I saw him only after a year, as I was unable to join Murty in the US because my son had infantile eczema, an allergy to vaccinations. So for more than a year I did not step outside our home for fear of my son contracting an infection. It was only after Rohan got all his vaccinations that I came to Bangalore where we rented a small house in Jayanagar and rented another house as Infosys headquarters. My father presented Murty a scooter to commute. I once again became a cook, programmer, clerk, secretary, office assistant et al. Nandan Nilekani (MD of Infosys) and his wife Rohini stayed with us. While Rohini babysat my son, I wrote programs for Infosys. There was no car, no phone, and just two kids and a bunch of us working hard, juggling our lives and having fun while Infosys was taking shape. It was not only me but also the wives of other partners too who gave their unstinted support. We all knew that our men were trying to build something good.

It was like a big joint family,taking care and looking out for one another. I still remember Sudha Gopalakrishna looking after my daughter Akshata with all care and love while Kumari Shibulal cooked for all of us. Murty made it very clear that it would either be me or him working at Infosys. Never the two of us together… I was involved with Infosys initially.

Nandan Nilekani suggested I should be on the Board but Murty said he did not want a husband and wife team at Infosys. I was shocked since I had the relevant experience and technical qualifications. He said, Sudha if you want to work with Infosys, I will withdraw, happily. I was pained to know that I will not be involved in the company my husband was building and that I would have to give up a job that I am qualified to do and love doing.

It took me a couple of days to grasp the reason behind Murty’s request..I realized that to make Infosys a success one had to give one’s 100 percent. One had to be focussed on it alone with no other distractions. If the two of us had to give 100 percent to Infosys then what would happen to our home and our children? One of us had to take care of our home while the other took care of Infosys.

I opted to be a homemaker, after all Infosys was Murty’s dream. It was a big sacrifice but it was one that had to be made. Even today, Murty says, Sudha, I stepped on your career to make mine. You are responsible for my success.

That’s the Power of Love.

Every man needs a woman to motivate him and to give him a reason to live…

Sudha Murthy was livid when a job advertisement posted by a Tata company at the institution where she was completing her post graduation stated that ‘lady candidates need not apply’. She dashed off a ‘postcard’ to JRD, protesting against the discrimination. It was the beginning of an association that would change her life in more ways than one

There are two photographs that hang on my office wall. Every day when I enter my office I look at them before starting my day. They are pictures of two old people, one of a gentleman in a blue suit and the other a black-and-white image of a man with dreamy eyes and a white beard.

People have asked me if the people in the photographs are related to me. Some have even asked me, “Is this black-and-white photo that of a Sufi saint or a religious guru?” I smile and reply “No, nor are they related to me. These people made an impact on my life. I am grateful to them.” “Who are they?” “The man in the blue suit is Bharat Ratna JRD Tata and the black-and-white photo is of Jamsetji Tata.” “But why do you have them in your office?” “You can call it gratitude.”

Then, invariably, I have to tell the person the following story.

It was a long time ago. I was young and bright, bold and idealistic. I was in the final year of my master’s course in computer science at the Indian Institute of Science [IISc] in Bangalore, then known as the Tata Institute. Life was full of fun and joy. I did not know what helplessness or injustice meant.

It was probably the April of 1974. Bangalore was getting warm and red gulmohars were blooming at the IISc campus. I was the only girl in my postgraduate department and was staying at the ladies hostel. Other girls were pursuing research in different departments of science. I was looking forward to going abroad to complete a doctorate in computer science. I had been offered scholarships from universities in US. I had not thought of taking up a job in India.

One day, while on the way to my hostel from our lecture-hall complex, I saw an advertisement on the notice board. It was a standard job-requirement notice from the famous automobile company Telco [now Tata Motors]. It stated that the company required young, bright engineers, hardworking and with an excellent academic background, etc.

At the bottom was a small line: “Lady candidates need not apply.” I read it and was very upset. For the first time in my life I was up against gender discrimination.

Though I was not keen on taking up a job, I saw this as a challenge. I had done extremely well in academics, better than most of my male peers. Little did I know then that in real life academic excellence is not enough to be successful.

After reading the notice I went fuming to my room. I decided to inform the topmost person in Telco’s management about the injustice the company was perpetrating. I got a postcard and started to write, but there was a problem: I did not know who headed Telco. I thought it must be one of the Tatas. I knew JRD Tata was the head of the Tata Group; I had seen his pictures in newspapers (actually, Sumant Moolgaokar was the company’s chairman then).

I took the card, addressed it to JRD and started writing. To this day I remember clearly what I wrote. “The great Tatas have always been pioneers. They are the people who started the basic infrastructure industries in India, such as iron and steel, chemicals, textiles and locomotives. They have cared for higher education in India since 1900 and they were responsible for the establishment of the Indian Institute of Science. Fortunately, I study there. But I am surprised how a company such as Telco is discriminating on the basis of gender.”

I posted the letter and forgot about it. Less than 10 days later, I received a telegram stating that I had to appear for an interview at Telco’s Pune facility at the company’s expense.

I was taken aback by the telegram. My hostel mates told me I should use the opportunity to go to Pune free of cost — and buy them the famous Pune saris for cheap! I collected Rs 30 each from everyone who wanted a sari. When I look back, I feel like laughing at the reasons for my going, but back then they seemed good enough to make the trip.

It was my first visit to Pune and I immediately fell in love with the city. To this day it remains dear to me. I feel as much at home in Pune as I do in Hubli, my hometown. The place changed my life in so many ways.

As directed, I went to Telco’s Pimpri office for the interview. There were six people on the panel and I realised then that this was serious business. “This is the girl who wrote to JRD,” I heard somebody whisper as soon as I entered the room. By then I knew for sure that I would not get the job. That realisation abolished all fears from my mind, so I was rather cool while the interview was being conducted.

Even before the interview started, I reckoned the panel was biased, so I told them, rather impolitely, “I hope this is only a technical interview.” They were taken aback by my rudeness, and even today I am ashamed about my attitude.

The panel asked me technical questions and I answered all of them. Then an elderly gentleman with an affectionate voice told me, “Do you know why we said lady candidates need not apply? The reason is that we have never employed any ladies on the shop floor. This is not a co-ed college; this is a factory. When it comes to academics, you are a first ranker throughout. We appreciate that, but people like you should work in research laboratories.”

I was a young girl from small-town Hubli. My world had been a limited place. I did not know the ways of large corporate houses and their difficulties, so I answered, “But you must start somewhere, otherwise no woman will ever be able to work in your factories.”

Finally, after a long interview, I was told I had been successful. So this was what the future had in store for me. Never had I thought I would take up a job in Pune. That city changed my life in many ways. I met a shy young man from Karnataka there, we became good friends and we got married.

It was only after joining Telco that I realised who JRD was: the uncrowned king of Indian industry. Now I was scared, but I did not get to meet him till I was transferred to Bombay. One day I had to show some reports to Mr Moolgaokar, our chairman, who we all knew as SM. I was in his office on the first floor of Bombay House [the Tata headquarters] when, suddenly, JRD walked in. That was the first time I saw ‘appro JRD’. Appro means ‘our’ in Gujarati. That was the affectionate term by which people at Bombay House called him.

I was feeling very nervous, remembering my postcard episode. SM introduced me nicely, “Jeh (that’s what his close associates called him), this young woman is an engineer and that too a postgraduate. She is the first woman to work on the Telco shop floor.” JRD looked at me. I was praying he would not ask me any questions about my interview (or the postcard that preceded it). Thankfully, he didn’t. Instead he remarked. “It is nice that girls are getting into engineering in our country. By the way, what is your name?” “When I joined Telco I was Sudha Kulkarni, Sir,” I replied. “Now I am Sudha Murty.” He smiled that kindly smile and started a discussion with SM. As for me, I almost ran out of the room.

After that I used to see JRD on and off. He was the Tata Group chairman and I was merely an engineer. There was nothing that we had in common. I was in awe of him.

One day I was waiting for Murthy, my husband, to pick me up after office hours. To my surprise I saw JRD standing next to me. I did not know how to react. Yet again I started worrying about that postcard. Looking back, I realise JRD had forgotten about it. It must have been a small incident for him, but not so for me.

“Young lady, why are you here?” he asked. “Office time is over.” I said, “Sir, I’m waiting for my husband to come and pick me up.” JRD said, “It is getting dark and there’s no one in the corridor. I’ll wait with you till your husband comes.” I was quite used to waiting for Murthy, but having JRD waiting alongside made me extremely uncomfortable.

I was nervous. Out of the corner of my eye I looked at him. He wore a simple white pant and shirt. He was old, yet his face was glowing. There wasn’t any air of superiority about him. I was thinking, “Look at this person. He is a chairman, a well-respected man in our country and he is waiting for the sake of an ordinary employee.”

Then I saw Murthy and I rushed out. JRD called and said, “Young lady, tell your husband never to make his wife wait again.”

In 1982 I had to resign from my job at Telco. I was reluctant to go, but I really did not have a choice. I was coming down the steps of Bombay House after wrapping up my final settlement when I saw JRD coming up. He was absorbed in thought. I wanted to say goodbye to him so I stopped. He saw me and paused.

Gently, he said, “So what are you doing, Mrs Kulkarni? (That was the way he always addressed me.) “Sir, I am leaving Telco.” “Where are you going?” he asked. “Pune, sir. My husband is starting a company called Infosys and I’m shifting to Pune.” “Oh! And what you will do when you are successful?” “Sir, I don’t know whether we will be successful.” “Never start with diffidence,” he advised me. “Always start with confidence. When you are successful you must give back to society. Society gives us so much; we must reciprocate. I wish you all the best.”

Then JRD continued walking up the stairs. I stood there for what seemed like a millennium. That was the last time I saw him alive.

Many years later I met Ratan Tata in the same Bombay office, occupying the chair JRD once did. I told him of my many sweet memories of working with Telco. Later, he wrote to me, “It was nice listening about Jeh from you. The sad part is that he’s not alive to see you today.”

I consider JRD a great man because, despite being an extremely busy person, he valued one postcard written by a young girl seeking justice. He must have received thousands of letters every day. He could have thrown mine away, but he didn’t do that. He respected the intentions of that unknown girl, who had neither influence nor money, and gave her an opportunity in his company. He did not merely give her a job; he changed her life and mindset forever.

Close to 50 per cent of the students in today’s engineering colleges are girls. And there are women on the shop floor in many industry segments. I see these changes and I think of JRD. If at all time stops and asks me what I want from life, I would say I wish JRD were alive today to see how the company we started has grown. He would have enjoyed it wholeheartedly.

My love and respect for the House of Tatas remains undiminished by the passage of time. I always looked up to JRD. I saw him as a role model – for his simplicity, his generosity, his kindness and the care he took of his employees. Those blue eyes always reminded me of the sky; they had the same vastness and munificence.

Sudha Murthy is the chairperson of the Infosys Foundation. She is involved in a number of social development initiatives and is also a widely published writer.

Gayatri Mantra

Aum Bhur Bhuvah Swah, Tat Savitur Varenyam
Bhargo Devasya Dhimahi, Dhiyo Yo Nah Prachodayat

ॐ भूर्भुव: स्व: तत्सवितुर्वरेण्यं । भर्गो देवस्य धीमहि, धीयो यो न: प्रचोदयात् ।।

Hello world!

Welcome to WordPress.com. This is your first post. Edit or delete it and start blogging!