Just contacted IT Programmers in the industry have a pain point , I think the code I wrote is very good , But when people look at your code , I always think it's too messy , There is no specification . It's painful for programmers to maintain later . Why did I ask this question , This is where I came from . A book recommended for today 《 Clean Code 》.

<> Mind map

<> summary :

<> Code is a way of team communication .

* Design thought flow chart compilation .
* Clear code structure , The annotation is reasonable , Method parameter remarks .
* Follow the team's code specifications , It must be followed , Novices should follow when they come in .
<> Meaningful naming

* Use meaningful and spelling variable names # the other side $ymdstr = $moment->format('y-m-d'); # positive $currentDate =
$moment->format('y-m-d');
* Variables of the same type use the same vocabulary # the other side getUserInfo(); getClientData(); getCustomerRecord(); # positive
getUser();
* Use an easy to retrieve name # the other side //What the heck is 86400 for?(86400 What is it for ) addExpireAt(86400);
# positive // Declare them as capitalized `const` globals.( Declare variables in constant uppercase ) interface
DateGlobal { const SECONDS_IN_A_DAY = 86400; } addExpireAt(DateGlobal::
SECONDS_IN_A_DAY);
* Using explanatory variables # the other side $address = 'One Infinite Loop, Cupertino 95014';
$cityZipCodeRegex = '/^[^,\\]+[,\\\s]+(.+?)\s*(\d{5})?$/'; preg_match(
$cityZipCodeRegex, $address, $matches); saveCityZipCode($matches[1], $matches[2]
); //* contrast # positive $address = 'One Infinite Loop, Cupertino 95014'; $cityZipCodeRegex
= '/^[^,\\]+[,\\\s]+(.+?)\s*(\d{5})?$/'; preg_match($cityZipCodeRegex, $address,
$matches); list(,$city, $zipCode) = $matchers; //list() Assign values in an array to a set of variables
saveCityZipCode($city, $zipCode); // It's only used here $city and $zipCode variable .
*
Avoid mental mapping

Don't let the reader translate your name into a name they are familiar with .

*
name
Class name : Should not be the present verb , Avoid use Manager,Processor,Data,Info Such a class name .
Method name : Verb or verb phrase , From words to meanings , From meaning to speech .eg:getName()
Domain name :eg :AccountVisitor =>Visitor pattern
Don't pun : Avoid using the same word for different purposes .
Don't add useless context : eg:GSDAccountAddress =>Address

<> function

* It's not clear how short the method is , But as long as 500 A method of line , Absolutely let the reader to kill the heart . # the other side // Access to personal information Private UserDTO
getUserDTO(Integer userId) { // Get basic information … It's written here 10 That's ok // Get the latest order information … It's written here 30 That's ok //
Get wallet balance , Number of coupons available, etc ... It's written here 30 That's ok return userDTO; } # positive // Access to personal information Private UserDTO
getUserDTO(Integer userId) { // Get basic information UserDTO userDTO= getUserBasicInfo(userId)
; // Get the latest order information userDTO.setUserLastOrder(getUserLastOrder(userId)); //
Get Wallet , Number of coupons available, etc userDTO.setUserAccount(getUserAccount(userId)); return userDTO; }
Private UserDTO getUserBasicInfo(userId); Private UserLastOrder getUserLastOrder
(userId); Private UserAccount getUserAccount(userId);
*
Single responsibility ( A function is responsible for only one thing )

*
Each function has an abstract level ( Read code top down code : Down rule )
How to write the total score ( Personal understanding ): Always write steps , Sub is the method needed to write the steps .

*
Use descriptive names ( verb + key word )
eg:writeField
* reduce if/else nesting , Multi use polymorphism , A function does one thing , Compliance with single responsibility # the other side // Change user password , This is the only example 3 Layer nesting , It's very gentle public
booleanmodifyPassword(Integer userId, String oldPassword, String newPassword) {
if (userId != null && StringUtils.isNotBlank(newPassword) && SpringUtils.
isNotBlank(oldPassword)) { User user = getUserById(userId); if(user != null) {
if(user.getPassword().equals(oldPassword) { return updatePassword(userId,
newPassword) } } } } # positive // Change user password Public Boolean modifyPassword(Integer userId,
String oldPassword, String newPassword) { if (userId == null || StringUtils.
isBlank(newPassword) || StringUtils.isBlank(oldPassword)) { return false; }
User user= getUserById(userId); if(user == null) { return false; } if(!user.
getPassword().equals(oldPassword) { return false; } return updatePassword(userId
, newPassword); }
* Too many function method parameters , How to optimize . # the other side Class Book { public function create($name, $cateId,
$author, $year, $price, $publish, $country, $language) { $params = [ 'name' =>
$name, 'cateId' => $cateId, 'author' => $author, 'year' => $year, 'price' =>
$price, 'publish' => $publish, 'country' => $country, 'language' => $language, ]
; } } # Real face class BookModel { protected $name; protected $cateId; protected
$author; protected $year; protected $price; protected $publish; protected
$country; protected $language; public function getName() { return $this->name; }
public function setName($name) { $this->name = $name; } public function
getCateId() { return $this->cateId; } public function setCateId($cateId) { $this
->cateId = $cateId; } public function getAuthor() { return $this->author; }
public function setAuthor($author) { $this->author = $author; } public function
getYear() { return $this->year; } public function setYear($year) { $this->year =
$year; } public function getPrice() { return $this->price; } public function
setPrice($price) { $this->price = $price; } public function getPublish() {
return $this->publish; } public function setPublish($publish) { $this->publish =
$publish; } public function getCountry() { return $this->country; } public
function getLanguage() { return $this->language; } public function setLanguage(
$language) { $this->language = $language; } } # Controller call Class Book { public
function create(BookModel $bookModel) { $params = [ 'name' => $bookModel->
getName(), 'cateId' => $bookModel->getCateId(), 'author' => $bookModel->
getAuthor(), 'year' => $bookModel->getYear(), 'price' => $bookModel->getPrice(),
'publish' => $bookModel->getPublish(), 'country' => $bookModel->getCountry(),
'language' => $bookModel->getLanguage(), ]; } }
* Withdraw try/catch
1, The error handling code is separated from the main path code and simplified .
2, crux try Should be the first word of this function and catch/finally There is no other content after .
3, Eliminate error code # the other side // Access to personal information Private UserDTO getUserDTO(Integer userId) { try {
// Get basic information ... It's written here 10 That's ok // Get the latest order information ... It's written here 20 That's ok // Get Wallet , Number of coupons available, etc ... It's written here 20 That's ok }
catch (Exception e) { logger.error(e); return null; } } return userDTO; } # positive
// Access to personal information Private UserDTO getUserDTO(Integer userId) { // Get basic information UserDTO userDTO
= getUserBasicInfo(userId); // Get the latest order information userDTO.setUserLastOrder(
getUserLastOrder(userId)); // Get Wallet , Number of coupons available, etc userDTO.setUserAccount(
getUserAccount(userId)); return userDTO; } Private UserDTO getUserBasicInfo(
userId); Private UserLastOrder getUserLastOrder(userId); Private UserAccount
getUserAccount(userId){ try{ // TODO } catch( Exception e) { //TODO} }
* Don't repeat yourself
such as : The algorithm is repeated several times , It's also mixed with other code , It needs to be modified 4 A place , The overall readability has declined .

*
notes
1, Legal information ( Copyright and copyright notice )
2, Notes providing information , Function name
3, Interpretation of intention —— The intention behind a decision
4, explain
5, Warning
6,TODO notes ( List the functions to be completed in the work , Comment on completion )

*
format
1, Vertical format : Most of them are 200 That's ok , Longest 500 It is possible to construct an excellent system with a single file of rows , Although this is not an inviolable principle , We should be willing to accept it . Essays are usually easier to understand than long documents .
1.1, The name of the source file is simple , The structure of the program is divided into two parts , Read from top to bottom .
1.2, Each line of code shows a complete idea . These ideas are separated by blank lines . Each blank line is a clue , Identify new independent concepts .
1.3, If the blank line separates the concept , Close code implies a close relationship between them . therefore , Closely related code should be close to each other .
1.4, Methods related methods should be placed nearby , Avoid jumping around .
2, Horizontal format : Keep code short .
2.1, Horizontal separation and approach : Use space character to separate , No spaces in function names and left parentheses .
2.2, horizontal alignment : It's not to distance the stressed declaration variables .
2.3, indent : Highlight the sense of hierarchy
2.4, Null range : Sometimes while or for The body of the statement is empty . Empty range indent , Surround it with brackets .
2.5, Set team rules before development , indent , Named class , Variables and methods .

*
Object and data structure
1, Adding new functions without changing the existing data structure , Object oriented adding new classes without changing existing functions
2, What is Demeter's law ?
Law of Demeter - object O Of M method , Can be accessed / Call the : 1. This object has its own methods ; 2. The method that passes in the parameters of the method ; 3. The method of the object created by this method ; 4.
Methods of the object directly owned by the object ; In other words : Each unit ( Object or method ) You should have a limited understanding of other elements .
For example : Suppose I shop in a convenience store . On payment , I should have given my wallet to the cashier , Ask her to open and take out the money ? Or should I just hand her the money ?( Don't talk to strangers .)class A{ private
B b= new B(); private void methodE(){} public void methodA(C c){ D d = new D();
methodE(); //1 This object has its own methods , Callable c.print(); //2 The method that passes in the parameters of the method , Callable d.invert();
//3 The method of the object created by this method , Callable b.kill(); //4 Methods of the object directly owned by the object , Callable F f = b.getF(); f.rock();
//5 The object depends on the module of the object's implementation , Not callable . } }
3, The most refined data structure , It's a Only public variables , Classes without functions , Call the data transfer object (DTO).

* error handling
1, Use exceptions instead of return codes . Just add new ones Exception Without modifying the error code enumeration class
2, Write first try-catch-finally sentence . Preconstruction try Object scope of code block , Maintain the transaction characteristics of the scope .
3, The exception is defined according to the caller's needs, and the third party is defined API Packaging is a good practice .
4, Define the general process . Special case model : Create a mine or configure an object to handle special cases , Customers don't have to deal with abnormal behavior
5, Don't go back NULL value

Technology
©2019-2020 Toolsou All rights reserved,
JQ get request Splicing url parameter ( query criteria ) Huawei's limited old rivals benefit the most ? More and more people divide the cake ! inherit jpa Repository Write custom method query Vue Get the text and option value of the drop-down box Fiddler Simulate request sending and modifying response data SpringBoot JpaRepository Database addition, deletion, modification and query Paging tool class PageResultToastUtils Use of mysql Recursively finds all child nodes of the parent class springboot Multi profile configuration