Published on

Design Patterns - Why & How?

Nextjs

I spent some past time learning design patterns in-depth to get better with software design. Here's quick gist:

Design Patterns are solutions to commonly occuring design problems in software. They are template solutions that follow many or all of SOLID principles solving maintainability and scalability out of the box.

Why use them?
  • Many of the design problems we encounter as developers have already been solved. Design Patterns help avoid the need to create new solutions from scratch.

  • They follow SOLID principles so it gets easier to manage the codebase.
  • They provide a common vocabulary for developers, leading to better communication and better solutions.

Design Patterns are categorised into 3 types:
  1. Creational design patterns: focus on object creation (you might have heard Factory, and Builder)

  2. Structural design patterns: focus on the composition of objects and classes

  3. Behavioral design patterns: focus on the communication between objects

There are 20+ patterns and all are very useful but here is the one that I found very interesting.

Flyweight Design Pattern: Helps fit more objects into available RAM by keeping common parts of objects separate, for all objects to share, instead of keeping all the data in all the objects.

Consider the focus app, Forest, that helps users stay productive by planting virtual trees when they remain focused on tasks. These trees represent the user’s progress and focus sessions.

Nextjs

If the app creates individual objects for each tree, with their species, size, animation, sound effects, and other data - it could lead to a lot of redundant data being stored in memory, which will slow down the app and hog memory.

Here we can use the flyweight pattern.

The data for each tree can be divided into these states:

  • Intrinsic state (shared, immutable) : species, appearance, animation, sounds

  • Extrinsic state : growth progress, size, position

When a user plants an oak tree, the intrinsic state is stored once and shared, while the extrinsic state is unique to that tree and stored separately. All the oak tree objects use the same memory reference to get that shared intrinsic state data.

The folks at SeekrTech (publishers of Forest app) might already be doing it.

If you need more code examples: Design Patterns Git Repo

Here are the resources that were super useful and I highly recommend:

  1. Shabbir Dawoodi's Design Patterns Master Class

    (link)

  2. Refactoring Guru

    (link)

You can read the full text here: Design Patterns - Why and How? on harshwadhwa.com

Thoughts or suggestions ?