Don’t write duplicate code (DRY)
Try to follow the DRY principle
Do your best to avoid duplicating code, it is a very bad behavior, duplicating code usually means that when you need to change some logic, you need to modify it Not just one place.
Imagine if you are running a restaurant and you are recording the purchases and sales of your warehouse: all the potatoes, onions, garlic, peppers, etc. If you have multiple lists to manage your purchases and sales, you will need to update all of them when you cook with some of the potatoes. If you only have one list there is only one place to update.
Usually when you copy code, you should have two or more slightly different logics. Most of them are the same, but because of their differences, you must have two or more isolated but In much the same way, removing duplicate code means using a function/module/class
to create an abstraction that can handle the differences.
Using the right abstraction is critical, which is why you must learn to abide by the SOLID
principles written in the classes chapter. Unreasonable abstraction is worse than duplicating code, so be careful! Having said all that, if you can design a reasonable abstraction, then do it! Don't write duplicate code, or you'll find that any time you want to change a piece of logic you have to change it in multiple places.
Bad:
function showDeveloperList(array $developers): void { foreach ($developers as $developer) { $expectedSalary = $developer->calculateExpectedSalary(); $experience = $developer->getExperience(); $githubLink = $developer->getGithubLink(); $data = [ $expectedSalary, $experience, $githubLink ]; render($data); } } function showManagerList(array $managers): void { foreach ($managers as $manager) { $expectedSalary = $manager->calculateExpectedSalary(); $experience = $manager->getExperience(); $githubLink = $manager->getGithubLink(); $data = [ $expectedSalary, $experience, $githubLink ]; render($data); } }
Good:
function showList(array $employees): void { foreach ($employees as $employee) { $expectedSalary = $employee->calculateExpectedSalary(); $experience = $employee->getExperience(); $githubLink = $employee->getGithubLink(); $data = [ $expectedSalary, $experience, $githubLink ]; render($data); } }
Excellent:
It’s better to make the code more compact
function showList(array $employees): void { foreach ($employees as $employee) { render([ $employee->calculateExpectedSalary(), $employee->getExperience(), $employee->getGithubLink() ]); } }