affiliate_link

Wednesday, December 27, 2017

Func vs. Action vs. Predicate?

In C#, Action and Func are extremely useful tools for reducing duplication in code and decreasing coupling.

A simple way of thinking about Action<>

Most of us are pretty familiar with finding sections of repeated code, pulling that code out into a method and making that method take parameters to represent the differences.
public void SteamGreenBeans()
{
    var greenBeans = new GreenBeans();
    Clean(greenBeans);
    Steam(greenBeans, Minutes.Is(10));
    Serve(greenBeans);
}
 
public void SteamCorn()
{
    var corn = new Corn();
    Clean(corn);
    Steam(corn, Minutes.Is(15));
    Serve(corn);
}
 
public void SteamSpinach()
{
    var spinach = new Spinach();
    Clean(spinach);
    SteamVegetable(spinach, Minutes.Is(8));
    Serve(spinach);
}
 
Each one of these methods pretty much does the same thing.  The only difference here is the type of vegetable and the time to steam it.
It is a simple and common refactor to refactor that code to:
public void SteamGreenBeans()
{
   SteamVegetable(new GreenBeans(), 10);
}
 
public void SteamCorn()
{
    SteamVegetable(new Corn(), 15);
}
 
public void SteamSpinach()
{
    SteamVegetable(new Spinach(), 8);
}
 
public void SteamVegetable(Vegetable vegetable, int timeInMinutes)
{
    Clean(vegetable);
    Steam(vegetable, Minutes.Is(timeInMinutes));
    Serve(vegetable);
}
Much better, now we aren’t repeating the “actions” in 3 different methods.
Now let's imagine we want to do something more than steam.  We need to be able to fry or bake the vegetables.  How can we do that?
Probably we will have to add some new methods for doing that.  So we will end up with something like this:
public void SteamVegetable(Vegetable vegetable, int timeInMinutes)
{
    Clean(vegetable);
    Steam(vegetable, Minutes.Is(timeInMinutes));
    Serve(vegetable);
}
 
public void FryVegetable(Vegetable vegetable, int timeInMinutes)
{
    Clean(vegetable);
    Fry(vegetable, Minutes.Is(timeInMinutes));
    Serve(vegetable);
}
 
public void BakeVegetable(Vegetable vegetable, int timeInMinutes)
{
   Clean(vegetable);
   Bake(vegetable, Minutes.Is(timeInMinutes));
   Serve(vegetable);
}
Hmm, lots of duplication again.  No problem.  Let's just do what we did to the first set of methods and make a CookVegetable method.  Since we always clean, then cook, then serve, we should be able to just pass in the method of cooking we will use.
Oh wait, how do we do that?  We can’t just extract out Bake  or Fry  or Steam, because the Bake, Fry and Steam methods are logic and not data.
Unless… unless we can make them data.  Can we do that?
We sure can, check this out:
public void SteamVegetable(Vegetable vegetable, int timeInMinutes)
{
    CookVegetable(vegetable, Steam, timeInMinutes);
}
 
public void FryVegetable(Vegetable vegetable, int timeInMinutes)
{
    CookVegetable(vegetable, Fry, timeInMinutes);
}
 
public void BakeVegetable(Vegetable vegetable, int timeInMinutes)
{
    CookVegetable(vegetable, Bake, timeInMinutes);
}
 
public void CookVegetable(Vegetable vegetable,
   Action<Vegetable, int> cookingAction,
   int timeInMinutes)
{
    Clean(vegetable);
    cookingAction(vegetable, Minutes.Is(timeInMinutes));
    Serve(vegetable);
}
 
We got rid of the duplicated code the same way we did when we did our first refactor, except this time we parameterized method calls instead of data.
If you understood this, you understand Action.  Action is just a way of treating methods like they are data. Now you can extract all of the common logic into a method and pass in data that changes as well as actions that change.
Congratulations, you are doing the strategy pattern without having to create an abstract base class and a huge inheritance tree!
So when you see Action, just think “ah, that means I am passing a method as data.”
It really is as simple as that.
Action<Vegetable, CookingTime> translated to English is: “A method that takes a Vegetable and a CookingTime as parameters and returns void.”

What about Func<>?

If you understand Action, you understand Func.
Func<X, Y, Z> translated to English is: “A method that takes an X, and a Y as parameters and returns a Z”.”
The only difference between Action and Func is that Func’s last template parameter is the return type.  Funcs have non-void return values.
Bonus: Predicate is a Func that always returns a boolean.
That’s all there is to it.  There really isn’t a need to know much more than that to make sure of Action and Func in order to start using them.


Wednesday, December 20, 2017

Association vs Aggregation vs Composition

The question "What is the difference between association, aggregation and composition" has been frequently asked lately. Actually, Aggregation and Composition are subsets of association meaning they are specific cases of association. In both aggregation and composition object of one class "owns" object of another class. But there is a subtle difference:
  • Aggregation implies a relationship where the child can exist independently of the parent. Example: Class (parent) and Student (child). Delete the Class and the Students still exist.
  • Composition implies a relationship where the child cannot exist independent of the parent. Example: House (parent) and Room (child). Rooms don't exist separate to a House.

Monday, December 18, 2017

Dispose vs Finalize?

The finalizer is for implicit cleanup - you should use this whenever a class manages resources that absolutely must be cleaned up as otherwise you would leak handles / memory etc...
Correctly implementing a finalizer is notoriously difficult and should be avoided wherever possible - the SafeHandle class (avaialble in .Net v2.0 and above) now means that you very rarely (if ever) need to implement a finalizer any more.
The IDisposable interface is for explicit cleanup and is much more commonly used - you should use this to allow users to explicitly release or cleanup resources whenever they have finished using an object.
Note that if you have a finalizer then you should also implement the IDisposable interface to allow users to explicitly release those resources sooner than they would be if the object was garbage collected.
See DG Update: Dispose, Finalization, and Resource Management for what I consider to be the best and most complete set of recommendations on finalizers and IDisposable.

How do I know if a class in C# is unmanaged, whether I have to implement the IDisposable interface?

StreamReader is not an unmanaged resource itself, but it wraps one, and therefore it implements IDisposable. Anything that implements IDisposable should be disposed. Other than that, you don't have to worry about unmanaged resources unless you're using Windows API calls via PInvoke (because anything that wraps resources allocated that way should implement IDisposable)

using (StreamReader sr = new StreamReader(filename)) {
     txt = sr.ReadToEnd();
}

Thursday, December 7, 2017

Difference between Process and Thead

Process:
  • An executing instance of a program is called a process.
  • Some operating systems use the term ‘task‘ to refer to a program that is being executed.
  • A process is always stored in the main memory also termed as the primary memory or random access memory.
  • Therefore, a process is termed as an active entity. It disappears if the machine is rebooted.
  • Several process may be associated with a same program.
  • On a multiprocessor system, multiple processes can be executed in parallel.
  • On a uni-processor system, though true parallelism is not achieved, a process scheduling algorithm is applied and the processor is scheduled to execute each process one at a time yielding an illusion of concurrency.
  • Example: Executing multiple instances of the ‘Calculator’ program. Each of the instances are termed as a process.
Thread:
  • A thread is a subset of the process.
  • It is termed as a ‘lightweight process’, since it is similar to a real process but executes within the context of a process and shares the same resources allotted to the process by the kernel.
  • Usually, a process has only one thread of control – one set of machine instructions executing at a time.
  • A process may also be made up of multiple threads of execution that execute instructions concurrently.
  • Multiple threads of control can exploit the true parallelism possible on multiprocessor systems.
  • On a uni-processor system, a thread scheduling algorithm is applied and the processor is scheduled to run each thread one at a time.
  • All the threads running within a process share the same address space, file descriptors, stack and other process related attributes.
  • Since the threads of a process share the same memory, synchronizing the access to the shared data withing the process gains unprecedented importance.

How SSL Certificates Work?

  1.  
  2. 1. A browser attempts to connect to a Website, a.k.a. Web server, secured with SSL. 
  3. 2 .The browser requests that the Web server identify itself.
  4. 3. The Web server sends the browser a copy of its SSL certificate.
  5. 4. The browser checks to see whether or not it trusts the SSL certificate. If so, it sends a message to the Web server.
  6. 5. The Web server sends back a digitally signed acknowledgement to start an SSL encrypted session.
  7. 6. Encrypted data is shared between the browser and the Web server.

There are many benefits to using SSL Certificates. Namely, SSL customers:
  • Get HTTPs which elicits a stronger Google ranking
  • Create safer experiences for your customers
  • Build customer trust and improve conversions
  • Protect both customer and internal data
  • Encrypt browser-to-server and server-to-server communication
  • Increase security of your mobile and cloud apps
  •  
How SSL Works Chart

Wednesday, October 11, 2017

Latest C# Questions

Wherever you go in for your .NET interview in Montreal or Toronto, you should be ready to answer the following questions:
  1. How many languages .NET is supporting now? - When .NET was introduced it came with several languages. VB.NET, C#, COBOL and Perl, etc. 
  2. How is .NET able to support multiple languages? - a language should comply with the Common Language Runtime standard to become a .NET language. In .NET, code is compiled to Microsoft Intermediate Language (MSIL for short). This is called as Managed Code. This Managed code is run in .NET environment. So after compilation to this IL the language is not a barrier. A code can call or use a function written in another language.
  3. How ASP .NET different from ASP? - Scripting is separated from the HTML, Code is compiled as a DLL, these DLLs can be executed on the server.
  4. Resource Files: How to use the resource files, how to know which language to use?
  5. What is smart navigation? - The cursor position is maintained when the page gets refreshed due to the server side validation and the page gets refreshed.
  6. What is view state? - The web is stateless. But in ASP.NET, the state of a page is maintained in the in the page itself automatically. How? The values are encrypted and saved in hidden controls. this is done automatically by the ASP.NET. This can be switched off / on for a single control
  7. Explain the life cycle of an ASP .NET page.
  8. How do you validate the controls in an ASP .NET page? - Using special validation controls that are meant for this. We have Range Validator, Email Validator.
  9. Can the validation be done in the server side? Or this can be done only in the Client side? - Client side is done by default. Server side validation is also possible. We can switch off the client side and server side can be done.
  10. How to manage pagination in a page? - Using pagination option in DataGrid control. We have to set the number of records for a page, then it takes care of pagination by itself.
  11. What is ADO .NET and what is difference between ADO and ADO.NET? - ADO.NET is stateless mechanism. I can treat the ADO.Net as a separate in-memory database where in I can use relationships between the tables and select insert and updates to the database. I can update the actual database as a batch.

1) The C# keyword .int. maps to which .NET type?
  1. System.Int16
  2. System.Int32
  3. System.Int64
  4. System.Int128
2) Which of these string definitions will prevent escaping on backslashes in C#?
  1. string s = #.n Test string.;
  2. string s = ..n Test string.;
  3. string s = @.n Test string.;
  4. string s = .n Test string.;
3) Which of these statements correctly declares a two-dimensional array in C#?
  1. int[,] myArray;
  2. int[][] myArray;
  3. int[2] myArray;
  4. System.Array[2] myArray;
4) If a method is marked as protected internal who can access it?
  1. Classes that are both in the same assembly and derived from the declaring class.
  2. Only methods that are in the same class as the method in question.
  3. Internal methods can be only be called using reflection.
  4. Classes within the same assembly, and classes derived from the declaring class.
5) What is boxing?
a) Encapsulating an object in a value type.
b) Encapsulating a copy of an object in a value type.
c) Encapsulating a value type in an object.
d) Encapsulating a copy of a value type in an object.
6) What compiler switch creates an xml file from the xml comments in the files in an assembly?
  1. /text
  2. /doc
  3. /xml
  4. /help
7) What is a satellite Assembly?
  1. A peripheral assembly designed to monitor permissions requests from an application.
  2. Any DLL file used by an EXE file.
  3. An assembly containing localized resources for another assembly.
  4. An assembly designed to alter the appearance or .skin. of an application.
8) What is a delegate?
  1. A strongly typed function pointer.
  2. A light weight thread or process that can call a single method.
  3. A reference to an object in a different process.
  4. An inter-process message channel.
9) How does assembly versioning in .NET prevent DLL Hell?
  1. The runtime checks to see that only one version of an assembly is on the machine at any one time.
  2. .NET allows assemblies to specify the name AND the version of any assemblies they need to run.
  3. The compiler offers compile time checking for backward compatibility.
  4. It doesn.t.
10) Which .Gang of Four. design pattern is shown below?
public class A {
    private A instance;
    private A() {
    }
    public
static A Instance {
        get
        {
            if ( A == null )
                A = new A();
            return instance;
        }
    }
}
  1. Factory
  2. Abstract Factory
  3. Singleton
  4. Builder
11) In the NUnit test framework, which attribute must adorn a test class in order for it to be picked up by the NUnit GUI?
  1. TestAttribute
  2. TestClassAttribute
  3. TestFixtureAttribute
  4. NUnitTestClassAttribute
12) Which of the following operations can you NOT perform on an ADO.NET DataSet?
  1. A DataSet can be synchronised with the database.
  2. A DataSet can be synchronised with a RecordSet.
  3. A DataSet can be converted to XML.
  4. You can infer the schema from a DataSet.
13) In Object Oriented Programming, how would you describe encapsulation?
  1. The conversion of one type of object to another.
  2. The runtime resolution of method calls.
  3. The exposition of data.
  4. The separation of interface and implementation.

Saturday, July 15, 2017

Agile Scrum FAQ


How is Scrum different from Waterfall model?

The major differences are:

1. The feedback from customer is received at an early stage in Scrum than in Waterfall, where the feedback from customer is received towards the end of development cycle.

2. To accommodate the new or changed requirement in scrum is easier than Waterfall.

3. Scrum focuses on collaborative development then Waterfall where the entire development cycle is divided into phases

4. At any point of time, we can rollback the changes in Scrum than in Waterfall

5. Test is considered as phase in Waterfall unlike Scrum

How is Scrum different from Iterative model?

Scrum is Iterative + Incremental model

Do you know any other methodology apart from Scrum?

Other Agile methodologies include, KanBan, XP, Lean

What are ceremonies you perform in Scrum?

There are three major ceremonies performed in Scrum:

1. Planning Meeting - Entire Scrum Team along with the Scrum Master and Product Owner meets and discuss each item from the product backlog  that they can work on the sprint. When is story is estimated and is well understood by the team, the story then moves into the Sprint Backlog.

2. Review Meeting - Where the Scrum Team demonstrates their work done to the stake holders

3. Retrospective Meeting - Scrum Team, Scrum Master and Product Owner meets and retrospect the last sprint worked on. They majorly discuss 3 things:

  • What went well?
  • What could be done better?
  • Action items 

Apart from these three ceremonies, there is one more "Backlog Grooming" meeting in which the Product Owner puts forward business requirements as per the priority. Team discusses over it, identifies the complexity, dependencies and efforts. The team may also do the story pointing at this stage

Three Amigos in Scrum?

Three Amigos are - The Product Owner, The Scrum Master and The Scrum Team

What should be the ideal size of Scrum Team?

Ideal size is 7 with +/-2

What do you discuss in daily stand-up meeting?

  • What did you do yesterday?
  • Planning for today
  • Any impediments/roadblocks
What is "time boxing" of a scrum process called?

It's called "Sprint"

What should be ideal sprint duration?

It should be 2-4 weeks 

How requirements are defined in Scrum?

Requirements are termed as "User Stories" in Scrum

What are the different artifacts in Scrum?

These are two artifacts maintained in Scrum:

1. Product Backlog - Contains the prioritized list of business requirements 

2. Sprint Backlog - Contains user stories to be done by the scrum team for a sprint

3. Velocity Chart

4. Burn-down Chart

How do you define a user story?

The user stories are defined as

As a <user / type of user>
I want to <action / feature to implement>
So that <objective>

What are the roles of Scrum Master and Product Owner?

Scrum Master - Leader for the Scrum team. Presides over all Scrum ceremonies and coaches team to understand and implement Scrum values.

Product Owner - Point of contact for Scrum team 

How do you measure the work done in Sprint?

Its measured in velocity

What is velocity?

Sum of story points that a Scrum team completed over a sprint

Who is responsible for deliverable? Scrum Master or Product Owner?

Neither the Scrum Master, nor the Product Owner. Its responsibility of the Team

How do you measure the complexity or effort in a sprint? Is there a way to determine and represent it?

Through “Story Points”. In scrum it’s recommended to use Fibonacci series to represent it.

How do you track your progress in a sprint?

The progress is tracked by a “Burn-Down chart”.

How do you create the burn down chart?

Burn down chart is a graph which shows the estimated v/s actual effort of the scrum tasks.
It is a tracking mechanism by which for a particular sprint; day to day tasks are tracked to check whether the stories are progressing towards the completion of the committed story points or not. Here we should remember that the efforts are measured in terms of user stories and not hours.

What do you do in a sprint review and retrospective?

During Sprint review we walkthrough and demonstrate the feature or story implemented by the scrum team to the stake holders.

During retrospective, we try to identify in a collaborative way what went well, what could be done better and action items to have continuous improvement.

Do you see any disadvantage of using scrum?

I don’t see any disadvantage of using scrum. The problems mainly arises when the scrum team do not either understand the values and principles of scrum or are not flexible enough to change. Before we deciding on scrum, we must first try to answer the

Do you think scrum can be implemented in all the software development process?

Scrum is used mainly for
  • complex kind of project
  • Projects which have early and strict deadlines.
  • When we are developing any software from scratch.
During review, suppose the product owner or stakeholder does not agree to the feature you implemented what would you do?

First thing we will not mark the story as done.
We will first confirm the actual requirement from the stakeholder and update the user story and put it into backlog. Based on the priority, we would be pulling the story in next sprint.

In case, the scrum master is not available, would you still conduct the daily stand up meeting?

Yes, we can very well go ahead and do our daily stand up meeting.

Where does automation fit into scrum?

Automation plays a vital role in Scrum. In order to have continuous feedback and ensure a quality deliverable we should try to implement TDD, BDD and ATDD approach during our development. Automation in scrum is not only related to testing but it is for all aspect of software development. As I said before introducing TDD, BDD and ATDD will speed up our development process along with maintaining the quality standards; automating the build and deployment process will also speed up the feature availability in different environment – QA to production. As far as testing is concerned, regression testing should be the one that will have most attention. With progress of every sprint, the regression suit keeps on increasing and it becomes practically very challenging to execute the regression suit manually for every sprint. Because we have the sprint duration of 2 – 4 weeks, automating it would be imperial.

Apart from planning, review and retrospective, do you know any other ceremony in scrum?

We have the Product backlog refinement meeting (backlog grooming meeting) where the team, scrum master and product owner meets to understand the business requirements, splits it into user stories, and estimating it.

Can you give an example of where scrum cannot be implemented? In that case what do you suggest?

Scrum can be implemented in all kinds of projects. It is not only applicable to software but is also implemented successfully in mechanical and engineering projects.

Tell me one big advantage of using scrum?

The major advantage which I feel is – Early feedback and producing the Minimal Viable Product to the stakeholders.

What is DoD? How is this achieved?

DoD stands for Definition of done. It is achieved when
  • the story is development complete,
  • QA complete,
  • The story meets and satisfy the acceptance criteria
  • regression around the story is complete
  • The feature is eligible to be shipped / deployed in production.
What is MVP in scrum?

A Minimum Viable Product is a product which has just the bare minimum required feature which can be demonstrated to the stakeholders and is eligible to be shipped to production.

What are Epics?

Epics are equivocal user stories or we can say these are the user stories which are not defined and are kept for future sprints.

How do you calculate a story point?

A Story point is calculated by taking into the consideration the development effort+ testing effort + resolving dependencies and other factors that would require to complete a story.

Is it possible that you come across different story point for development and testing efforts? In that case how do you resolve this conflict?

Yes, this is a very common scenario. There may be a chance that the story point given by the development team is, say 3 but the tester gives it 5. In that case both the developer and tester have to justify their story point, have discussion in the meeting and collaborate to conclude a common story point.

You are in the middle of a sprint and suddenly the product owner comes with a new requirement, what will you do?

In ideal case, the requirement becomes a story and moves to the backlog. Then based on the priority, team can take it up in the next sprint. But if the priority of the requirement is really high, then the team will have to accommodate it in the sprint but it has to very well communicated to the stakeholder that incorporating a story in the middle of the sprint may result in spilling over few stories to the next sprint.

In case you receive a story at the last day of the sprint to test and you find there are defects, what will you do? Will you mark the story to done?


A story is done only when it is development complete + QA complete + acceptance criteria is met + it is eligible to be shipped into production. In this case if there are defects, the story is partially done and not completely done, so I will spill it over to next sprint.