avatarNeeramitra Reddy

Free AI web copilot to create summaries, insights and extended knowledge, download it at here

4376

Abstract

<span class="hljs-keyword">private</span> <span class="hljs-keyword">readonly</span> paymentService: PaymentService, <span class="hljs-keyword">private</span> <span class="hljs-keyword">readonly</span> moderationService: ModerationService </span>) {}

<span class="hljs-keyword">public</span> <span class="hljs-title function_">createPost</span>(<span class="hljs-attr">args</span>: <span class="hljs-title class_">CreatePostArgs</span>): <span class="hljs-title class_">Post</span> { <span class="hljs-keyword">const</span> post = <span class="hljs-variable language_">this</span>.<span class="hljs-property">postRepository</span>.<span class="hljs-title function_">create</span>(args);

<span class="hljs-variable language_">this</span>.<span class="hljs-property">reputationService</span>.<span class="hljs-title function_">increaseReputation</span>(args.<span class="hljs-property">userId</span>);
<span class="hljs-variable language_">this</span>.<span class="hljs-property">notificationService</span>.<span class="hljs-title function_">notifyFollowersAboutPost</span>(post);
<span class="hljs-variable language_">this</span>.<span class="hljs-property">userService</span>.<span class="hljs-title function_">updateUserActivity</span>(<span class="hljs-string">'post.created'</span>, post);
<span class="hljs-variable language_">this</span>.<span class="hljs-property">trackingService</span>.<span class="hljs-title function_">registerTrackable</span>(<span class="hljs-string">'post'</span>, post);
<span class="hljs-variable language_">this</span>.<span class="hljs-property">moderationService</span>.<span class="hljs-title function_">checkPostContentForViolations</span>(post.<span class="hljs-property">content</span>);    

<span class="hljs-keyword">if</span> (args.<span class="hljs-property">isPremium</span>) {
  <span class="hljs-variable language_">this</span>.<span class="hljs-property">paymentService</span>.<span class="hljs-title function_">chargeUserForPremiumPost</span>(args.<span class="hljs-property">userId</span>);
}

<span class="hljs-keyword">return</span> post;

} }</pre></div><p id="154d">This example is obviously made up, so please don’t pay too much attention to the details. I just want you to notice how many services <code>PostService</code> is dependent on and imagine that these services may also be dependent on PostService. For example, the notification service may require additional data from the post service to dispatch notifications, or the <code>ModerationService</code> may need to modify the post again via <code>PostService</code> after moderation. This is where circular dependencies occur.</p><p id="96c0">So now that we have a grasp of the problem, let’s explore the solution that I want to propose.</p><h1 id="c471">The solution</h1><p id="72f0">The solution I want to propose for this problem is to use the well-known concept of Event-Driven Architecture. Instead of calling all subsequent actions from the <code>createPost</code> method, we will simply create the post there and emit an event. Then, any module interested in performing some action related to the event may do so without crossing its logical borders.</p><p id="53d2">NestJS already comes with handy tools that we can use to benefit from events. If you don't yet have the package installed, you can simply add <code>@nestjs/event-emitter</code> to your application.</p><div id="9629"><pre>yarn <span class="hljs-keyword">add</span> @nestjs/<span class="hljs-keyword">event</span>-emitter</pre></div><p id="32cf">And when the package is installed, add the <code>EventEmitterModule</code> to the root module of your application.</p><div id="e0ec"><pre><span class="hljs-keyword">import</span> { Module } <span class="hljs-keyword">from</span> <span class="hljs-string">'@nestjs/common'</span>; <span class="hljs-keyword">import</span> { EventEmitterModule } <span class="hljs-keyword">from</span> <span class="hljs-string">'@nestjs/event-emitter'</span>;

<span class="hljs-meta">@Module(<span class="hljs-params">{ imports: [ EventEmitterModule.forRoot(<span class="hljs-params"></span>), // ... ], }</span>)</span> export <span class="hljs-keyword">class</span> <span class="hljs-title class_">AppModule</span> {}</pre></div><p id="f073">When we have it ready, we may simply ge

Options

t rid of all <code>PostService</code> dependencies and replace them with only one — <code>EventEmitter2</code>. After this, we may also remove subsequent method invocations from the <code>createPost</code> method and instead emit an event with its key and payload. The payload may be defined as a separate interface or class if you wish, but here, for presentation purposes, I will just emit the created post as a payload.</p><div id="86c2"><pre><span class="hljs-keyword">class</span> <span class="hljs-title class_">PostsService</span> { <span class="hljs-title function_">constructor</span>(<span class="hljs-params"><span class="hljs-keyword">private</span> eventEmitter: EventEmitter2</span>) {}

<span class="hljs-keyword">public</span> <span class="hljs-title function_">createPost</span>(<span class="hljs-attr">args</span>: <span class="hljs-title class_">CreatePostArgs</span>): <span class="hljs-title class_">Post</span> { <span class="hljs-keyword">const</span> post = <span class="hljs-variable language_">this</span>.<span class="hljs-property">db</span>.<span class="hljs-property">posts</span>.<span class="hljs-title function_">create</span>({ ... }); <span class="hljs-variable language_">this</span>.<span class="hljs-property">eventEmitter</span>.<span class="hljs-title function_">emit</span>(<span class="hljs-string">'post.created'</span>, post);

<span class="hljs-keyword">return</span> post;

} }</pre></div><p id="a801">The last thing we have to do is to add a listener to the modules that may be interested in this event. For example, in the notification module, we may have a listener as below. In the other modules, the code will be pretty much the same, just other services will be involved in event handling.</p><div id="c0ad"><pre><span class="hljs-keyword">class</span> <span class="hljs-title class_">NotificationsListener</span> { <span class="hljs-title function_">constructor</span>(<span class="hljs-params"> <span class="hljs-keyword">private</span> <span class="hljs-keyword">readonly</span> notificationsService: NotificationsService </span>) {}

<span class="hljs-meta">@OnEvent</span>(<span class="hljs-string">'post.created'</span>) <span class="hljs-title function_">handlePostCreated</span>(<span class="hljs-params">post: Post</span>) { <span class="hljs-variable language_">this</span>.<span class="hljs-property">reputationService</span>.<span class="hljs-title function_">notifyFollowersAboutPost</span>(post); } }</pre></div><p id="9b3f">This way, the <code>NotificationService</code> and <code>PostService</code> are only loosely coupled now. The <code>PostService</code> is no longer dependent on <code>NotificationService</code>. We get rid of circular dependency here, yet we keep the functionality still working — Yay!</p><h1 id="ea7f">Summary</h1><p id="bf46">To sum up, in this article we explored the proposition of introducing events into your application to solve the issue of circular dependencies. This approach helps modules to stay within their borders yet react to actions performed in another module as well. Even though this way may not be applicable to all solutions it definitely may fix the one presented today.</p><p id="c9dc">I want to say thank you to all who read this article. I would love to hear your thoughts about this proposal and your ways of tackling circular dependencies in your applications, so feel free to share.</p><p id="913c">Don’t forget to check out my other articles for more tips and insights. Happy hacking!</p><h1 id="7cf6">Stackademic 🎓</h1><p id="d5c3">Thank you for reading until the end. Before you go:</p><ul><li>Please consider <b>clapping</b> and <b>following</b> the writer! 👏</li><li>Follow us <a href="https://twitter.com/stackademichq"><b>X</b></a><b> | <a href="https://www.linkedin.com/company/stackademic">LinkedIn</a> | <a href="https://www.youtube.com/c/stackademic">YouTube</a> | <a href="https://discord.gg/in-plain-english-709094664682340443">Discord</a></b></li><li>Visit our other platforms: <a href="https://plainenglish.io"><b>In Plain English</b></a><b> | <a href="https://cofeed.app/">CoFeed</a> | <a href="https://venturemagazine.net/">Venture</a> | <a href="https://blog.cubed.run">Cubed</a></b></li><li>More content at <a href="https://stackademic.com"><b>Stackademic.com</b></a></li></ul></article></body>

How I Almost Killed Myself Trying to Lose Fat

And what you can learn from my mistakes.

Photo by Cesar Galeão from Pexels

A couple of years back I was overweight. A fun wager with a friend turned into a serious decision to lose fat and get shredded.

Despite being a regular gym-goer for around 2 years or so, I knew very little about working out and didn’t know jack about dieting.

So I spent the first few days learning about how to lose fat. What I learned in a nutshell was — I had to set up a caloric deficit, track my macros and calories, workout and do cardio.

I learned quite a bit but not enough and as the saying goes,

“Half knowledge is much more dangerous than ignorance.”

I started off with a severe calorie deficit of around 1100 calories — 750 calories through my diet and the rest through exercise.

I started feeling fatigued and my strength plummeted quite a bit in the first few days.

Every time my progress stalled, I would further reduce my food intake and increase my physical activity.

Over time, I developed a sickly pallor, sunken cheeks, deep bags under my eyes, and felt extremely fatigued all day. My appetite had drastically reduced and my sex drive had hit rock bottom.

I felt like a walking zombie overall but assuring myself with the blind affirmation that fat loss is supposed to be hard, I went on.

I still clearly remember how one night, I had gone to bed feeling sure I wouldn’t wake up the next morning.

I had pushed through that day with only my sheer willpower and as night approached, I was blacking out every now and then. I did wake up the next morning or I wouldn’t be here to tell the tale.

Some days, unable to exercise self-restrain anymore, I would binge eat and wallow in guilt later on.

By the end, I was eating less than 1000 calories per day, cycling 10 km thrice a week, and working out in the gym the remaining 4 days.

From 87 kgs to 63 kgs, I had lost 24 kgs in a span of 6 months — a lot of strength and muscle along with the fat.

Standing 6'1'’ tall and weighing only 63 kgs, I looked skinny and almost anorexic as opposed to ripped.

I had developed an unhealthy relationship with food. Being scared of gaining back the weight I had lost, I obsessed over every single calorie.

Overall, I felt miserable, and, eating, and working out felt tormenting.

Looking back, I honestly don’t know how I even stayed alive with such strenuous physical activity and eating in a day as many calories as I eat in a single meal now.

I now weigh around 73 kgs and carry a lot more muscle but only slightly more fat than I did back then.

I’ve learned a lot since then and want to share the mistakes I made so that you can learn from and not commit them. As the saying goes,

“It’s good to learn from your mistakes. It’s better to learn from other’s mistakes”

— Warren Buffett

Photo by Brooke Lark on Unsplash

Mistake #1 — Severely Restricting My Calories

I made this mistake at the beginning itself when I started off with a high calorie deficit.

As and when my progress stalled, I further increased the deficit and as I said earlier, by the end, I was eating less than 1000 calories which meant close to a whopping 1700 calorie deficit!

Restricting calories too much can have an effect opposite of what’s intended due to the slew of harmful side effects such as:

Lowered metabolism

Several studies such as this, this, and this have found that low-calorie diets can decrease the number of calories the body burns by as much as 23%.

Moreover, this study published in the International Journal of Obesity found that this lower metabolism can persist long after the calorie-restriction is stopped.

Over time this leads to “metabolic damage”.

Fatigue and nutrient deficiencies

Regularly eating fewer calories than your body requires can cause fatigue and make it more challenging for you to meet your daily nutrient needs.

Mainly, calorie-restricted diets may not provide sufficient amounts of iron, folate, or vitamin B12. This can lead to anemia and extreme fatigue.

Wreck your hormones

This article by Precision Nutrition describes how severe calorie restriction affects appetite hormones such as leptin and ghrelin while this study published in the United States Health and Human Services found it decreases Testosterone levels.

Other studies have consistently shown a relationship between severe calorie restriction and disrupted hormones. This means that your hunger, sex drive, muscle, bones, skin, and overall health is greatly affected.

Lower Your Immunity

This study published in the British Journal Of Sports Medicine and this study published in the Clinical Journal Of Sports Medicine have found a relation between severe calorie restriction and decreased immunity.

The Takeaway

Crash or “yo-yo” dieting where you use severe calorie deficits are recipes for disaster as they not only impede your weight loss but even affect your health in other ways.

A low to moderate calorie deficit over a longer period is much better than a severe deficit over a short period.

Photo by Polina Rytova on Unsplash

Mistake #2- Doing Too Much Cardio

I was cycling 10 kilometers thrice a week and sometimes I would add a fourth session where I would go up to 20 kilometers.

Research shows that intense, prolonged endurance training is a particularly effective way to induce overtraining.

You’re also more likely to experience an excessive metabolic slowdown, which can persist long after weight loss is stopped. Research also shows that just doing cardio guarantees little in the way of fat loss.

So this means that despite cardio being able to burn calories, excess of it can accelerate muscle loss, greatly impact recovery and cause a metabolic slowdown.

How much cardio should you do?

You don’t need any cardio but generating the deficit through diet alone means that you won’t get to eat a lot.

Mike Matthews, a best-selling health and fitness author does and recommends only an hour or two of cardio per week.

Yes, not per day but per week.

Do just enough cardio to not impair your recovery and training regime.

Photo by Binyamin Mellish from Pexels

Mistake #3 — Not Prioritizing Strength Training

Due to the severe calorie deficit and excessive cardio I could barely perform in the gym. I lost a lot of strength in the gym and as a result, lost muscle also.

When losing weight, you should aim to lose fat and preserve muscle.

Studies show that prioritizing resistance training and supplementing it with some cardio is the best way to lose fat without losing muscle.

The myth of light weights and higher reps to “cut”

One of the biggest myths associated with “cutting” that even I used to believe in is lifting “light weights with high reps” to get a “toned” look.

No, all you will do is lose muscle not get “toned” that way.

You need to continue lifting heavy to preserve muscle as muscle is a result of your body’s adaptations to increasing demands placed on it. By lifting light you literally “signal” to your body that you no longer need the muscle.

So you need to continue to lift heavy.

Cut down volume

Since your rate of recovery and energy is lower, you might want to reduce the number of sets, especially on the compound movements.

I would recommend cutting down volume by 30–40%.

Ramp up the frequency

Frequency is basically how frequently you train a particular muscle group. Lowering volume and increasing the frequency will enable you to perform and recover better as the sessions get shorter.

A training frequency of 2–4 times per week has been found to be optimal to maximize muscle protein synthesis.

The Takeaway

Focus on the compound lifts, continue to lift heavy trying to maintain or even gain strength, reduce the volume and increase the frequency.

Photo by Avery Steadman on Unsplash

Mistake #4 — Not Listening to My Body

I never listened to my body and believed that more is better. But more isn’t always better and I realized that the hard way.

Along with my gym workouts and cardio, I would do HIIT sessions or “ab” workout sessions at home.

This led to severe overtraining — muscle cramps, extreme fatigue, affected recovery, joint inflammation, etc.

Here’s a detailed blog post on the effects of overtraining.

I encountered a lot of red flags but I never paid heed to them. The day when I went to bed feeling sure I wouldn’t wake up is one such example where I blatantly refused to listen to my body.

The human body is an amazing thing that throws up signs which you need to pay heed to.

Listen to your body. Don’t ignore red flags such as joint pains, fatigue, muscle cramps, parched lips, headaches etc. which could mean lack of rest, physical strain, mental strain, dehydration etc.

Want to Lose (and Keep Off) Body Fat without Any Overcomplicated B.S.? Grab Your Free Copy of The 5-Minute Fat-Loss Simplifier

Health
Fitness
Fitness Tips
Fat Loss
Weight Loss
Recommended from ReadMedium