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