Wednesday, January 18, 2017

Skills Expectation from 7+ years of .Net/Java professional

In the last year, I decided to separate from earlier company and started looking for job opportunities.
As  my overall experience in the product based companies and interested in only product based company like Philips, Amazon, GE , Harmon, ABB, Fluke, Morgan Stanley etc.

By giving interviews to some of the above companies, got to know what companies expect from 7+ years of experience. So decided to share technical expectations so it can help others who is looking other opportunities.

1. Strong in OOPS - Inheritance, Polymorphism, Encapsulation and Abstraction.
     Clear difference between the Encapsulation and Abstraction is very important with examples.

2. Identifying objects/Classes when designing any system like implementing PayRoll System, Calculator, TicTacTo game etc.

3. UML concepts : Association, Composition and Aggregation with examples. Required to know Activity, Sequential and class diagrams.    

4.SOLID Principles in/out everything: Clear understanding of Liskov Substitution and Dependency inversion principle. Apart from DIP, Inversion of Control and Some IOC containers(DI injects) like Unity, NInject or MEF any one of clear understanding.

5. Design pattern : To explain design pattern, intent of pattern means what problem it is supposed to solve and difference between the patterns(Factory v/s Abstract Factory) is very important.
Some required patterns are: Singleton(difference with static class), factory, Abstract factory, Builder, Adapter, Facade(v/s Controller), Decorator(v/s Normal inheritance), Strategy, Repository, Unit of Work and visitor.

Architectural patterns : MVC, MVP, MVVM and layered Architectures.
UI layer, Workflow, Business, Data Access layer and Cross cutting concerns responsibilities and communication between these layers.
In the following links Design patterns are explained bit well.

6. For .Net framework- Required to read the CLR via C# by Jeffery Ritcher and WPF by Adam Nathan.
Be aware of latest release of new features in .Net 4.6.1 and WPF4.5
CLR and memory management is very important :)

7. Memory profiler : DotTrace or PerformanceMonitor(any one).

8.  Data Structures : List, Stack, Queue, Tree, Graph and HashTable (Collision techniques).Some problems based on that.
We can practice using the following links:

9. Unit Testing Framework : NUnit with Rhino mocks/Moq.
   Clear understanding of Stub vs Mocks 

10. Managerial Round : last but not least
·        How to gather requirements(Feature Specifications)
·        How to start the project from scratch (Basic Infrastructures)
·        How will ensure that your software is ready?
·        After getting into the project , how to start learning the big system.
·        UX and UI- How you take care.
·        Last project worked Architecture (very important)
·        Types of tests and How unit and Integration tests will help.
·        How you mentor new joinee.
·        Some random questions.....
Hope this might help to somebody in small world :)

 Please let me know , if any good links to learn more things.

Tuesday, October 13, 2015

Unit Testing



In this post lets try to answer a few questions on unit test. Would be great to hear from you which would help to improve my knowledge J

1.    What is NOT a unit test?
A Test which:
·           Talks to the database.
·           Communicates across the network
·           Touches the file system
·           Can’t run at the same time as any other unit tests
·           have to do special things to your environment to run it

2.    What is the necessity of a unit test and how does it lead to good maintainable source code?

            Existing unit tests benefits developers in at least two ways:
            1. Unit   tests provide concrete expressions of business requirements. It also provides the developer with debugging opportunity for deeper understanding of the existing code,.
            2. Ensures that changes made by the enhancement do not break the existing system, or gives the developer a testing pathway to test the existing behavior based on the enhancements.

  Adding new tests provides the following benefits:
  1. They ensure that code meets requirements.
  2. They ensure that all logic conditions are accounted for. They force the developer to   revisit the code they have just written and to approach it from different directions. This helps to find out conditions the developer might otherwise not think of, resulting in code changes to properly handle these conditions.

3.         How to start writing unit tests?
Following have to be kept in mind before we venture to write unit tests:
·         Understand what the code is doing :)
·         What is our assertion or expectation in test case? One and only One assertion per test.
·         How to mock the dependencies?
·         Name the test evidently; it should explain the business requirement that was achieved with this unit module.

Consider the following class:
internal class MostRecentlyUsedList : Collection
   {
       private readonly int m_maxSize;

       internal MostRecentlyUsedList(int maxsize)
       {
           if (maxsize <= 0)
           {
               throw new InvalidOperationException("Recent lists limitation should be more than 0.");
           }
           m_maxSize = maxsize;
       }

       ///
       /// If size exceeds more than maximum count,
       /// remove the first element and add the new element at last.
       ///
       /// item to be add
       internal void Insert(T item)
       {
           if (object.Equals(item, null))
           {
               throw new ArgumentNullException("item");
           }

           int itemPosition = Items.IndexOf(item);
           if (itemPosition == -1) //value not found
           {
               if (this.Count == m_maxSize)
               {
                   RemoveLastElement();
               }

               InsertAtFirst(item);
           }
           else
           {
               BringItemToTop(itemPosition);  
           }
       }

       ///
       /// If collection size is more than max size, collection will be trim to max size
       ///
       /// Existing Collection
       internal void AddRange(IEnumerable collection)
       {
           if (object.Equals(collection, null))
           {
               throw new ArgumentNullException("collection");
           }

           IEnumerable tempEnumerable = collection as T[] ?? collection.ToArray();
           if (tempEnumerable.Count() > m_maxSize)
           {
               tempEnumerable = tempEnumerable.Take(m_maxSize);
           }
           tempEnumerable.ForEach(obj => Insert(Count, obj));
       }

       internal void Replace(T original, T newone)
       {
           int existingpos = this.IndexOf(original);

           if (existingpos == -1)
           {
               throw new ArgumentException(string.Format("{0} not exist to edit.", original));
           }

           this.RemoveAt(existingpos);
           this.Insert(existingpos, newone);
       }

       #region Private methods
   
       private void InsertAtFirst(T item)
       {
           Insert(0, item);
       }

       private void RemoveLastElement()
       {
           this.RemoveAt(Count - 1);
       }

       private void BringItemToTop(int itemPosition)
       {
           T selectedItem = Items[itemPosition];
           Items.RemoveAt(itemPosition);
           InsertAtFirst(selectedItem);
       }

       #endregion
   }

Now we can start writing test for this class:

Suddenly, a question will arise, for which method (module) should a unit test be written?

All the public methods are testable, which interns call the private or protected methods. So if we write tests for public methods, it will cover the private or protected methods of the class.

Consider method => Insert()

List out test cases for Insert() method:

·     It should throw exception when null value is passed as argument
·     Insert the items more than MAXSIZE, list size should not be more than MAXSIZE
·     Insert the fresh item=> should insert at zeroth position
·     Insert existing item=> existing item should bubbled up in list

Now write all test cases separately:

Normal criteria to write test case name => MethodName_Scenario_Expectation
Test body is divided into three parts:
Arrange: setup everything needed for the running the tested code. This includes any initialization of dependencies, mocks and data needed for the test to run.
Act: Invoke the code under test.
Assert: Specify the pass criteria for the test, which fails it if not met.
  
  •  It should throw exception when null value is passed as argument
[Test]
       public void Insert_InsertNullItem_ThrowsException()
       {
            //Arrange
           const int maxSize = 5;// Don’t use magic numbers           
MostRecentlyUsedList mrulist = new MostRecentlyUsedList(maxSize);
           //Act, Assert
           Assert.Throws(() => mrulist.Insert(null));
}

  • ·         Insert the items more than MAXSIZE, list size should not be more than MAXSIZE

[Test]
public void InsertItems_MoreThanRecentListMaxCount_ListSizeShouldBeEqualToMaxCount()
       {
           //Arrange
           const int recentlyusedlimit = 4;
    MostRecentlyUsedList mrulist = new MostRecentlyUsedList(recentlyusedlimit);

           //Act
           mrulist.Insert(1);
           mrulist.Insert(2);
           mrulist.Insert(3);
           mrulist.Insert(4);
           mrulist.Insert(5);
           mrulist.Insert(6);

           //Assert
           Assert.AreEqual(recentlyusedlimit, mrulist.Count);
       }

Finally, most important is modify MostRecentlyUsedList=> Insert() method implementations , run tests again . If it fails, then our tests are good :)

In the same way we can write tests for remaining methods.

In the next blog I would write about,
  • Bad class design/implementation which are not testable. How we can convert to testable class.
  • Mocking techniques in C# to mock dependency  
Hope you enjoyed the read!, awaiting for your suggestions

Thanks a lot :)




Friday, December 12, 2014

Async and Await usage

The goal of this post is to explain the usage of async and await keywords, how could be used to convert the existing synchronous method to asynchronous method.

Pre-Requisites:
Working knowledge of Task
Details of what async and await mean can be found in MSDN.

Asynchrony is essential for activities that are potentially blocking, such as when your application accesses the web(or writing big stream to file). Access to a web resource sometimes is slow or delayed. If such an activity is blocked within a synchronous process, the entire application must wait. In an asynchronous process, the application can continue with other work that doesn't depend on the web resource until the potentially blocking task finishes. In this scenario, the usage of wait and async keywords helps to achieve Asynchrony.

Eg: Download the RSS feed from the web asynchronously.
Implementation of this example helps to differentiate the ease of code to achieve Asynchrony with/without async and await keywords.

This could be achieved in 3 ways

Synchronous - UI will be unresponsive until there is no response from the feed server. In the Dot net 4.5 era, nobody will follow this way.

Code snippet to achieve this:

internal static string GetFeed()
{
HttpWebRequest request = HttpWebRequest.Create(@"http://rss.news.yahoo.com/rss/entertainment") as HttpWebRequest;
WebResponse response = request.GetResponse();
Stream responseStream =  response.GetResponseStream();
return new StreamReader(responseStream).ReadToEnd();
}

AsyncCallback - UI will be responsive, but code becomes bulky with extra overhead of callbacks. Before introducing the async and await keywords, this way was very useful to achieve Asynchrony.

Code snippet to achieve this:

internal static void GetFeedUsingAsyncCallback()
        {
 HttpWebRequest request = HttpWebRequest.Create(@"http://rss.news.yahoo.com/rss/entertainment") as HttpWebRequest;
             request.BeginGetResponse(new AsyncCallback(OnGetResponse), request);
        }
  private static void OnGetResponse(IAsyncResult ar)
        {
            HttpWebRequest myHttpWebRequest = ar.AsyncState as HttpWebRequest;
            WebResponse response = (HttpWebResponse)myHttpWebRequest.EndGetResponse(ar);
            // Read the response into a Stream object.
            Stream responseStream = response.GetResponseStream();
            string content = new StreamReader(responseStream).ReadToEnd();

            //Raise event here
        }

Async and Await
·         Responsive UI
·         Clean code
·         Debugging becomes easier as sequential control flow.

Code snippet to achieve this:

 async internal static  Task<string>  GetFeedAsync()
     {
HttpWebRequest request = HttpWebRequest.Create(@"http://rss.news.yahoo.com/rss/entertainment") as HttpWebRequest;
WebResponse response = await request.GetResponseAsync();         
            Stream responseStream = response.GetResponseStream();

            return await new StreamReader(responseStream).ReadToEndAsync();
        }

Assume if Async method is not available, how we will convert it to async method?

async internal static Task<string> GetStringAsyncExtesion(this HttpWebRequest request)
        {
TaskCompletionSource<string> taskCompletionSource = new TaskCompletionSource<string>();

          
                await Task.Run(() =>
                               {
                                  try
                                 {
                                   WebResponse
                                       response = request.GetResponse();

                                   Stream responseStream = response.GetResponseStream();
                                   string result = new StreamReader(responseStream).ReadToEnd();
                                   taskCompletionSource.SetResult(result);
                                    }
                                    catch (Excecption ex)
                                    {
                                        taskCompletionSource.SetException(ex);
                                    }
                               });
           
          
            return await taskCompletionSource.Task;
 }

Use above created new async method as follows:
static internal Task<string> GetStringExplictAsync()
        {
HttpWebRequest request = HttpWebRequest.Create(@"http://rss.news.yahoo.com/rss/entertainment") as HttpWebRequest;

            return request.GetStringAsyncExtesion();
        }
Pl. Provide your comments on this post.