程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Programming language-11-eight honors and Eight Disgraces in programming and the honor and Disgrace View in Python

編輯:Python

Eight honors and eight disgraces of the programmer version ~
Python: programming “ Eight honors and eight disgraces ”

1 General version

1.1 Proud of interface compatibility , Shame on the interface running naked

One 、 Proud of interface compatibility , How do you understand that
quite a lot bug All because of the modification External old interface , But not because of compatibility . Most of the key problems are serious , May directly lead to System Publishing failure . It's easy for novice programmers to make this mistake . So we When modifying the old interface , Generally, it is necessary to be compatible .

If your requirements are modified on the original interface , Especially if this interface is to provide services to the outside world , Be sure to consider interface compatibility . Let's give you an example , such as dubbo Interface (Dubbo It is a high-performance and excellent service framework of Alibaba open source , Enables applications to pass high-performance RPC Realize the output and input functions of services , You can talk to Spring Seamless integration of framework ), Originally, it only received A,B Parameters , Now you add a parameter C, We can consider this way of handling :

// Old interface
void oldService(A,B){

// Compatible with new interface , Send a null Instead of C
newService(A,B,null);
}
// The new interface , The old interface cannot be deleted for the time being , Need to be compatible .
void newService(A,B,C){

...
}

Two 、 We should also be ashamed of the interface streaking .
To ensure the security of interface message , Reject interface message streaking . therefore , We can use https agreement , It is also recommended to add a signature for the interface , Data encryption, etc .

Interface signing is simple , Is to request relevant information from the interface ( Request message , Include request timestamp 、 Version number 、appid etc. ), Client private key signature , Then the server verifies the signature with the public key , It is considered legal only after passing the verification 、 A request that has not been tampered with by an intermediary .

1.2 Take pride in standardizing the log , Shame on typing logs

Our business logic code needs Log escort . such as : You realize the transfer business , Turn a few million , Then it failed , Then the customer complains , And then you haven't printed it into the Journal , Think about the deep and hot predicament , You have no way .

So everyone should keep a good diary , For example, the log level is used properly , Log format , Where to log , Parameter which to print, etc etc. . Don't make random logs , Take pride in standardizing the log , It's a shame to make a random diary .

1.3 Proud of code self-test , Shame on overconfidence

Modify the code , I need to test myself , This is a must for every programmer , Even if you just change a variable or a field .

Put an end to overconfidence , In particular, do not have such a fluke mentality : I just changed a variable or I just changed one line of configuration code , Don't test yourself , How could there be a problem .

1.4 Proud of parameter verification , Shame on running exceptions

Parameter checking It is a basic quality that every programmer must have . Your way of dealing with , Parameters must be verified first . For example, whether the input parameter is allowed to be empty , Whether the input length meets your expected length . therefore , We should be proud of parameter verification .

For example, your database table field is set to varchar(16), The other side passed a 32 Bit string over here , If you don't check the parameters , Inserting into the database directly caused an exception .

We should be ashamed of runtime exceptions .

For example, you didn't do some non empty checks , Array boundary verification, etc , Null pointer exception caused by 、 Array boundary exception , Especially if these run-time exceptions still occur in the production environment , In the eyes of experienced programmers , These misbehaviors can be particularly low-level .

1.5 Take pride in design patterns , Shame on code repetition

On a daily basis , We should be proud of the design pattern .

such as The strategy pattern 、 Factory mode 、 Template method pattern 、 Observer mode 、 The singleton pattern 、 Chain of responsibility pattern and so on , They are very common . In the right business scenario , Let's use design patterns . Design patterns can make our code more elegant 、 More extensible . But don't over design , Don't apply design patterns .

We are also ashamed of repeating the code . Duplicate code , I believe every programmer hates it , Especially sometimes your development tools will prompt you . We Public methods can be extracted , Extract common variables 、 Extend inheritance classes to eliminate duplicate code .

1.6 Take pride in optimizing your code , Shame on copy and paste

Daily development , Many programmers implement a function , If you see that the old code has similar functions , They love copying and pasting . This can easily lead to duplicate code , So we should be ashamed of copying and pasting .

It is generally recommended to add your own thinking , How to optimize this part of the code , How to extract public methods , What design patterns to use, etc .

Personally feel , The process of optimizing code , You can make greater progress . So we should be proud to optimize the code , Shame on copy and paste .

1.7 Proud to define constants , Shame on magic numbers

In our daily work , Do you often see magic numbers . Magic number (Magic Number) It means having a special meaning , But it can not clearly show the meaning of the numbers .

There are magic numbers in the program , Poor legibility , And very difficult to maintain .

if(type==1){

System.out.println(" Official account : A little boy picking up snails ");
}else if(type==2){

System.out.println(" Official account : Programmer snail ");
}else{

System.out.println(" Pay attention to other official account numbers ");
}

In code 1、2 It means magic numbers , We You can replace magic numbers with constants , Or define enumerations to replace magic numbers .

1.8 Take pride in summarizing and thinking , It is a shame to fish in troubled waters

For example, after you read brother Tianluo's article , You can sum up and think about , Or take notes , Or put it in your favorites , Take a look after dinner .

Another example is in your daily work , See a good piece of code , You can also think about the highlights , If you write it yourself , How to write better code . Anyway How to summarize , Think more , Review more , Review the old and learn the new .

We should be ashamed of fishing in troubled waters . For example, at work , Some friends like to fish in troubled waters , When a monk strikes a clock one day , The code is mostly copy and paste , Fish when you need it . In fact, this is not desirable .

We should grow in our work , By working hard , Make yourself more , In the future, you can get a higher salary by changing jobs , Right , Come on! , Young man , Take pride in summarizing and thinking , It is a shame to fish in troubled waters .

2 python edition

​ Take pride in hands-on practice , It's a shame not to practice .
Take pride in printing logs , Shame on one-step tracking .
Proud to be separated by white space , Shame on tabulating .
Take pride in unit testing , Shame on testing by hand .
Take pride in code reuse , Shame on copy and paste .
Take pride in polymorphic applications , Shame on the branch .
With Pythonic take as an honor , Shame on redundancy and procrastination .
Take pride in summarizing and thinking , To be ashamed of not asking for understanding .

2.1 Take pride in hands-on practice , It's a shame not to practice

【 Time is the only test of truth 】 For programming , This is absolutely the truth of truth , This is true of any programming language learning . Do it yourself , compile 、 Debug it , Find the error , correct , Print out , To have a deeper understanding of the details of the language .

Many things seem simple , It may not be the same thing to do . therefore , Hands on , necessary . also , Do it again , It can also deepen the impression and understanding , Just watch and forget without practicing for a while .

2.2 Take pride in printing logs , Shame on one-step tracking

Different people have different opinions , For a mature software , Logging is the most basic . But in the process of development , It is not a very good way to analyze only through logs , Usually single step tracking and periodic printing of logs , It can find out the cause of the error and the way to correct it more quickly , Especially remember the hints of reference errors , Can help us make changes faster .

2.3 Proud to be separated by white space , Shame on tabulating

PEP 8 – Style Guide for Python Code
stay PEP 8 in Tabs or Spaces? In a column , Introduction to :
Spaces are the preferred indentation method.
Space is the preferred indentation method .

Tabs should be used solely to remain consistent with code that is already indented with tabs.
Tabs should only be used to align with code that has already used tab indents .

Python 3 disallows mixing the use of tabs and spaces for indentation.
Python 3 Do not mix tabs and spaces in indents .

Suggest : Coding at ordinary times , take TAB Chain set to 4 A space , A lot of IDE Or the editor has this option , So this tool can help us solve . I often make mistakes about this problem , After all TAB Keys are really more convenient than typing four spaces .

2.4 Take pride in unit testing , Shame on testing by hand

【 I haven't done much code testing , This sentence quotes the answer of the great God on the Internet 】 I don't think this sentence is well written , The manual test definition here is not clear , Unit test individuals typically use single step tracking , This cannot be separated from manual work , The opposite is automated testing , I understand if what is said here is TDD( Test Driven Development in agile ). don't quite understand .

2.5 Take pride in code reuse , Shame on copy and paste

This truth , Copy and paste can easily cause a lot of redundant code , Using code is getting harder and harder to maintain . for example :

from label_detect import classify_face

The above sentence means from label_detect.py Medium multiplexing classify_face This function , This is supportive .

take def classify_face to copy It's time to .py Next , Is code copying . This needs to be changed later classify_face The definition of , You need to modify several places , This way is not advisable .

2.6 Take pride in polymorphic applications , Shame on the branch

Polymorphism means that functions with different functions can use the same function name , In this way, you can use a function name to call functions with different contents . In object-oriented method, polymorphism is usually expressed in this way : Send the same message to different objects , Different objects have different behaviors when they are received ( That is the method ).

in other words , Each object can respond to a common message in its own way . The so-called news , Call function , Different behavior means different realization , That is, to perform different functions .

import abc
class Animal(metaclass=abc.ABCMeta): # The same thing : animal 
@abc.abstractmethod
def talk(self):
pass
class Cat(Animal): # One of the forms of animals : cat 
def talk(self):
print('say miaomiao')
class Dog(Animal): # The second form of animals : Dog 
def talk(self):
print('say wangwang')
class Pig(Animal): # The third form of animals : The pig 
def talk(self):
print('say aoao')

In a function , If we receive a variable obj, Then no matter what obj yes Cat、Dog still Pig, Can be executed talk The action of :

def func(obj):
obj.talk()
c = Cat()
d = Dog()
p = Pig()
func(c)
func(d)
func(p)
Running results :
>>> say miaomiao
>>> say wangwang
>>> say aoao

The benefits of polymorphism :
(1) Added program flexibility , Maintaining the status quo , No matter how diverse the objects are , Users are all in the same form to call , Such as func(obj)
(2) Added program Extensibility , By inheritance animal Class creates a new class , Users do not need to change their own code , Or use it func(obj) To call

Look at the branch judgment statement , There are several kinds :

 A single if structure
if-else structure
if-elif-else structure
if Nested structure

Corresponding to the above polymorphism , It just needs to be judged animal Different types of ,print Different talk.

2.7 With Pythonic take as an honor , Shame on redundancy and procrastination

What is? Pythonic Well , The central idea is as follows : Simple 、 Clear , Don't overemphasize skill , Use as much as possible Python Functions already provided and conform to Python Way of thinking .

for example :C In language , Exchange two numbers a,b, The following operations are required :

t=a;
a=b;
b=t;

Judge the numbers a Whether to be in (c,d) Within the interval , need :

if(a>c && a<d):

And in the Python in , Just do it :

a,b = b,a
if(c<a<d):

2.8 Take pride in summarizing and thinking , To be ashamed of not asking for understanding

Truth in truth , Not just programming , Everything should be like this .


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved