- Notifications
You must be signed in to change notification settings - Fork0
🛁 Clean Code concepts adapted for Python
License
PhanDuc/clean-code-python
Folders and files
| Name | Name | Last commit message | Last commit date | |
|---|---|---|---|---|
Repository files navigation
Software engineering principles, from Robert C. Martin's bookClean Code,adapted for Python. This is not a style guide. It's a guide to producingreadable, reusable, and refactorable software in Python.
Not every principle herein has to be strictly followed, and even fewer will be universallyagreed upon. These are guidelines and nothing more, but they are ones codified over manyyears of collective experience by the authors ofClean Code.
Inspired fromclean-code-javascript
Bad:
ymdstr=datetime.date.today().strftime("%y-%m-%d")
Good:
current_date=datetime.date.today().strftime("%y-%m-%d")
Bad:
get_user_info()get_client_data()get_customer_record()
Good:
get_user()We will read more code than we will ever write. It's important that the code we do write isreadable and searchable. Bynot naming variables that end up being meaningful forunderstanding our program, we hurt our readers.Make your names searchable.
Bad:
# What the heck is 86400 for?time.sleep(86400);
Good:
# Declare them in the global namespace for the module.SECONDS_IN_A_DAY=60*60*24time.sleep(SECONDS_IN_A_DAY)
Bad:
address='One Infinite Loop, Cupertino 95014'city_zip_code_regex=r'^[^,\\]+[,\\\s]+(.+?)\s*(\d{5})?$'matches=re.match(city_zip_code_regex,address)save_city_zip_code(matches[1],matches[2])
Not bad:
It's better, but we are still heavily dependent on regex.
address='One Infinite Loop, Cupertino 95014'city_zip_code_regex=r'^[^,\\]+[,\\\s]+(.+?)\s*(\d{5})?$'matches=re.match(city_zip_code_regex,address)city,zip_code=matches.groups()save_city_zip_code(city,zip_code)
Good:
Decrease dependence on regex by naming subpatterns.
address='One Infinite Loop, Cupertino 95014'city_zip_code_regex=r'^[^,\\]+[,\\\s]+(?P<city>.+?)\s*(?P<zip_code>\d{5})?$'matches=re.match(city_zip_code_regex,address)save_city_zip_code(matches['city'],matches['zip_code'])
Don’t force the reader of your code to translate what the variable means.Explicit is better than implicit.
Bad:
seq= ('Austin','New York','San Francisco')foriteminseq:do_stuff()do_some_other_stuff()# ...# Wait, what's `item` for again?dispatch(item)
Good:
locations= ('Austin','New York','San Francisco')forlocationinlocations:do_stuff()do_some_other_stuff()# ...dispatch(location)
If your class/object name tells you something, don't repeat that in yourvariable name.
Bad:
class Car{public$carMake;public$carModel;public$carColor;//...}
Good:
class Car{public$make;public$model;public$color;//...}
Not good:
This is not good because$breweryName can beNULL.
functioncreateMicrobrewery($breweryName ='Hipster Brew Co.'){ // ...}
Not bad:
This opinion is more understandable than the previous version, but it better controls the value of the variable.
functioncreateMicrobrewery($name =null){ $breweryName =$name ?:'Hipster Brew Co.';// ...}
Good:
If you support only PHP 7+, then you can usetype hinting and be sure that the$breweryName will not beNULL.
functioncreateMicrobrewery(string$breweryName ='Hipster Brew Co.'){ // ...}
Limiting the amount of function parameters is incredibly important because it makestesting your function easier. Having more than three leads to a combinatorial explosionwhere you have to test tons of different cases with each separate argument.
Zero arguments is the ideal case. One or two arguments is ok, and three should be avoided.Anything more than that should be consolidated. Usually, if you have more than twoarguments then your function is trying to do too much. In cases where it's not, mostof the time a higher-level object will suffice as an argument.
Bad:
functioncreateMenu($title,$body,$buttonText,$cancellable) {// ...}
Good:
class MenuConfig{public$title;public$body;public$buttonText;public$cancellable =false;}$config =newMenuConfig();$config->title ='Foo';$config->body ='Bar';$config->buttonText ='Baz';$config->cancellable =true;functioncreateMenu(MenuConfig$config) {// ...}
This is by far the most important rule in software engineering. When functions do morethan one thing, they are harder to compose, test, and reason about. When you can isolatea function to just one action, they can be refactored easily and your code will read muchcleaner. If you take nothing else away from this guide other than this, you'll be aheadof many developers.
Bad:
functionemailClients($clients) {foreach ($clientsas$client) {$clientRecord =$db->find($client);if ($clientRecord->isActive()) {email($client); } }}
Good:
functionemailClients($clients) {$activeClients =activeClients($clients);array_walk($activeClients,'email');}functionactiveClients($clients) {returnarray_filter($clients,'isClientActive');}functionisClientActive($client) {$clientRecord =$db->find($client);return$clientRecord->isActive();}
Bad:
class Email{//...publicfunctionhandle() {mail($this->to,$this->subject,$this->body); }}$message =newEmail(...);// What is this? A handle for the message? Are we writing to a file now?$message->handle();
Good:
class Email {//...publicfunctionsend() {mail($this->to,$this->subject,$this->body); }}$message =newEmail(...);// Clear and obvious$message->send();
When you have more than one level of abstraction your function is usuallydoing too much. Splitting up functions leads to reusability and easiertesting.
Bad:
functionparseBetterJSAlternative($code){$regexes = [// ... ];$statements =split('',$code);$tokens = [];foreach ($regexesas$regex) {foreach ($statementsas$statement) {// ... } }$ast = [];foreach ($tokensas$token) {// lex... }foreach ($astas$node) {// parse... }}
Bad too:
We have carried out some of the functionality, but theparseBetterJSAlternative() function is still very complex and not testable.
functiontokenize($code){$regexes = [// ... ];$statements =split('',$code);$tokens = [];foreach ($regexesas$regex) {foreach ($statementsas$statement) {$tokens[] =/* ... */; } }return$tokens;}functionlexer($tokens){$ast = [];foreach ($tokensas$token) {$ast[] =/* ... */; }return$ast;}functionparseBetterJSAlternative($code){$tokens =tokenize($code);$ast =lexer($tokens);foreach ($astas$node) {// parse... }}
Good:
The best solution is move out the dependencies ofparseBetterJSAlternative() function.
class Tokenizer{publicfunctiontokenize($code) {$regexes = [// ... ];$statements =split('',$code);$tokens = [];foreach ($regexesas$regex) {foreach ($statementsas$statement) {$tokens[] =/* ... */; } }return$tokens; }}
class Lexer{publicfunctionlexify($tokens) {$ast = [];foreach ($tokensas$token) {$ast[] =/* ... */; }return$ast; }}
class BetterJSAlternative{private$tokenizer;private$lexer;publicfunction__construct(Tokenizer$tokenizer,Lexer$lexer) {$this->tokenizer =$tokenizer;$this->lexer =$lexer; }publicfunctionparse($code) {$tokens =$this->tokenizer->tokenize($code);$ast =$this->lexer->lexify($tokens);foreach ($astas$node) {// parse... } }}
Now we can mock the dependencies and test only the work of methodBetterJSAlternative::parse().
Flags tell your user that this function does more than one thing. Functions shoulddo one thing. Split out your functions if they are following different code pathsbased on a boolean.
Bad:
functioncreateFile($name,$temp =false) {if ($temp) {touch('./temp/'.$name); }else {touch($name); }}
Good:
functioncreateFile($name) {touch($name);}functioncreateTempFile($name) {touch('./temp/'.$name);}
A function produces a side effect if it does anything other than take a value in andreturn another value or values. A side effect could be writing to a file, modifyingsome global variable, or accidentally wiring all your money to a stranger.
Now, you do need to have side effects in a program on occasion. Like the previousexample, you might need to write to a file. What you want to do is to centralize whereyou are doing this. Don't have several functions and classes that write to a particularfile. Have one service that does it. One and only one.
The main point is to avoid common pitfalls like sharing state between objects withoutany structure, using mutable data types that can be written to by anything, and notcentralizing where your side effects occur. If you can do this, you will be happierthan the vast majority of other programmers.
Bad:
// Global variable referenced by following function.// If we had another function that used this name, now it'd be an array and it could break it.$name ='Ryan McDermott';functionsplitIntoFirstAndLastName() {global$name;$name =preg_split('/ /',$name);}splitIntoFirstAndLastName();var_dump($name);// ['Ryan', 'McDermott'];
Good:
functionsplitIntoFirstAndLastName($name) {returnpreg_split('/ /',$name);}$name ='Ryan McDermott';$newName =splitIntoFirstAndLastName($name);var_dump($name);// 'Ryan McDermott';var_dump($newName);// ['Ryan', 'McDermott'];
Polluting globals is a bad practice in many languages because you could clash with anotherlibrary and the user of your API would be none-the-wiser until they get an exception inproduction. Let's think about an example: what if you wanted to have configuration array.You could write global function likeconfig(), but it could clash with another librarythat tried to do the same thing.
Bad:
functionconfig(){return ['foo' =>'bar', ]}
Good:
Create PHP configuration file or something else
// config.phpreturn ['foo' =>'bar',];
class Configuration{private$configuration = [];publicfunction__construct(array$configuration) {$this->configuration =$configuration; }publicfunctionget($key) {returnisset($this->configuration[$key]) ?$this->configuration[$key] :null; }}
Load configuration from file and create instance ofConfiguration class
$configuration =newConfiguration($configuration);
And now you must use instance ofConfiguration in your application.
Singleton is aanti-pattern.
Bad:
class DBConnection{privatestatic$instance;privatefunction__construct($dsn) {// ... }publicstaticfunctiongetInstance() {if (self::$instance ===null) {self::$instance =newself(); }returnself::$instance; }// ...}$singleton = DBConnection::getInstance();
Good:
class DBConnection{publicfunction__construct(array$dsn) {// ... }// ...}
Create instance ofDBConnection class and configure it withDSN.
$connection =newDBConnection($dsn);
And now you must use instance ofDBConnection in your application.
Bad:
if ($article->state ==='published') {// ...}
Good:
if ($article->isPublished()) {// ...}
Bad:
functionisDOMNodeNotPresent($node) {// ...}if (!isDOMNodeNotPresent($node)) {// ...}
Good:
functionisDOMNodePresent($node) {// ...}if (isDOMNodePresent($node)) {// ...}
This seems like an impossible task. Upon first hearing this, most people say,"how am I supposed to do anything without anif statement?" The answer is thatyou can use polymorphism to achieve the same task in many cases. The secondquestion is usually, "well that's great but why would I want to do that?" Theanswer is a previous clean code concept we learned: a function should only doone thing. When you have classes and functions that haveif statements, youare telling your user that your function does more than one thing. Remember,just do one thing.
Bad:
class Airplane {// ...publicfunctiongetCruisingAltitude() {switch ($this->type) {case'777':return$this->getMaxAltitude() -$this->getPassengerCount();case'Air Force One':return$this->getMaxAltitude();case'Cessna':return$this->getMaxAltitude() -$this->getFuelExpenditure(); } }}
Good:
class Airplane {// ...}class Boeing777extends Airplane {// ...publicfunctiongetCruisingAltitude() {return$this->getMaxAltitude() -$this->getPassengerCount(); }}class AirForceOneextends Airplane {// ...publicfunctiongetCruisingAltitude() {return$this->getMaxAltitude(); }}class Cessnaextends Airplane {// ...publicfunctiongetCruisingAltitude() {return$this->getMaxAltitude() -$this->getFuelExpenditure(); }}
PHP is untyped, which means your functions can take any type of argument.Sometimes you are bitten by this freedom and it becomes tempting to dotype-checking in your functions. There are many ways to avoid having to do this.The first thing to consider is consistent APIs.
Bad:
functiontravelToTexas($vehicle){if ($vehicleinstanceof Bicycle) {$vehicle->peddleTo(newLocation('texas')); }elseif ($vehicleinstanceof Car) {$vehicle->driveTo(newLocation('texas')); }}
Good:
functiontravelToTexas(Traveler$vehicle){$vehicle->travelTo(newLocation('texas'));}
If you are working with basic primitive values like strings, integers, and arrays,and you use PHP 7+ and you can't use polymorphism but you still feel the need totype-check, you should considertype declarationor strict mode. It provides you with static typing on top of standard PHP syntax.The problem with manually type-checking is that doing it well requires so muchextra verbiage that the faux "type-safety" you get doesn't make up for the lostreadability. Keep your PHP clean, write good tests, and have good code reviews.Otherwise, do all of that but with PHP strict type declaration or strict mode.
Bad:
functioncombine($val1,$val2){if (!is_numeric($val1) || !is_numeric($val2)) {thrownew \Exception('Must be of type Number'); }return$val1 +$val2;}
Good:
functioncombine(int$val1,int$val2){return$val1 +$val2;}
Dead code is just as bad as duplicate code. There's no reason to keep it inyour codebase. If it's not being called, get rid of it! It will still be safein your version history if you still need it.
Bad:
functionoldRequestModule($url) {// ...}functionnewRequestModule($url) {// ...}$request =newRequestModule($requestUrl);inventoryTracker('apples',$request,'www.inventory-awesome.io');
Good:
functionrequestModule($url) {// ...}$request =requestModule($requestUrl);inventoryTracker('apples',$request,'www.inventory-awesome.io');
In PHP you can setpublic,protected andprivate keywords for methods.Using it, you can control properties modification on an object.
- When you want to do more beyond getting an object property, you don't haveto look up and change every accessor in your codebase.
- Makes adding validation simple when doing a
set. - Encapsulates the internal representation.
- Easy to add logging and error handling when getting and setting.
- Inheriting this class, you can override default functionality.
- You can lazy load your object's properties, let's say getting it from aserver.
Additionally, this is part of Open/Closed principle, from object-orienteddesign principles.
Bad:
class BankAccount {public$balance =1000;}$bankAccount =newBankAccount();// Buy shoes...$bankAccount->balance -=100;
Good:
class BankAccount {private$balance;publicfunction__construct($balance =1000) {$this->balance =$balance; }publicfunctionwithdrawBalance($amount) {if ($amount >$this->balance) {thrownew \Exception('Amount greater than available balance.'); }$this->balance -=$amount; }publicfunctiondepositBalance($amount) {$this->balance +=$amount; }publicfunctiongetBalance() {return$this->balance; }}$bankAccount =newBankAccount();// Buy shoes...$bankAccount->withdrawBalance($shoesPrice);// Get balance$balance =$bankAccount->getBalance();
Bad:
class Employee {public$name;publicfunction__construct($name) {$this->name =$name; }}$employee =newEmployee('John Doe');echo'Employee name:'.$employee->name;// Employee name: John Doe
Good:
class Employee {protected$name;publicfunction__construct($name) {$this->name =$name; }publicfunctiongetName() {return$this->name; }}$employee =newEmployee('John Doe');echo'Employee name:'.$employee->getName();// Employee name: John Doe
As stated in Clean Code, "There should never be more than one reason for a classto change". It's tempting to jam-pack a class with a lot of functionality, likewhen you can only take one suitcase on your flight. The issue with this isthat your class won't be conceptually cohesive and it will give it many reasonsto change. Minimizing the amount of times you need to change a class is important.It's important because if too much functionality is in one class and you modify a piece of it,it can be difficult to understand how that will affect other dependent modules inyour codebase.
Bad:
class UserSettings {private$user;publicfunction__construct($user) {$this->user =$user; }publicfunctionchangeSettings($settings) {if ($this->verifyCredentials()) {// ... } }privatefunctionverifyCredentials() {// ... }}
Good:
class UserAuth {private$user;publicfunction__construct($user) {$this->user =$user; }publicfunctionverifyCredentials() {// ... }}class UserSettings {private$user;publicfunction__construct($user) {$this->user =$user;$this->auth =newUserAuth($user); }publicfunctionchangeSettings($settings) {if ($this->auth->verifyCredentials()) {// ... } }}
As stated by Bertrand Meyer, "software entities (classes, modules, functions,etc.) should be open for extension, but closed for modification." What does thatmean though? This principle basically states that you should allow users toadd new functionalities without changing existing code.
Bad:
abstractclass Adapter{protected$name;publicfunctiongetName() {return$this->name; }}class AjaxAdapterextends Adapter{publicfunction__construct() {parent::__construct();$this->name ='ajaxAdapter'; }}class NodeAdapterextends Adapter{publicfunction__construct() {parent::__construct();$this->name ='nodeAdapter'; }}class HttpRequester{private$adapter;publicfunction__construct($adapter) {$this->adapter =$adapter; }publicfunctionfetch($url) {$adapterName =$this->adapter->getName();if ($adapterName ==='ajaxAdapter') {return$this->makeAjaxCall($url); }elseif ($adapterName ==='httpNodeAdapter') {return$this->makeHttpCall($url); } }protectedfunctionmakeAjaxCall($url) {// request and return promise }protectedfunctionmakeHttpCall($url) {// request and return promise }}
Good:
interface Adapter{publicfunctionrequest($url);}class AjaxAdapterimplements Adapter{publicfunctionrequest($url) {// request and return promise }}class NodeAdapterimplements Adapter{publicfunctionrequest($url) {// request and return promise }}class HttpRequester{private$adapter;publicfunction__construct(Adapter$adapter) {$this->adapter =$adapter; }publicfunctionfetch($url) {return$this->adapter->request($url); }}
This is a scary term for a very simple concept. It's formally defined as "If Sis a subtype of T, then objects of type T may be replaced with objects of type S(i.e., objects of type S may substitute objects of type T) without altering anyof the desirable properties of that program (correctness, task performed,etc.)." That's an even scarier definition.
The best explanation for this is if you have a parent class and a child class,then the base class and child class can be used interchangeably without gettingincorrect results. This might still be confusing, so let's take a look at theclassic Square-Rectangle example. Mathematically, a square is a rectangle, butif you model it using the "is-a" relationship via inheritance, you quicklyget into trouble.
Bad:
class Rectangle{protected$width;protected$height;publicfunction__construct() {$this->width =0;$this->height =0; }publicfunctionrender($area) {// ... }publicfunctionsetWidth($width) {$this->width =$width; }publicfunctionsetHeight($height) {$this->height =$height; }publicfunctiongetArea() {return$this->width *$this->height; }}class Squareextends Rectangle{publicfunctionsetWidth($width) {$this->width =$this->height =$width; }publicfunctionsetHeight(height) {$this->width =$this->height =$height; }}functionrenderLargeRectangles($rectangles){foreach ($rectanglesas$rectangle) {$rectangle->setWidth(4);$rectangle->setHeight(5);$area =$rectangle->getArea();// BAD: Will return 25 for Square. Should be 20.$rectangle->render($area); }}$rectangles = [newRectangle(),newRectangle(),newSquare()];renderLargeRectangles($rectangles);
Good:
abstractclass Shape{protected$width;protected$height;abstractpublicfunctiongetArea();publicfunctionrender($area) {// ... }}class Rectangleextends Shape{publicfunction__construct() {parent::__construct();$this->width =0;$this->height =0; }publicfunctionsetWidth($width) {$this->width =$width; }publicfunctionsetHeight($height) {$this->height =$height; }publicfunctiongetArea() {return$this->width *$this->height; }}class Squareextends Shape{publicfunction__construct() {parent::__construct();$this->length =0; }publicfunctionsetLength($length) {$this->length =$length; }publicfunctiongetArea() {returnpow($this->length,2); }}functionrenderLargeRectangles($rectangles){foreach ($rectanglesas$rectangle) {if ($rectangleinstanceof Square) {$rectangle->setLength(5); }elseif ($rectangleinstanceof Rectangle) {$rectangle->setWidth(4);$rectangle->setHeight(5); }$area =$rectangle->getArea();$rectangle->render($area); }}$shapes = [newRectangle(),newRectangle(),newSquare()];renderLargeRectangles($shapes);
ISP states that "Clients should not be forced to depend upon interfaces thatthey do not use."
A good example to look at that demonstrates this principle is forclasses that require large settings objects. Not requiring clients to setuphuge amounts of options is beneficial, because most of the time they won't needall of the settings. Making them optional helps prevent having a "fat interface".
Bad:
interface WorkerInterface {publicfunctionwork();publicfunctioneat();}class Workerimplements WorkerInterface {publicfunctionwork() {// ....working }publicfunctioneat() {// ...... eating in launch break }}class SuperWorkerimplements WorkerInterface {publicfunctionwork() {//.... working much more }publicfunctioneat() {//.... eating in launch break }}class Manager {/** @var WorkerInterface $worker **/private$worker;publicfunctionsetWorker(WorkerInterface$worker) {$this->worker =$worker; }publicfunctionmanage() {$this->worker->work(); }}
Good:
interface WorkerInterfaceextends FeedableInterface, WorkableInterface {}interface WorkableInterface {publicfunctionwork();}interface FeedableInterface {publicfunctioneat();}class Workerimplements WorkableInterface, FeedableInterface {publicfunctionwork() {// ....working }publicfunctioneat() {//.... eating in launch break }}class Robotimplements WorkableInterface {publicfunctionwork() {// ....working }}class SuperWorkerimplements WorkerInterface {publicfunctionwork() {//.... working much more }publicfunctioneat() {//.... eating in launch break }}class Manager {/** @var $worker WorkableInterface **/private$worker;publicfunctionsetWorker(WorkableInterface$w) {$this->worker =$w; }publicfunctionmanage() {$this->worker->work(); }}
This principle states two essential things:
- High-level modules should not depend on low-level modules. Both shoulddepend on abstractions.
- Abstractions should not depend upon details. Details should depend onabstractions.
This can be hard to understand at first, but if you've worked with PHP frameworks (like Symfony), you've seen an implementation of this principle in the form of DependencyInjection (DI). While they are not identical concepts, DIP keeps high-levelmodules from knowing the details of its low-level modules and setting them up.It can accomplish this through DI. A huge benefit of this is that it reducesthe coupling between modules. Coupling is a very bad development pattern becauseit makes your code hard to refactor.
Bad:
class Worker {publicfunctionwork() {// ....working }}class Manager {/** @var Worker $worker **/private$worker;publicfunction__construct(Worker$worker) {$this->worker =$worker; }publicfunctionmanage() {$this->worker->work(); }}class SuperWorkerextends Worker {publicfunctionwork() {//.... working much more }}
Good:
interface WorkerInterface {publicfunctionwork();}class Workerimplements WorkerInterface {publicfunctionwork() {// ....working }}class SuperWorkerimplements WorkerInterface {publicfunctionwork() {//.... working much more }}class Manager {/** @var WorkerInterface $worker **/private$worker;publicfunction__construct(WorkerInterface$worker) {$this->worker =$worker; }publicfunctionmanage() {$this->worker->work(); }}
This pattern is very useful and commonly used it many libraries suchas PHPUnit and Doctrine. It allows your code to be expressive, and less verbose.For that reason, I say, use method chaining and take a look at how clean your codewill be. In your class functions, simply returnthis at the end of every function,and you can chain further class methods onto it.
Bad:
class Car {private$make,$model,$color;publicfunction__construct() {$this->make ='Honda';$this->model ='Accord';$this->color ='white'; }publicfunctionsetMake($make) {$this->make =$make; }publicfunctionsetModel($model) {$this->model =$model; }publicfunctionsetColor($color) {$this->color =$color; }publicfunctiondump() {var_dump($this->make,$this->model,$this->color); }}$car =newCar();$car->setColor('pink');$car->setMake('Ford');$car->setModel('F-150');$car->dump();
Good:
class Car {private$make,$model,$color;publicfunction__construct() {$this->make ='Honda';$this->model ='Accord';$this->color ='white'; }publicfunctionsetMake($make) {$this->make =$make;// NOTE: Returning this for chainingreturn$this; }publicfunctionsetModel($model) {$this->model =$model;// NOTE: Returning this for chainingreturn$this; }publicfunctionsetColor($color) {$this->color =$color;// NOTE: Returning this for chainingreturn$this; }publicfunctiondump() {var_dump($this->make,$this->model,$this->color); }}$car = (newCar()) ->setColor('pink') ->setMake('Ford') ->setModel('F-150') ->dump();
As stated famously inDesign Patterns by the Gang of Four,you should prefer composition over inheritance where you can. There are lots ofgood reasons to use inheritance and lots of good reasons to use composition.The main point for this maxim is that if your mind instinctively goes forinheritance, try to think if composition could model your problem better. In somecases it can.
You might be wondering then, "when should I use inheritance?" Itdepends on your problem at hand, but this is a decent list of when inheritancemakes more sense than composition:
- Your inheritance represents an "is-a" relationship and not a "has-a"relationship (Human->Animal vs. User->UserDetails).
- You can reuse code from the base classes (Humans can move like all animals).
- You want to make global changes to derived classes by changing a base class.(Change the caloric expenditure of all animals when they move).
Bad:
class Employee {private$name,$email;publicfunction__construct($name,$email) {$this->name =$name;$this->email =$email; }// ...}// Bad because Employees "have" tax data.// EmployeeTaxData is not a type of Employeeclass EmployeeTaxDataextends Employee {private$ssn,$salary;publicfunction__construct($name,$email,$ssn,$salary) {parent::__construct($name,$email);$this->ssn =$ssn;$this->salary =$salary; }// ...}
Good:
class EmployeeTaxData {private$ssn,$salary;publicfunction__construct($ssn,$salary) {$this->ssn =$ssn;$this->salary =$salary; }// ...}class Employee {private$name,$email,$taxData;publicfunction__construct($name,$email) {$this->name =$name;$this->email =$email; }publicfunctionsetTaxData($ssn,$salary) {$this->taxData =newEmployeeTaxData($ssn,$salary); }// ...}
Try to observe theDRY principle.
Do your absolute best to avoid duplicate code. Duplicate code is bad becauseit means that there's more than one place to alter something if you need tochange some logic.
Imagine if you run a restaurant and you keep track of your inventory: all yourtomatoes, onions, garlic, spices, etc. If you have multiple lists thatyou keep this on, then all have to be updated when you serve a dish withtomatoes in them. If you only have one list, there's only one place to update!
Oftentimes you have duplicate code because you have two or more slightlydifferent things, that share a lot in common, but their differences force youto have two or more separate functions that do much of the same things. Removingduplicate code means creating an abstraction that can handle this set of differentthings with just one function/module/class.
Getting the abstraction right is critical, that's why you should follow theSOLID principles laid out in theClasses section. Bad abstractions can beworse than duplicate code, so be careful! Having said this, if you can makea good abstraction, do it! Don't repeat yourself, otherwise you'll find yourselfupdating multiple places anytime you want to change one thing.
Bad:
functionshowDeveloperList($developers){ foreach ($developersas$developer) {$expectedSalary =$developer->calculateExpectedSalary();$experience =$developer->getExperience();$githubLink =$developer->getGithubLink();$data = [$expectedSalary,$experience,$githubLink ];render($data); }}functionshowManagerList($managers){ foreach ($managersas$manager) {$expectedSalary =$manager->calculateExpectedSalary();$experience =$manager->getExperience();$githubLink =$manager->getGithubLink();$data = [$expectedSalary,$experience,$githubLink ];render($data); }}
Good:
functionshowList($employees){ foreach ($employeesas$employee) { $expectedSalary =$employee->calculateExpectedSalary(); $experience =$employee->getExperience(); $githubLink =$employee->getGithubLink();$data = [$expectedSalary,$experience,$githubLink ];render($data); }}
Very good:
It is better to use a compact version of the code.
functionshowList($employees){ foreach ($employeesas$employee) {render([$employee->calculateExpectedSalary(),$employee->getExperience(),$employee->getGithubLink() ]); }}
About
🛁 Clean Code concepts adapted for Python
Resources
License
Uh oh!
There was an error while loading.Please reload this page.
Stars
Watchers
Forks
Releases
Packages0
Languages
- PHP100.0%