Once upon a time, a junior engineer at his first job
Everything started with my first professional job.
I was a junior software engineer, the least experienced on the team. I had just finished reading The Clean Code. And I wanted to rewrite all the code I had worked with.
I had a lot to share with my colleagues about coding. But I was the new guy. So I came up with “Daily Tips.” It was a weekly email with a single tip about writing better code.
Those tips came from what I had seen in the book and in the code I worked with. For example, use boolean variables instead of integers for flags. I started to accumulate some of these tips on my personal computer.
A few years later, those tips ended up in my presentations for newcomers at my next job.
The first post
The real starting point was a few years later in my second job.
After getting tired of writing log statements to chase down bugs, I went to the Internet to see what was out there. There must be a better way!–I thought.
I found Fody, a solution using Aspect-Oriented Programming. I put up a proof of concept and showed it to my team lead. Unfortunately, we ended up doing something else. But I had my findings. And I didn’t want to lose that time and that how-to behind an unread email. My blog and its first post were born.
Next posts
After that, from time to time, I started to share my learning and my experiences.
I started to write about the bugs that literally gave me headaches, the resources I used to learn languages and frameworks, and the notes from the books I read. And here you are, 30 posts after that first post.
Your turn
You don’t need to wait to be a well-known figure in the tech field to have a blog.
A blog is a means to share your learning. To learn in public. To share your insights. To show your work. That will make your blog unique.
I don’t have anything to write about?–you said. Have you learned something new? Share that. Share the resources you used to learn it.
Probably, next time you’re Googling something, you will find your own blog posts.
Scott Young describes in Ultralearning the strategy behind his own learning challenges, like “MIT Challenge in 1 year” and “A year without English.” Let’s learn what Ultralearning is all about. These are my takeaways.
Ultralearning is a self-directed and intense strategy to learn any subject. Ultralearning projects help to advance careers or excel at a particular subject. Ultralearning is a perfect alternative to traditional learning methods.
1. Before starting
Before starting an ultralearning project, answer why, what, and how you are going to ultralearn.
Why?
First, identify why you’re learning a subject and the effect you want to achieve. Are you learning the subject to get a specific result? Are you driven only by curiosity?
For example, are you learning to code to get a promotion? Or do you want to learn a new language to go on a trip? Those are two different motivations.
What?
Next, determine the concepts, facts, and procedures you need to learn.
A concept is something you need to understand instead of memorizing
A fact is something you need to memorize. Facts are useful only if you can recall them later
A procedure is something you need to practice
For example, learning vocabulary and expressions are facts when learning a foreign language. But pronunciation is procedural.
How?
After answering Why and What, select your resources. Spend about 10% of your learning time doing research. Use this research time to find how people are learning that subject.
Look for syllabi of courses, textbooks, boot camps, and experts in that field. Filter what won’t help you to achieve your goal.
Learning should be in the context where those skills will be applied. It’s doing the thing you want to get good at where most of the learning happens. For example, solve problem sets instead of watching lectures and learn a language through conversations instead of vocabulary lists.
Try project-based learning and immerse learning. For example, learn how to create a website in a month or go on a trip to learn a new language.
Prefer short study sessions
Spread shorter study sessions over a long period. Find a balance between long study sessions on a single topic and shorter sessions on different subjects. It’s better to have shorter sessions, between 15 minutes and an hour.
If you find yourself procrastinating, follow the 5-minute rule: start and sustain for 5 minutes. Also, you can try the Pomodoro technique: spread 25-minute practice sessions between 5-minute breaks.
Identify the bottleneck components in your learning. Separate your skill into sub-skills. And practice each sub-skill. Imagine a musician who practices tricky parts of a piece in isolation and then practices everything.
Recall instead of concept mapping
Recalling is better than concept maps and passive note reviewing. Recall concepts and facts. Your memory is a leaky bucket. Try space-repetition software or flashcards. After watching a lecture, write all you can remember. When practicing, avoid using your resources.
Voilà! Those are my takeaways from the Ultralearning book. It changed how I approach learning. Instead of overloading my brain with information, I start by creating a plan and list of learning resources.
Do you want to learn a new programming language but don’t know what language to choose? Have you heard about Go? Well, let’s learn Go in 30 days!
From its official page, Go is “an open source programming language that makes it easy to build simple, reliable, and efficient software”.
Go is a popular language. According to Stack Overflow Developer Survey, since 2020, Go is in the top 10 of most admired/desired languages and in the top 15 of the most popular languages.
Go reduces the complexity of writing concurrent software.
Go uses the concept of channels and goroutines. These two constructs allow us to have a “queue” and “two threads” to write to and read from it, out-of-the-box.
In other languages, we would need error-prone code to achieve similar results. Threads, locks, semaphores, etc, …
To learn a new programming language, library or framework, stop passively reading tutorials and copy-pasting code you find online.
Instead, follow these two principles:
1. Learn something by doing. This is one of the takeaways from the book Pragmatic Thinking and Learning. Instead of watching videos or skimming books, recreate examples and build mini-projects.
2. Don’t Copy and Paste. Instead of copy-pasting, read the sample code, “cover” it and reproduce it without looking at it. If you get stuck, search online instead of going back to the sample. For exercises, read the instructions and try to solve them by yourself. Then, check your solution.
“Instead of dissecting a frog, build one”.
― Andy Hunt, Pragmatic Thinking and Learning
Resources
Before starting to build something with Go, we can have a general overview of the language with the Pluralsight course Go Big Picture.
To grasp the main concepts, we can follow Learn Go with tests. It teaches Go using the concept of Test-Driven Development (TDD). Red, green, and refactor.
Go was designed to reduce the clutter and complexity of other languages. Go syntax is like C. Go is like C on asteroids. Goodbye, C pointers! Go doesn’t include common features in other languages like inheritance or exceptions. Yes, Go doesn’t have exceptions.
However, Go is batteries-included. You have a testing and benchmarking library, a formatter, and a race-condition detector. Coming from C#, you can still miss assertions like the ones from NUnit or XUnit.
Aren’t you curious about a language without exceptions? Happy Go time!
You can find my own 30-day journey following the resources from this post in LetsGo
Let’s say we have a SlowService that calls a microservice and we need to speed it up. Let’s see how to add a caching layer to a service using ASP.NET Core 6.0.
A cache is a storage layer used to speed up future requests. Reading from a cache is faster than computing data or retrieving it from an external source on every request. ASP.NET Core has built-in abstractions for a caching layer using memory and Redis.
1. In-Memory cache
Let’s start with an ASP.NET Core 6.0 API project with a controller that uses our SlowService class.
First, let’s install the Microsoft.Extensions.Caching.Memory NuGet package. Then, let’s register the in-memory cache using the AddMemoryCache() method.
Since memory isn’t infinite, we need to limit the number of items stored in the cache. Let’s use SizeLimit. It sets the number of “slots” or “places” the cache can hold. Also, we need to tell how many “places” a cache entry takes when stored. More on that later!
Decorate a service to add caching
Next, let’s use the decorator pattern to add caching to the existing SlowService without modifying it.
To do that, let’s create a new CachedSlowService. It should inherit from the same interface as SlowService. That’s the trick!
The CachedSlowService needs a constructor receiving IMemoryCache and ISlowService. This last parameter will hold a reference to the existing SlowService.
Then, inside the decorator, we will call the existing service if we don’t have a cached value.
Let’s always use expiration times when caching items.
Let’s choose between sliding and absolute expiration times:
SlidingExpiration resets the expiration time every time an entry is used before it expires.
AbsoluteExpirationRelativeToNow expires an entry after a fixed time, no matter how many times it’s been used.
If we use both, the entry expires when the first of the two times expire
If parents used SlidingExpiration, kids would never stop watching Netflix or using smartphones! Photo by Sigmund on Unsplash
Let’s always add a size to each cache entry. This Size tells how many “places” from SizeLimit an entry takes.
When the SizeLimit value is reached, the cache won’t store new entries until some expire.
Now that we know about expiring entries, let’s create the GetOrSetValueAsync() extension method. It checks first if a key is in the cache. Otherwise, it uses a factory method to compute and store a value into the cache. This method receives a custom MemoryCacheEntryOptions to overwrite the default values.
publicstaticclassMemoryCacheExtensions{// Make sure to adjust these values to suit your own defaults...publicstaticreadonlyMemoryCacheEntryOptionsDefaultMemoryCacheEntryOptions=newMemoryCacheEntryOptions{AbsoluteExpirationRelativeToNow=TimeSpan.FromSeconds(60),// ^^^^^SlidingExpiration=TimeSpan.FromSeconds(10),// ^^^^^Size=1// ^^^^^};publicstaticasyncTask<TObject>GetOrSetValueAsync<TObject>(thisIMemoryCachecache,stringkey,Func<Task<TObject>>factory,MemoryCacheEntryOptionsoptions=null)whereTObject:class{if(cache.TryGetValue(key,outobjectvalue)){returnvalueasTObject;}varresult=awaitfactory();options??=DefaultMemoryCacheEntryOptions;cache.Set(key,result,options);returnresult;}}
Register a decorated service
To start using the new CachedSlowService, let’s register it into the dependency container.
Let’s register the existing SlowService and the new decorated service,
A distributed cache layer lives in a separate server. We aren’t limited to the memory of our application server.
A distributed cache is helpful when we share our cache server among many applications or our application runs behind a load balancer.
Redis and ASP.NET Core
Redis is “an open source (BSD licensed), in-memory data structure store, used as a database, cache, and message broker.” ASP.NET Core supports distributed caching with Redis.
Using a distributed cache with Redis is like using the in-memory implementation. We need the Microsoft.Extensions.Caching.StackExchangeRedis NuGet package and the AddStackExchangeRedisCache() method.
Now our CachedSlowService should depend on IDistributedCache instead of IMemoryCache.
Also we need a Redis connection string and an optional InstanceName. With an InstanceName, we group cache entries with a prefix.
Let’s register a distributed cache with Redis like this,
varbuilder=WebApplication.CreateBuilder(args);builder.Services.AddControllers();builder.Services.AddTransient<SlowService>();builder.Services.AddTransient<ISlowService>(provider=>{varcache=provider.GetRequiredService<IDistributedCache>();// ^^^^^varslowService=provider.GetRequiredService<SlowService>();returnnewCachedSlowService(cache,SlowService);// ^^^^^});builder.Services.AddStackExchangeRedisCache(options=>// ^^^^^{options.Configuration="localhost";// ^^^^^// I know, I know! We should put it in an appsettings.json// file instead.varassemblyName=Assembly.GetExecutingAssembly().GetName();options.InstanceName=assemblyName.Name;// ^^^^^});varapp=builder.Build();app.MapControllers();app.Run();
It’s a good idea to read our Redis connection string from a configuration file instead of hardcoding one.
In previous versions of ASP.NET Core, we also had the Microsoft.Extensions.Caching.Redis NuGet package. It’s deprecated. It uses an older version of the StackExchange.Redis client.
Redecorate a service
Let’s change our CachedSlowService to use IDistributedCache instead of IMemoryCache,
Now let’s create a new GetOrSetValueAsync() extension method to use IDistributedCache instead.
This time, we need the GetStringAsync() and SetStringAsync() methods. Also, we need a serializer to cache objects. Let’s use Newtonsoft.Json.
publicstaticclassDistributedCacheExtensions{publicstaticreadonlyDistributedCacheEntryOptionsDefaultDistributedCacheEntryOptions=newDistributedCacheEntryOptions{AbsoluteExpirationRelativeToNow=TimeSpan.FromSeconds(60),// ^^^^^SlidingExpiration=TimeSpan.FromSeconds(10),// ^^^^^// We don't need Size here anymore...};publicstaticasyncTask<TObject>GetOrSetValueAsync<TObject>(thisIDistributedCachecache,stringkey,Func<Task<TObject>>factory,DistributedCacheEntryOptionsoptions=null)whereTObject:class{varresult=awaitcache.GetValueAsync<TObject>(key);if(result!=null){returnresult;}result=awaitfactory();awaitcache.SetValueAsync(key,result,options);returnresult;}privatestaticasyncTask<TObject>GetValueAsync<TObject>(thisIDistributedCachecache,stringkey)whereTObject:class{vardata=awaitcache.GetStringAsync(key);if(data==null){returndefault;}returnJsonConvert.DeserializeObject<TObject>(data);}privatestaticasyncTaskSetValueAsync<TObject>(thisIDistributedCachecache,stringkey,TObjectvalue,DistributedCacheEntryOptionsoptions=null)whereTObject:class{vardata=JsonConvert.SerializeObject(value);awaitcache.SetStringAsync(key,data,options??DefaultDistributedCacheEntryOptions);}}
With IDistributedCache, we don’t need sizes in the DistributedCacheEntryOptions when caching entries.
Unit Test a decorated service
For unit testing, let’s use MemoryDistributedCache, an in-memory implementation of IDistributedCache. This way, we don’t need a Redis server in our unit tests.
Let’s replace the MemoryCache dependency with the MemoryDistributedCache like this,
With this change, our unit test now looks like this,
[TestClass]publicclassCachedSlowServiceTests{[TestMethod]publicasyncTaskDoSomethingSlowlyAsync_ByDefault_UsesCachedValues(){varcacheOptions=Options.Create(newMemoryDistributedCacheOptions());varmemoryCache=newMemoryDistributedCache(cacheOptions);// ^^^^^// This time, we're using an in-memory implementation// of IDistributedCachevarfakeSlowService=newMock<ISlowService>();fakeSlowService.Setup(t=>t.DoSomethingSlowlyAsync(It.IsAny<int>())).ReturnsAsync(newSomething());varservice=newCachedSlowService(memoryCache,fakeSlowService.Object);// ^^^^^varsomeId=1;awaitservice.DoSomethingSlowlyAsync(someId);awaitservice.DoSomethingSlowlyAsync(someId);// Yeap! Twice again!fakeSlowService.Verify(t=>t.DoSomethingSlowlyAsync(someId),Times.Once);}}
We don’t need that many changes to migrate from the in-memory to the Redis implementation.
Conclusion
Voilà! That’s how we cache the results of a slow service using an in-memory and a distributed cache with ASP.NET Core 6.0. Additionally, we can turn on or off the caching layer with a toggle in our appsettings.json file to create a decorated or raw service.
The Clean Coder is the second book on the Clean Code trilogy. It should be a mandatory reading for any professional programmer. These are my main takeaways.
The Clean Coder isn’t about programming in itself. It’s about the professional practice of programming. It covers from what is professionalism to testing strategies, pressure and time management.
Professionalism
Your career is your responsibility, not your employer’s
Professionalism is all about taking responsibility.
Do not harm: Do not release code, you aren’t certain about. If QA or an user finds a bug, you should be surprised. Make sure to take steps to prevent it to happen in the future.
Know how it works: Every line of code should be tested. Professional developers test their code.
Know your domain: It’s unprofessional to code your spec without any knowledge of the domain.
Practice: It’s what you do when you aren’t getting paid so you will be paid well.
Be calm and decisive under pressure: Enjoy your career, don’t do it under pressure. Avoid situations that cause stress. For example, commit to deadlines.
Meetings are necessary and costly. It’s unprofessional to attend to so many meetings.
When the meetings get boring, be polite and ask if your presence is still needed.
One of my favorite quotes from the Clean Coder
Say No/Say Yes
Say. Mean. Do
Professionals have courage to say no to their managers. Also, as professional, you don’t have to say yes to everything. But you should find a creative way to make a yes possible.
There is no “trying”. Say no and offer a trade-off. “Try” is taken as yes and outcomes are expected accordingly
You can’t commit to things you don’t control. But, you can commit to some actions. For example, if you need somebody else to finish a dependency, create an interface and meet with the responsible guy.
Raise the flag. If you don’t tell someone you have a problem as soon as possible, you won’t have someone to help you on time.
Saying yes to drop out professionalism is not the way to solve problems.
Coding
It could be consider unprofessional not to use TDD
If you are tired or distracted, do not code. Coding requires concentration. And you will end up rewriting your work.
Be polite! Remember you will be the next one interrupting someone else. Use a failing test to let you know where you were after an interruption.
Debugging time is as expensive as coding time. Reduce your debugging time to almost 0. Use TDD, instead.
When you are late, raise the flag and be honest. It isn’t ok to say up to the end you’re fine and not to deliver your task.
Be honest about finishing your work. The worst attitude is when you say you’re done when you actually aren’t.
Ask for help. It’s unprofessional to remain stuck when there is help available.
Voilà! These are my main points from The Clean Coder. Do you see why I think it should be a mandatory reading? Oh, I missed another thing. An estimate isn’t a date, but a range of dates.