Skip to main content

Posts

Showing posts from 2021

Angular - How to create custom form controls

Greetings! If you are working in an Angular project, you surely have created many UI components. We can easily use @Input, @Output to communicate data between parent to child and child to parent. However, we are unable to bind those values directly to angular forms. But, do we realy need to do it that way? Yes! we need, utilizing the form modules is more powerful way to get user input. Then, can't we use our 'normal' components to do the job? No! we can't. I was ashamed to know that I didn't know the existence of the ControlValueAccessor but better late than never ;) Complete code  custom-form-control What is ControlValueAccessor? When you are working with forms in Angular, whether it is template driven or reactive form, NgModel, formControl, formControlName, Angular creates FormControl to track the value, validations etc. Then Angular should have a way to communicate data between actual html element and the FormControl. Angular is smarter enough not to create one t...

Case Study - How to handle concurrent reservation

Greetings! There are multiple domains with reservation build into it, however the problem they face is same. How do you handle when concurrent users try to reserve the same resource? We can see this situation in systems like; Doctor appointment Airline ticketing Movie ticketing Hotel booking Train ticket many more... Depending on how you define the business this again has two paths. Reserve the same resource - exact time slot for a doctor appointment. Reserve with count - 10 patients for a doctor for given timeslot with an appointment number. Let's understand the problem again You are going to watch the latest hit movie. While you are on your way, someone faster than you passed you. Then both of you joined the queue. Unfortunately for you, the person before you got the last available ticket hence you missed the chance to watch the movie at that time. Now imagine there is a fraud happen. Somehow, someone has the same ticket as you have. Sure...

Case Study - URL Shortener

Greetings! There are URL shortning services like https://tinyurl.com/ , https://bitly.com/ for the obvious reason. Shorten the URL to save space! Be it a twitter message, an email, your resume, it is a handy way to give your valuable URL to others. Let's study the underline techniques together. It looks really simple piece of software at first glance, and it is. The real implementation doesn't look that scary. However, overall architecture give us a whole set of ideas. Related articles https://www.slmanju.com/2021/07/design-unique-sequence-with-mongodb.html https://www.slmanju.com/2021/07/basebase62-encoding-with-java.html What does it do? Any URL shortner will have 2 main features. Give a short URL for any given URL. Redirect to the original URL when we enter the shorten URL in a browser. Just 2 features and what is there to talk? That is the interesting part of this. It touches wide range of architecture decisions when we really implement. I personaly haven't experience...

Angular NgRx: A Simple Effect

Greetings! In this fourth installment of our simple NgRx example series we are going to have a look at effects. Yet again, our example will be very simple. This is the complete example https://github.com/slmanju/ngrx-at-slmanju/tree/main/ngrx-hello-effects What we need Store with initial state Create action to add, remove http status codes Create reducers act upon actions Create selector to read from store Create an effect to store http status url Register the reducer Register the effect Generate the Project ng new ngrx-hello-effects --routing=false --style=css cd ngrx-hello-effects/ ng add @ngrx/store@latest ng add @ngrx/effects@latest ng serve Create the Store At this point i'll asume that you have atleast little idea about the action, reducer and selectors. Hence i'll just add the code. One change i'm doing here to previous examples is I have created separate files. ngrx-hello-effects/src/app/store/app.state.ts export interface HttpCodeState...

Angular NgRx: A Simple Selector

Greetings! In this third installment of our simple NgRx series we are going to have a look at selectors. As this is again confusing at first, let's use our simple message string to learn this. For the simplicity, i'm not using any actions in this example. Comple code can is here  https://github.com/slmanju/ngrx-at-slmanju/tree/main/ngrx-hello-selector What we need Store initial value Create reducer to get initial value Register the reducer Create selector(s) Read, change values from the component Generate the Project ng new ngrx-hello-selector --routing=false --style=css cd ngrx-hello-selector/ ng add @ngrx/store@latest ng serve Register the Reducer As in our first article, we will just store a string value in our store. Then register the reducer to read it. If you haven't read it, here is the code. ngrx-hello-selector/src/app/app.reducer.ts const initialState = 'Whatever you are, be a good one.'; const _messageReducer = createReducer( ini...

Angular NgRx: A Simple Action

Greetings! This is our second article on our simple NgRx series. As we saw how to read stored value from the Store, let's see how we can change the value using Actions in this article. Yet again, this will be another simple working example. Full working example https://github.com/slmanju/ngrx-at-slmanju/blob/main/ngrx-hello-action "Red Light, Green Light" ;) What we need Store initial value Define actions to change it Create reducers to react on the action changes Register the reducer Read, change values Generate the Project ng new ngrx-hello-action --routing=false --style=css cd ngrx-hello-action/ ng add @ngrx/store@latest ng serve As this is to demonstrate, we will add Store realted code in a single file. Initial Value In this example, we will store color value and change it. export const initialState: string = 'red'; Create Action Let us create our red and green actions. export const red = createAction('[Color] Red'); export ...

Angular NgRx: The Most Simplest Store

Greetings! When learning Angular, one of the difficulties we face (including myself) is understanding NgRx. In theory, it is so simple. However, difficulty is in implementation. I don't want to add lengthy explanations (documentation has better explanation anyway) but want to add simplest working examples incrementatly so that anyone in any level can understand. As usual, here is the code https://github.com/slmanju/ngrx-at-slmanju/tree/main/ngrx-hello-store Let's create the most simplest store then :). A simple value stored in the store!!! What we need Store with initial value A reducer A component to read the value Yes, no action, no effects as this example is so simple. Generate the Project ng new ngrx-hello-store --routing=false --style=css cd ngrx-hello-store/ ng add @ngrx/store@latest ng serve Initiate the Reducer We will store a simple message in our store. ngrx-hello-store/src/app/hello.reducer.ts import { Action, createReducer } from '@...

Design a unique sequence with MongoDB

Greetings! If you have used RDBMS like MySQL or Oracle you know that those databases support auto-increment fields or sequences. However MongoDB's way of ID is using an ObjectId which is a large string. However if you want an unique sequence what will you do? One solution is of cause to use RDBMS solution like Oracle. Unlike NoSQL solutions, RDBMS have problems with scaling. Let's imagine that to overcome scaling problems we are using MongoDB. Why do we need a unique sequence? We will need unique sequences for several reasons. Design a hit counter. Short string generation (https://www.slmanju.com/2021/07/basebase62-encoding-with-java.html). Rate limiting. Easy to read identifier value. You are migrating from relational database. Eventhough MongoDB doesn't offer this feature out of box, we can implement it using it's atomic operations. The trick is to create a collection with desired name as the _id and findAndModify with $inc. db.counters.insert({ _id: "my-se...

Base/Base62 encoding with Java

Greetings! Converting base 10 number to another base is a common mathematical operation. First of all, why do we need base62? Shorten a given URL Saving a file using timestamp Short text As the base62 has lot more characters, we can easily create a small version of a given number. Let's do the Math Converting to another base has common steps. ( base-10-to-other-bases ) Divide the number by the base and get the remainder. Divide the quotient and get the remainder. Continue this process untill the quotient is zero. Order the remainders from last to first. We can try this process for hexa-decimal. As hexa-decimal is 16 chars, we need a way to represent that value. For that 0123456789ABCDEF are used. 42 42 / 16 = remainder 10, quotient 2 2 / 16 = remainder 2, quotient 0 Since 10 is A in hexa representation 42 = 2A in hexa-decimal number system. This same logic is applied for Base62. We can use 0-9A-Za-z characters to encoe base62. 0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopq...

Batch processing with Iterator pattern

 Greetings! While peeping on a pull request I came across this 60+ lines long complex looking code. Intention of the code was to fetch data from the legacy database as batches. Source code -  Iterator Pattern   In brief, idea was like this, while there_are_more_records fetch next batch do any processing handle exceptions calculate next batches calculate is there another iteration Though lines count has been reduced by creating private methods later, this has multpiple problems. Doing multiple things in this method. Looks too complex. Difficult to unit tests. Unit tests will not be that much valid. Hard to maintain. Error prone. Cannot resuse the logics. Unfortunately, people think doing this kind of complex codes are the good work. A better code will treated like an easy work. Anyway, we can do better with an Iterator. As Java's collection framework uses this heavily, most of the time, people don't use this pattern as they don't know they can use I...

Why you should not use field injection

 Greetings! While doing code reviews, I usually come across DI framework (ex: Spring) managed beans with no constructor. I myself have done this many times (and still for POCs). What you can see in these classes is, fields are annotated with @Autowired, @Resource, @Inject, etc. How do they write unit tests then? They will for example use @InjectMocks using mock framework. As I am not a fan of this approach I ask the reasons why are you creating classes like this and use constructors. However, many will not agree with me giving these kinds of reasons. Reasons to use field injection We are using a DI framework (Spring), do not need to worry about this. The unit testing framework we use support field mocking (InjectMocks). We can use reflection in unit tests. Different developers have different practices, you need to accept that fact and respect them. This is how the previous developer coded. This is how our internal framework use. I'm senior than you, do as I say :P. While those can ...

How I achieved CKAD

 Greetings! I finally became a Certified Kubernetes Application Developer aka CKAD offered by the Cloud Native Computing Foundation (CNCF), in collaboration with The Linux Foundation. I would like to share my experience with few tips with you. I do not use, do not have a chance to use Kubernetes in my daily work. Not only Kubernetes, I do not have real world experience in Docker as well. So it is a hard journey. Exam details I don't want to repeat it here. You can read it here  https://www.cncf.io/certification/ckad/ . This exam is not something you learn and remember things and answer the questions. You have to perform labs in live environment. You have to fight with the time and that is the most difficult part.  Even if you remember, know everything you can't pass!!! This is why everyone says practice! practice! practice! There are discount coupons. Use them to buy the voucher. Recommended materials Learning depends on your character. Some people like to read do...