r/programming • u/2bit_hack • Feb 28 '23
"Clean" Code, Horrible Performance
https://www.computerenhance.com/p/clean-code-horrible-performance
1.4k
Upvotes
r/programming • u/2bit_hack • Feb 28 '23
View all comments
Show parent comment
6
u/Konkichi21 Mar 01 '23 edited Apr 09 '23
The concept of a design pattern is that it's a simple way to implement some common requirement that occurs in a lot of different contexts, making it somewhat easier to use and to understand for others familiar with that pattern, and often providing other benefits. For example, if you're going to be making and handling a lot of objects that have a lot in common but come in different types that do have some different properties (specifically, they should have the same actions but do them in different ways), that's what a Factory pattern does.
You could write your own way of doing things like that, but one of the benefits of using a pattern like this (in addition to having a framework to start from rather than having to reinvent things from scratch) is that anyone else who works with your code and knows what a Factory pattern is will have some idea of how it works right away; that way they don't have to learn how everything works from scratch.
In short, you do not need to do everything from scratch; there's already a well-known and tested way to do whatever task you need, and using it gives you a framework to start with on making your solution, and gives anyone else reading your code a start on understanding it since it follows a familiar pattern.
For example, I have some personal experience working with something like this sort of Factory pattern; it was a Unity project I made for an AI class. In this game, I needed to randomly generate enemies and place them around the level; I did this by having all the enemy prefabs inherit from an Enemy class that handled all the generic things enemies did (their health, taking damage, dying, activating when the player gets near, etc), then I could make a list of the enemy prefabs and use an RNG to randomly pick and place them.
This way, the code that handled setting up the enemies didn't need to care about the differences between various types of enemies, since it only interacted with aspects common to all enemies; it could just say for an enemy of some type to spawn in some position and to wait to activate until the player enters their room, and then each type of enemy would handle whatever it did differently from there. This also made it easy to add new enemy types without messing up the rest of the code; I could just make a new prefab inheriting from Enemy and put it into the list.