C# Delegate

When was the last time you write code using delegate in C#? Hmm do you know what it means? To be honest, I have not used delegate keyword for years. Long time ago, when I wrote I had to google for the syntax. With the evolving of C#, we have not seen it being used in production code. But, it is important, or at least is nice, to know what it is.

Years ago, when I read about it, I did not understand at all. I could not wrap it up in my head. Therefore, I avoided to use it. Maybe because I did not understand the why behind the keyword.

Time flies. I am reading C# fundamentals again. Luckily, with 10 years of experience, I can understand the delegate keyword, not that bad.

Here is the official document from MS Doc. However, I would suggest you to read from Jon Skeet.

Such a definition might cause confusion and hard to understand. One way to understand a new concept is to map it with what we have known. I hope you can have your own mapping.

Let’s explore some examples to understand delegate. Imagine a context where there is a team which has a team leader and some developers. There are some bugs need to fixed in a week. The team leader has the responsibility of leading the team to finish the mission.

The example might confuse you because, well, it is an imaginary context. In the real life, or real project modeling, things are so much complicated. The main point is a playground to write some code with delegate, forget about all new fancy stuffs such as Action, Func, inline method, or expression.

Wire up a very simple .NET Core project using VS Code, here the first version I got (after some failing builds with first time using VS Code on Mac)

using System;
using System.Collections.Generic;
namespace funApp
{
    
    delegate void KillBug(Bug bug);
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello Team Leader");
            var tl = new TeamLeader();
            tl.StartSprint(new List<Bug>{
                new Bug("Fix homepage layout"),
                new Bug("Timeout exception when searching")
            });
            tl.RunSprint(new KillBug(SayBugName));
            
            Console.Read();
        }
        private static void SayBugName(Bug bug)
        {
            Console.WriteLine($"Hi {bug.Name}, how are you today?");
        }
        
    }
    class TeamLeader
    {
        private IList<Bug> _bugs = new List<Bug>();
        public void StartSprint(IList<Bug> bugsFromBacklog)
        {
            foreach (var bug in bugsFromBacklog)
            {
                _bugs.Add(bug);
            }
        }
        public void RunSprint(KillBug knowHowToKillBug)
        {
            foreach (var bug in _bugs)
            {
                knowHowToKillBug(bug);
            }
        }
    }
    class Bug
    {
        public string Name { get; set; }
        
        public Bug(string name)
        {
            Name = name;
        }
    }
}

It works.

The example demonstrates a very important concept in programming: Separation of Concern. Looking at the RunSprint method for a moment. A team leader usually does not know how to kill a bug, I know many team leaders are great developers, but they cannot kill all bugs themselves. They usually use ones who know how to kill a bug, which is usually a developer in his/her team. Or he can outsource to others, as far as they know how to kill a bug. That “know how to kill a bug” is modeled via a delegate “KillBug”.

In later version of C# (2, 3,..) and .NET, there are more options to rewrite the code to get rid of KillBug delegate declaration. But the concept remains.

       public void RunSprint(Action<Bug> knowHowToKillBug)
        {
            foreach (var bug in _bugs)
            {
                knowHowToKillBug(bug);
            }
        }

That method will produce the same outcome.

Do I need to know delegate to write C# code, to finish my job? No. You don’t.

Do I need to understand it? Yes. You should. Understanding the why behind the delegate concept is very important to make a proper design. Every feature has a good reason. We, developers, must understand that reason to make the best use.

C# Sharpen Your Sword

Do you know C#? Yes. I do. How long have you been using it? 4-5 years. I am an experienced C# developer, sir.

While interviewing candidates for C# developer position, I came across many CV with saying kind of the same thing. Candidates claim that they are experienced C# developers. I am sure they are. Many of them are. But, unfortunately, there are some who misunderstood themselves.

Why was that? Regardless of C# evolution, they kept writing the same code as if it was C# 1.0. Many just use C# to write basic code such as class, if statement. They use basic data types not even care or know that there are better versions of data structures that can do a better job.

Many experienced developers have problems with writing code that access database, manipulate XML, read files, … The forever argument is they will google when they need it. Ok, that makes sense. Oh no! experienced developers ask google for basic operations?? Hmm that does not make any sense at all.

One day I realized that I am a C# developer, too (Just kidding I know I am a C# developer, writing C# code for a living). I started to ask myself

How much do I know about C#?

I know some. That’s all I can admit. With the thinking flow, I thought many C# developers have that problem; they are not aware of how much they know about C#.

I decided to compose a list of fundamental that every developer should know about C#. Not everyone uses all of them in their daily job.

There are 2 purposes when I composed the list

  1. Self-improvement: I want to improve my C# skill regardless of where I am now. I want to have a strong foundation.
  2. Help others: I have developers at my workplace. I want to help whoever accept my help. Remember that helping is growing, a perfect win-win situation.

 

Primitive Data Types and Keywords

What are differences between integer and float data types? between float and double? And when to use what?

The problem: many do not think twice before deciding a data type to use. What primitive data type do you use to hold a person’s age? Probably it is int, right?

What are checked and unchecked keywords used for?

String Manipulation and Regular Expression

Developers deal with string more often than they thought.

  1. Concatenate strings
  2. Format string with Join
  3. Format string with Format
  4. Find string with regular expression
  5. ToString(): when displaying a value (integer, date, currency, …), we convert it to a string.
  6. String and Culture

The regular expression is an exciting, sometimes headache, topic. How many ways are there to check if a string is an integer?

Protection Levels

Hey, do you remember these: Private, Protected, Internal, Protected Internal, and Public?

The problem: Do not know how to take advantages of the language to protect data correctly.

I have seen developers have a habit of using public for methods and properties, private for fields. The public modifier is used because it is the easiest, which allows a function can be consumed everywhere.

When was the last time you think of using Internal, or Protected Internal?

Collections and Concurrent Collections

How many types of collection do you know? And when to use what? List, Queue, Stack, Dictionary, Array, ArrayList, … Oh how about the readonly and concurrent versions?

The problem: Not use the right collection. Usually, developers take the easiest one instead of a proper one.

Using the right collection is very important. Because it will protect the data from unexpected access, unexpected modification.

The most common use is the List<T> class. Because it does not require any thinking process.

To use a proper collection type, at least a developer should consider these questions

  • Is it ordered?
  • Access pattern? FIFO, FILO, Random, by index, by key, …
  • Is it readonly?
  • Do we need to keep it after processing all items?
  • What are the most common operations (business operations) on that collection?

 

Threading, Task, Parallelism, Async and Await

This topic is not easy at all. It is not required that every developer has a deep understanding; however, a fundamental is crucial.

The problem: Use without a bit of understanding how it works. This causes many nasty issues in production.

XML

Sometimes, we forget how to process an XML document. That’s sad. A direct XML processing might not be popular these days. But a proper understanding is important.

File and I/O

The problem: We do not know what we are doing.

When there is a need to read a file, developers use the first API available File.Open with just enough required parameters. Many times, they fail to ask

  1. What is the file encoding?
  2. What if a file is being opened by another process?
  3. What if a file does not exist?
  4. What if a file is too big?
  5. Do we need to load its content at once? or should we process line by line?

Have you ever wondered those questions?

ADO.NET

The rise of ORM tools (EF, NHibernate, …) makes developers’ life easier when dealing with databases. That comes at a cost. Developers seem to forget how to interact with databases.

The problem: Do not know how to work with databases.

When doing interviews, I asked candidates about the SQL transaction in an EF application. They said EF does it all for us. Yes. It does. The next question, when does it commit a transaction? Answer: Oh, EF does it for us. Period.

Lacking the database fundamental is such a bad excuse.

LINQ

It is hard to say whether it is a fundamental thing. It came out with C# 3.0. Before, you can write code with for loop. Proper use of LINQ will improve the readability of your code.

Covariance and Contravariance

Same as LINQ. If you understand them, you are rock.

Dynamic

Not used often, but listed here for reference.

 

Having the list is a first step to sharpen my C# sword. The list works as an agenda, a guiding star. Some of the items I am good at, others I am a beginner.

Stay calm, sit down, put hands on the sword, move it slowly. That’s good! Let’s the game on.

Team Practice – Work

A team is a group of people to accomplish something. That something usually calls Work or Job. In my job, that is building software, fixing bugs, maintaining systems; all sort of stuff related to software development. The common scenario is that we come to the office (or virtual office), pick tasks assigned to us, get them done. Mission Accomplished! So far so good! And if everyone can do just that, it would be a perfect team.

However,

  • The requirement is not clear.
  • The client changes their mind.
  • We do not control clients.
  • We cannot plan. We do not have authority to decide.

Looks like the team does not have control over their job. It is fine to do just fine. What if we can do it better, or make it worth our time when we are working?

We cannot improve what we cannot control

We have control our work; but not by the authority, not by asking for permission, not by making special requests. It might work that way, yet the chance is low. Why? Because those actions depend on other people. You, unconsciously, just move the control over to your boss, your clients, … those whom you cannot control.

I have a few tips to get it back.

  1. Scope – What the team can impact.
  2. Internalized empower – Goal, Inspection, and Adaptation
  3. Protect your coffee

Scope – What the Team Can Impact

If you draw a diagram where the team is in the central, you might come up with something like this

Team Impact Diagram
Team Impact Diagram

If you see a team is a unit, you can easily draw that impact diagram. In those connections, some you can impact, others are out of your reach. Focus on what you can impact. Ignore the rest because not much you can do.

What are your team main areas? What are the factors that decide your team success or failure? You do not need to make a full long list. But you need some, agreed by the team, without approval from anyone.

Internalized Empower – Goal, Inspection, and Adaptation

Your team is doing a good job. We want to improve the team deliveries. Some might seek help from external resources. But I prefer the internal empowerment. By heading toward internal, we have the full control of what, how we want to improve. Asking for help is a good solution, but it must come after the internalized empowerment.

Regardless circumstances, we can start by setting goals for a week. When talking to people, I realize that setting goals is not easy for many. Many struggle with the perfection, focusing too much on how to set a good one. No. Stop doing that. Just pick any thing to get started. What important is the process, not the goal itself. Once you get into the process, it is much easier to define a good goal. It will come naturally. So you should not worry about that.

Inspection! Without inspection, we cannot grow. Inspection helps the team know where they are standing, how far they have gone to accomplish the goal. Inspection can be as simple as asking yourselves questions: Am I moving in the right direction? Is there any potential issues? … Inspection should happen daily basic.

Adaptation! The output of inspection is the input for adaptation. Everyday comes with new information, new challenge. You have to adapt. You have to response to them. Some expect a fixed period without changes. That is so naive. Requirements change. Deadline comes. Oh maybe a team member is on vacation, is sick, … By making Adaptation explicitly, you will deal with the changes better.

The whole thing sounds theoretical and vague. Yes they are. What you should take from here is the keywords Goal, Inspection, and Adaption. Either you start it now, or your team stays the same week by week. A good way to grow is depending on your internal power, not from outside or someone else.

Protect Your Coffee

I asked the kids, ” What would happen if somebody dropped sugar in my coffee?” They said ” you would be ok”. I said “What will happen if somebody drop strychnine in my coffee?” Well you’d be dead”. I said correct.
Lesson one: life is both sugar and strychnine, you got to be careful. I said ” what if my worst enemy drops in the sugar? They said ” you would be OK. I said ” what if my best friend even by accident drops in the strychnine? ” they said ” well you’d be dead. ” I said “correct “.
Lesson two: watch your coffee.
You got to be careful see it doesn’t matter who hands you the bad stuff it doesn’t matter where you get the bad stuff it’ll still do its damage on your bank account wherever you get it. Mr Shoaff gave me one of the greatest phrases when I first met him when he said ” Jim everyday stand guard at the door of your mind”, how important. Stand guard at the door of your mind and you decide what goes into your mental factory don’t let anybody just dump anything they want to in your mental factory because you have got to live with the results.

Jim Rohn

I like that story so much. It does not matter who hands you the bad stuff. It does not matter where you get the bad stuff. The result is the same. You get the consequences.

The team has been working so hard. The result is good. They are reaching the goal. And at the last minutes something bad happens because of a team member, because of managers, … because of … Regardless of “because of”, your goal is affected, your hard work is draining.

We cannot prevent bad things. It is a part of life, of Mother Nature. But we can reduce the impact if we raise our awareness.

 

Everyday we have to think of how to improve the team. Otherwise, a team is simply a group of people. No mission! No direction! I do not like such a team.

Team Practice – People

What we call a team is a group of people. What we call a work is a thing that will be done by people. In IT industry I am in, people build software, not a machine. When we look at a team, there are many roles. Some are developers; some are testers; some are called QA; some are architects and so on. And then we come up with many processes to make those roles worked well together. Sooner or later, we just prefer to team as Roles and Processes. People are eliminated. That’s sad!

I started to step into building a great team by looking at its components in my own eyes. I do not judge anyone or how they run their teams. This is purely my observations and practices.

I started to pay attention to how things work; where they come from. In that quest, I met Simon Sinek where I found inspirational speeches about leadership, about people, about what have been missing these days. Last year, I decided to study SCRUM seriously. There is a match between them: The People — The heart of everything.

Not many people say “I do not care about others“. It does not matter what we say. What we do matters. To get me engaged with the people, I constantly practice asking myself

  1. What have I done to help others?
  2. When was the last time I did?
  3. Do I really mean what I did?
  4. Do I foster the caring environment?

Why do I have to ask myself those questions? Because I really mean it. I do not want to stop at saying that I care about others, in the team context.

Part of the practice is to get others involved. The end goal is not you become a good guy. The end goal is to have a good team where everyone cares each other, brings out the best, and deliver the best. What if every member practices asking those questions?

With the growing of collaborative tools, team members are preferring to chat on tools than talking to each other. The tools are perfect for remote team. But when everyone is sitting at the same office, each can reach others in a matter of tick, is it better if we can talk directly to each other? Yes. They have their own reasons. However, if they might talk a lot when discussing non-work topics.

I do not advocate for right or wrong regarding to the people in the team. There is no silver bullet of how to do it right. However, I do have some suggestions that I believe in, and that I am practicing.

First, a team leader should have the correct mindset when looking at people. He/she should reflect base on these questions

  1. Do I pay attention to helping my teammates?
  2. I might. Oh what was the last time then?
  3. Do I foster a good team spirit? That they help each other.
  4. What is my next step that I can start immediately?

In general there are 3 steps

  1. Recheck your intentions
  2. Reflect your actions in the light of your intentions
  3. Define immediate next doable actions

Second, Team Leader should share it with their team. You cannot do the right thing without honesty first. This is a hard step because of emotional barrier. It is not easy to speak out in the first time, honestly accepted our own faults. Regardless, you have to do it to reach the third step.

Third, foster the team spirit. The reason we are in a team is to help each other to accomplish certain things, usually defined as our job. We are there, team up, to build a software, to deliver a feature. What you have done individually does not much matter. What matter is the delivery of the whole team. A member might be very smart, work fast. He/she might finish his/her tasks quickly. But if he/she just stops there, the whole team still sucks.

To foster that spirit, one can practice

  1. Do I help other teammates?
  2. Oh when was that?
  3. Look after the guys next to you.
  4. Look at the team goals.

We cannot get everyone participated in that at the first time. There will be resistant. But, very important but, there will be some who are willing to change and see it as a good way to work.

 

We spend a major time of our live at work, with people we call coworkers, with people we call teammates. We team up to finish a job, to get things done. To accomplish those, and have fun at those major time spent, we have to start with us first. We are the one who makes a difference. All we need is to bring back our old behavior: Talk to each other and Help each other.

That how I believe it should work. I fight for it.

2017 Retrospective

2017 was finished. It is worth to spend some hours looking back on how I spent the year. The main objectives are what I have done well, what improvements I should do in 2018. I will not look at the past to judge whether it is good or bad. There is no value in that judgment thinking.

First, let’s start with what I started at the beginning of 2017. This facebook timeline reminded me

2017 Keyword: SOW
2017 Keyword: SOW

Back in time, I had no idea what I should sow whatsoever. I just knew that I had to start somewhere. The SOW has been the main theme in my direction so far. I am a strong believer in

You reap what you sow

Right after that, I wrote a post to set my mind clear, so I would not fall into a wish trap. And I started this blog again in 2017.

Let’s start with the blog review.

The Blog

To sow, I need to do things that will benefit others. Blogging is the easiest way to accomplish that. When started, I had all the fear that many have had when writing a blog

  • Fear of bad writing
  • Fear of no reader
  • Fear of someone laughing

Hell! you either step back or move forward. I chose the later.

2017 statistic

  1. 50 posts
  2. 1680 views
  3. Various topics: technical, personal development, leadership, …

I still remember the feeling when I looked at the page views every day, then every week. Not because I wanted to be popular, but because it gave me a special feeling. And that feeling brought me the courage to write more. It is a good loop.

The sowing process in blogging is good. I will keep going. By writing, it both helps me and others, a perfect win-win scenario.

The Mind

I have read 11 books completely, and 7 in progress.

2017 Reading on Goodreads
2017 Reading on Goodreads

Many of them are in English. A few are in Vietnamese. At home, I have my bookshelves. Which allows me to read a couple of books.

Reading is a way of improving my mind, my understanding of life, my understanding of how things work.

On December, I managed to get my PSM 1 Certification.

The Body

I started to play badminton again, not frequently. At the same time, I practice Tai Chi in the morning. I just started on the Tai Chi with a desire to improve my health.

However, I have not fixed my health problems:

  1. My stomach
  2. The endurance

They are the main improvements I will take seriously in 2018. I will write about them soon when the time comes. I have started that process and I am pretty sure that I have found a good solution. I just need the willpower and discipline.

The Work and Accomplishments

2016, I worked 2284 hours. 2017, I worked 2093 hours. I do not aim at working as many hours as possible. Rather, I want to focus on the value per hours. So the reduced amount is a good process. Of course, I have to make sure my income at an acceptable level. Sorry I cannot tell about income in a public blog post.

Accomplishments? There are some. Unfortunately, they are private. I want to keep them for myself.

 

Those are quick reviews of my 2017. By reviewing it this way, I am fully aware of how I spent a year. There is one very important pattern here.

  1. I start something at the beginning of the year
  2. I review at the end
  3. I see the progress

Of course, there are many unexpected things. There are bad things happened. Just accept them. That is how the life runs.

2018 has started. I have my own goals of what I want in this year, of how I want to spend the year.

Officially farewell 2017 from Thai Anh Duc. Thank you for your coming Mr. 2017.