Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

🛁 Clean Code concepts adapted for Python

License

NotificationsYou must be signed in to change notification settings

AlexanderHobert/clean-code-python

 
 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 
 
 
 
 
 
 

Repository files navigation

Table of Contents

  1. Introduction
  2. Variables
  3. Functions
  4. Objects and Data Structures
  5. Classes
    1. S: Single Responsibility Principle (SRP)
    2. O: Open/Closed Principle (OCP)
    3. L: Liskov Substitution Principle (LSP)
    4. I: Interface Segregation Principle (ISP)
    5. D: Dependency Inversion Principle (DIP)
  6. Don’t repeat yourself (DRY)

Introduction

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

Targets Python3.7+

Variables

Use meaningful and pronounceable variable names

Bad:

ymdstr=datetime.date.today().strftime("%y-%m-%d")

Good:

current_date:str=datetime.date.today().strftime("%y-%m-%d")

⬆ back to top

Use the same vocabulary for the same type of variable

Bad:Here we use three different names for the same underlying entity:

get_user_info()get_client_data()get_customer_record()

Good:If the entity is the same, you should be consistent in referring to it in your functions:

get_user_info()get_user_data()get_user_record()

Even betterPython is (also) an object oriented programming language. If it makes sense, package the functions together with the concrete implementationof the entity in your code, as instance attributes, property methods, or methods:

classUser:info :str@propertydefdata(self)->dict:# ...defget_record(self)->Union[Record,None]:# ...

⬆ back to top

Use searchable names

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)

⬆ back to top

Use explanatory variables

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'])

⬆ back to top

Avoid Mental Mapping

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)

⬆ back to top

Don't add unneeded context

If your class/object name tells you something, don't repeat that in yourvariable name.

Bad:

classCar:car_make:strcar_model:strcar_color:str

Good:

classCar:make:strmodel:strcolor:str

⬆ back to top

Use default arguments instead of short circuiting or conditionals

Tricky

Why write:

defcreate_micro_brewery(name):name="Hipster Brew Co."ifnameisNoneelsenameslug=hashlib.sha1(name.encode()).hexdigest()# etc.

... when you can specify a default argument instead? This also makes ist clear thatyou are expecting a string as the argument.

Good:

defcreate_micro_brewery(name:str="Hipster Brew Co."):slug=hashlib.sha1(name.encode()).hexdigest()# etc.

⬆ back to top

Functions

Function arguments (2 or fewer ideally)

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:

defcreate_menu(title,body,button_text,cancellable):# ...

Good:

classMenu:def__init__(self,config:dict):title=config["title"]body=config["body"]# ...menu=Menu(    {"title":"My Menu","body":"Something about my menu","button_text":"OK","cancellable":False    })

Also good

classMenuConfig:"""A configuration for the Menu.    Attributes:        title: The title of the Menu.        body: The body of the Menu.        button_text: The text for the button label.        cancellable: Can it be cancelled?    """title:strbody:strbutton_text:strcancellable:bool=Falsedefcreate_menu(config:MenuConfig):title=config.titlebody=config.body# ...config=MenuConfigconfig.title="My delicious menu"config.body="A description of the various items on the menu"config.button_text="Order now!"# The instance attribute overrides the default class attribute.config.cancellable=Truecreate_menu(config)

Fancy

fromtypingimportNamedTupleclassMenuConfig(NamedTuple):"""A configuration for the Menu.    Attributes:        title: The title of the Menu.        body: The body of the Menu.        button_text: The text for the button label.        cancellable: Can it be cancelled?    """title:strbody:strbutton_text:strcancellable:bool=Falsedefcreate_menu(config:MenuConfig):title,body,button_text,cancellable=configcreate_menu(MenuConfig(title="My delicious menu",body="A description of the various items on the menu",button_text="Order now!"    ))

⬆ back to top

Functions should do one thing

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:

defemail_clients(clients:List[Client]):"""Filter active clients and send them an email.    """forclientinclients:ifclient.active:email(client)

Good:

defget_active_clients(clients:List[Client])->List[Client]:"""Filter active clients.    """return [clientforclientinclientsifclient.active]defemail_clients(clients:List[Client, ...])->None:"""Send an email to a given list of clients.    """forclientinclients:email(client)

Do you see an opportunity for using generators now?

Even better

defactive_clients(clients:List[Client])->Generator[Client]:"""Only active clients.    """return (clientforclientinclientsifclient.active)defemail_client(clients:Iterator[Client])->None:"""Send an email to a given list of clients.    """forclientinclients:email(client)

⬆ back to top

Function names should say what they do

Bad:

classEmail:defhandle(self)->None:# Do something...message=Email()# What is this supposed to do again?message.handle()

Good:

classEmail:defsend(self)->None:"""Send this message.        """message=Email()message.send()

⬆ back to top

Functions should only be one level of abstraction

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().

⬆ back to top

Don't use flags as function parameters

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);}

⬆ back to top

Avoid Side Effects

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'];

⬆ back to top

Don't write to global functions

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.

⬆ back to top

Don't use a Singleton pattern

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.

⬆ back to top

Encapsulate conditionals

Bad:

if ($article->state ==='published') {// ...}

Good:

if ($article->isPublished()) {// ...}

⬆ back to top

Avoid negative conditionals

Bad:

functionisDOMNodeNotPresent($node) {// ...}if (!isDOMNodeNotPresent($node)) {// ...}

Good:

functionisDOMNodePresent($node) {// ...}if (isDOMNodePresent($node)) {// ...}

⬆ back to top

Avoid conditionals

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();    }}

⬆ back to top

Avoid type-checking (part 1)

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'));}

⬆ back to top

Avoid type-checking (part 2)

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;}

⬆ back to top

Remove dead code

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');

⬆ back to top

Objects and Data Structures

Use getters and setters

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 aset.
  • 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();

⬆ back to top

Make objects have private/protected members

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

⬆ back to top

Classes

Single Responsibility Principle (SRP)

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()) {// ...        }    }}

⬆ back to top

Open/Closed Principle (OCP)

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);    }}

⬆ back to top

Liskov Substitution Principle (LSP)

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);

⬆ back to top

Interface Segregation Principle (ISP)

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();    }}

⬆ back to top

Dependency Inversion Principle (DIP)

This principle states two essential things:

  1. High-level modules should not depend on low-level modules. Both shoulddepend on abstractions.
  2. 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();    }}

⬆ back to top

Use method chaining

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();

⬆ back to top

Prefer composition over inheritance

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:

  1. Your inheritance represents an "is-a" relationship and not a "has-a"relationship (Human->Animal vs. User->UserDetails).
  2. You can reuse code from the base classes (Humans can move like all animals).
  3. 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);    }// ...}

⬆ back to top

Don’t repeat yourself (DRY)

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()        ]);    }}

⬆ back to top

About

🛁 Clean Code concepts adapted for Python

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages

  • PHP100.0%

[8]ページ先頭

©2009-2025 Movatter.jp