当前位置:网站首页>How can programmers improve the speed of code writing?
How can programmers improve the speed of code writing?
2022-07-04 16:50:00 【Dafang teacher talks about SCM】
How can programmers improve the speed of code writing ?
Don Roberts A reconstruction criterion is proposed : The first time you do something, just do it ; The second time you do something like that, you're going to get disgusted , But you can do it anyway ; The third time you do something like that , You should reconstruct .
So is coding , When writing similar code many times , We need to consider whether there is a way to improve the encoding speed , Make coding speed “ take off ”? Chenchangyi, a technical expert of Gaode map ( Common sense ) For many years, I have been committed to agile development , A set of coding methodology is summarized , Help programmers " Fast 、 High quality 、 Efficient " To encode more efficiently .
Method 1: Code by hand
Most just learn Java The programmer , With a sense of ritual of reverence , Type the following code on the development tool word for word :
public class Test {
public static void main(String[] args) {
System.out.println("Hello world!");
}
}
you 're right , This is the classic "Hello world", This is the first program most people write by hand .
Code by hand , It can reflect the basic quality of a programmer . There are many companies , They all take computer programming test as one of the important means of interview . The interviewers need to follow the requirements of the topic , Choose a familiar programming tool ( such as Eclipse), Manually write code and debug run through . In the whole process , You can't search for answers through the Internet , Unable to view online help documentation , The interviewer is required to write the code by hand , It is mainly about the ability of interviewers to write code by hand —— grammar 、 function 、 Logic 、 thinking 、 Algorithm and hands-on ability .
Code by hand , Is a good programmer must have the basic ability . Writing code by hand is like writing an article , Grammar is the way to choose words and make sentences 、 Functions are the words that make up an article 、 The class library is the anecdote according to the classics 、 Architecture is the style of writing 、 Function is the theme of writing 、 Algorithm is the logic of organizing language …… therefore , As long as you master the grammar of a programming language 、 Learn a bunch of basic class library functions 、 Reference some required third-party class libraries 、 Choose a mature and stable architecture 、 Define the function of the product requirements 、 Pick an algorithm to implement logic …… Writing code by hand is as easy as writing an article .
Method 2: Copy and paste code
As the saying goes :" Familiar with 300 tang poems , You can sing even if you can't write a poem ." The same goes for coding , The first step in coding is to imitate , In a nutshell " Copy the code "—— Copy and paste code . Copy and paste code is an art , With good coding, you can get twice the result with half the effort . however , Things that haven't been tested , After all, we can't believe it all . When you see the code you need , Before you copy and paste , We all need to read it carefully 、 Think seriously about 、 Detailed screening …… A lot of things , Different people have different opinions 、 What a wise man sees , Suitable for other scenes, but not necessarily for your scene . As a qualified programmer , We must not blindly " si ".
1. Why copy and paste code
· Copy and paste existing code , Can save development time ;
· Copy and paste stable code , It can reduce the risk of system failure ;
· Copy and paste network code , You can turn other people's achievements into your own .
2. Copy and paste code brings problems
· How well do you understand the copied code ? Whether the implementation logic is reasonable ? Can it run stably ? How many potential Bug?
· How many times has this code been copied and pasted in the project ? according to “ Three refactorings ” principle , Do you need to refactor the same code ?
· The more code is copied and pasted , The more code maintenance problems it brings . Changes and fixes to multiple code versions , To keep the code in sync , You have to make the same changes everywhere , Increased maintenance costs and risks .
All in all , Copy and paste code , Just like other coding methods , There is no right or wrong . It's just a way , You can make good use of , It can also be abused . If we use copy and paste , We have to be responsible for the results .
Method 3: Replace the generated code with text
1. Generate code samples
User query related code has been written :
/** Query user service function */
public PageData queryUser(QueryUserParameterVO parameter) {
Long totalCount = userDAO.countByParameter(parameter);
List userList = null;
if (Objects.nonNull(totalCount) && totalCount.compareTo(0L) > 0) {
userList = userDAO.queryByParameter(parameter);
}
return new PageData<>(totalCount, userList);
}
/** Query user controller functions */
@RequestMapping(path = "/queryUser", method = RequestMethod.POST)
public Result<>> queryUser(@Valid @RequestBody QueryUserParameterVO parameter) {
PageData pageData = userService.queryUser(parameter);
return Result.success(pageData);
}
If we want to write company query related code , Its code form is similar to user query , Sort out the replacement relationship as follows :
· hold " user " Replace with " company ";
· hold "User" Replace with "Company";
· hold "user" Replace with "company".
utilize Notepad、EditPlus Wait for the text editor , Choose case sensitive , Replace with plain text , The final result is as follows :
/** Query company service function */
public PageData queryCompany(QueryCompanyParameterVO parameter) {
Long totalCount = companyDAO.countByParameter(parameter);
List companyList = null;
if (Objects.nonNull(totalCount) && totalCount.compareTo(0L) > 0) {
companyList = companyDAO.queryByParameter(parameter);
}
return new PageData<>(totalCount, companyList);
}
/** Query company controller function */
@RequestMapping(path = "/queryCompany", method = RequestMethod.POST)
public Result<>> queryCompany(@Valid @RequestBody QueryCompanyParameterVO parameter) {
PageData pageData = companyService.queryCompany(parameter);
return Result.success(pageData);
}
Using text substitution to generate code , The whole code generation time will not exceed 1 minute .
2. The main advantages and disadvantages
The main advantages :
· Generating code is faster .
Main drawback :
· You have to write sample code ;
· Only for text replacement scenarios .
Method 4: use Excel Formula generation code
Excel The formula is very powerful , Can be used to write some formulaic code .
1. utilize Excel Formulas generate model classes
from WIKI Copy the interface model definition to Excel in , The sample data is as follows :
To write Excel The formula is as follows :
= "/** "&D6&IF(ISBLANK(F6), "", "("&F6&")")&" */ "&IF(E6 = " no ", IF(C6 = "String", "@NotBlank", "@NotNull"), "")&" private "&C6&" "&B6&";"
The code generated by the formula is as follows :
/** User ID */ @NotNull private Long id;
/** User name */ @NotBlank private String name;
/** User's gender (0: Unknown ;1: male ;2: Woman ) */ @NotNull private Integer sex;
/** User description */ private String description;
Create model classes , The code is as follows :
/** user DO class */
public class UserDO {
/** User ID */
@NotNull
private Long id;
/** User name */
@NotBlank
private String name;
/** User's gender (0: Unknown ;1: male ;2: Woman ) */
@NotNull
private Integer sex;
/** User description */
private String description;
......
}
2. utilize Excel Formulas generate enumeration classes
from WIKI Copy enumeration defined to Excel in , The sample data is as follows :
To write Excel The formula is as follows :
="/** "&D2&"("&B2&") */"&C2&"("&B2&", """&D2&"""),"
The code generated by the formula is as follows :
/** empty (0) */NONE(0, " empty "),
/** male (1) */MAN(1, " male "),
/** Woman (2) */WOMAN(2, " Woman "),
Create enumeration class , The code is as follows :
/** User gender enumeration */
public enum UserSex {
/** Enumeration Definition */
/** empty (0) */
NONE(0, " empty "),
/** male (1) */
MAN(1, " male "),
/** Woman (2) */
WOMAN(2, " Woman ");
......
}
3. utilize Excel Formulas generate database statements
use Excel The list of companies sorted out is as follows , It needs to be organized into SQL Statement directly into the database :
To write Excel The formula is as follows :
= "('"&B2&"', '"&C2&"', '"&D2&"', '"&E2&"'),"
Use formulas to generate SQL as follows :
(' Gao de ', ' Shoukai building ', '(010)11111111', '[email protected]'),
(' Alibaba cloud ', ' Green Center ', '(010)22222222', '[email protected]'),
(' rookie ', ' Ali Center ', '(010)33333333', '[email protected]'),
add to into Statement header , Arrangement SQL as follows :
insert into t_company(name, address, phone, email) values
(' Gao de ', ' Shoukai building ', '(010)11111111', '[email protected]'),
(' Alibaba cloud ', ' Green Center ', '(010)22222222', '[email protected]'),
(' rookie ', ' Ali Center ', '(010)33333333', '[email protected]');
4. The main advantages and disadvantages
The main advantages :
· Code generation for tabular data ;
· After writing the formula , Drag and drop to generate code , Faster generation .
Main drawback :
· Not suitable for code generation of complex functions .
Method 5: Generate code with tools
Generate code with tools , As the name suggests, it is to use existing tools to generate code . Many development tools provide tools to generate code , such as : Build constructor , Overloading base classes / The interface function , Generate Getter/Setter function , Generate toString function …… Can avoid a lot of hand code . There are also some code generation plug-ins , You can also generate code that meets some application scenarios .
Here we use mybatis-generator Plug in generated code as an example , Describes how to use tools to generate code .
1. Install and run the plug-in
The specific method will not be repeated here , Search for documents on the Internet by yourself .
2. Generate code samples
| 2.1. Generate model class code
file User.java Content :
......
public class User {
private Long id;
private String user;
private String password;
private Integer age;
......
}
| 2.2. Generate mapping interface code
file UserMapper.java Content :
......
public interface UserMapper {
User selectByPrimaryKey(Long id);
......
}
| 2.3. Generate mapping XML Code
file UserMapper.xml Content :
......
id, user, password, age
select
from test_user
where id = #{id,jdbcType=BIGINT}
......
3. The main advantages and disadvantages
The main advantages :
· Using the generated code plug-in , Generating code is faster ;
· Using the plug-in configuration file , Control the generation of desired function code .
Main drawback :
· It takes time to study and familiarize yourself with the use of the generated code plug-in ;
· The generated code does not necessarily meet the code specification , Code compliance is required after each generation ;
· After regenerating the code , Easy to override custom code ( It is recommended to maintain a separate generated code base , adopt DIFF Tools compare code differences , Then assign the value and paste the difference code ).
Method 6: Generate code from code
Generate code from code , Just write your own code , Generate code in your own format . below , To generate data based on MyBatis Database access code for example .
1. Query form information
First , We need to get the table and column information we need to generate code from the database .
| 1.1. Query table information
Query table information statement :
select t.table_name as ' The name of the table '
, t.table_comment as ' fpt '
from information_schema.tables t
where t.table_schema = ?
and t.table_type = 'BASE TABLE'
and t.table_name = ?;
among , The first 1 A question mark is assigned to the database name , The first 2 A question mark assignment table name .
Query table information results :
| 1.2. Query column information
Query column information statement :
select c.column_name as ' Column name '
, c.column_comment as ' Column remarks '
, c.data_type as ' data type '
, c.character_maximum_length as ' Character length '
, c.numeric_precision as ' Digital precision '
, c.numeric_scale as ' The range of numbers '
, c.column_default as ''
, c.is_nullable as ' Could you empty '
, c.column_key as ' Column key name '
from information_schema.columns c
where c.table_schema = ?
and c.table_name = ?
order by c.ordinal_position;
among , The first 1 A question mark is assigned to the database name , The first 2 A question mark assignment table name .
Query column information results :
2. Write the generated code
| 2.1. Write code to generate model classes
/** Generate model class file function */
private void generateModelClassFile(File dir, Table table, List columnList) throws Exception {
try (PrintWriter writer = new PrintWriter(new File(dir, className + "DO.java"))) {
String className = getClassName(table.getTableName());
String classComments = getClassComment(table.getTableComment());
writer.println("package " + groupName + "." + systemName + ".database;");
......
writer.println("/** " + classComments + "DO class */");
writer.println("@Getter");
writer.println("@Setter");
writer.println("@ToString");
writer.println("public class " + className + "DO {");
for (Column column : columnList) {
String fieldType = getFieldType(column);
String fieldName = getFieldName(column.getColumnName());
String fieldComment = getFieldComment(column);
writer.println("\t/** " + fieldComment + " */");
writer.println("\tprivate " + fieldType + " " + fieldName + ";");
}
writer.println("}");
}
}
| 2.2. Write build DAO Interface code
/** Generate DAO Interface file function */
private void generateDaoInterfaceFile(File dir, Table table, List columnList, List pkColumnList) throws Exception {
try (PrintWriter writer = new PrintWriter(new File(dir, className + "DAO.java"))) {
String className = getClassName(table.getTableName());
String classComments = getClassComment(table.getTableComment());
writer.println("package " + groupName + "." + systemName + ".database;");
......
writer.println("/** " + classComments + "DAO Interface */");
writer.println("public interface " + className + "DAO {");
writer.println("\t/** obtain " + classComments + " function */");
writer.print("\tpublic " + className + "DO get(");
boolean isFirst = true;
for (Column pkColumn : pkColumnList) {
if (!isFirst) {
writer.print(", ");
} else {
isFirst = false;
}
String fieldType = getFieldType(pkColumn);
String fieldName = getFieldName(pkColumn.getColumnName());
writer.print("@Param(\"" + fieldName + "\") " + fieldType + " " + fieldName);
}
writer.println(");");
......
writer.println("}");
}
}
| 2.3. Write build DAO Mapping code
/** Generate DAO Mapping file functions */
private void generateDaoMapperFile(File dir, Table table, List columnList, List pkColumnList) throws Exception {
try (PrintWriter writer = new PrintWriter(new File(dir, className + "DAO.xml"))) {
String className = getClassName(table.getTableName());
String classComments = getClassComment(table.getTableComment());
writer.println("");
......
writer.println("");
writer.println("");
writer.println("\t");
writer.println("\t");
if (CollectionUtils.isNotEmpty(columnList)) {
boolean isFirst = true;
String columnName = getColumnName(pkColumn.getColumnName());
for (Column column : columnList) {
if (isFirst) {
isFirst = false;
writer.println("\t\t" + columnName);
} else {
writer.println("\t\t, " + columnName);
}
}
}
writer.println("\t");
writer.println("\t");
writer.println("\t");
writer.println("\t\tselect");
writer.println("\t\t");
writer.println("\t\tfrom " + table.getTableName());
boolean isFirst = true;
for (Column pkColumn : pkColumnList) {
String columnName = getColumnName(pkColumn.getColumnName());
String fieldName = getFieldName(pkColumn.getColumnName());
writer.print("\t\t");
if (isFirst) {
writer.print("where");
isFirst = false;
} else {
writer.print("and");
}
writer.println(" " + columnName + " = #{" + fieldName + "}");
}
writer.println("\t");
writer.println("");
}
}
3. Generate relevant code
| 3.1. Generated model class code
/** Organizing companies DO class */
@Getter
@Setter
@ToString
public class OrgCompanyDO {
/** Company logo */
private Long id;
/** Corporate name */
private String name;
/** Contact address */
private String address;
/** Company description */
private String description;
}
| 3.2. Generated DAO Interface code
/** Organizing companies DAO Interface */
public interface OrgCompanyDAO {
/** Get the organization company function */
public OrgCompanyDO get(@Param("id") Long id);
}
| 3.3. Generated DAO Mapping code
id
, name
, address
, description
select
from org_company
where id = #{id}
3. The main advantages and disadvantages
The main advantages :
· The code format can be customized , Ensure that generated code is compliant ;
· Code functions can be customized , Just generate the code you need ;
· After the previous code precipitation , It can be used directly later .
Main drawback :
· We need to study the data sources , Make sure you get the data you need to generate the code ;
· You need to build a data model 、 Write the generated code , It takes a long time .
The ultimate solution : Nothing beats nothing
The ultimate way to code , Is it right to say demand directly to the computer , Then the computer generates the code automatically ? After the development of science and technology to a certain level in the future , This may come true . however , At present, this situation is unrealistic . In reality , Want to do it " A big one 、 The code is coming ", Unless you're the boss 、 Product manager or technology manager .
The ultimate way to code is “ Nothing beats nothing ”," No move " It's not that I don't pay attention to " movements in martial arts or traditional opera ", It's not sticking to one " movements in martial arts or traditional opera ", Come up with the right " movements in martial arts or traditional opera " It is advisable to . The various coding methods listed in this paper , There is no difference between high and low , It's only appropriate to say . therefore , Flexible use of various coding methods , It's the ultimate way to code .
Code normalization
In the above coding methods , Many methods require manual sample code . If your code doesn't follow the code specifications , It's hard to find commonalities between codes , And abstract the sample code that can be used as a standard ; If the standard sample code does not meet the code specification , Inevitably, the generated code does not meet the code specification , So these irregularities were magnified ten times 、 A hundred or even a thousand times . therefore , Code normalization is the top priority of coding .
边栏推荐
- Four point probe Industry Research Report - market status analysis and development prospect prediction
- Go语言循环语句(第10课下)
- Hidden communication tunnel technology: intranet penetration tool NPS
- Cut! 39 year old Ali P9, saved 150million
- Can I "reverse" a Boolean value- Can I 'invert' a bool?
- What is the catalog of SAP commerce cloud
- Model fusion -- stacking principle and Implementation
- DIY a low-cost multi-functional dot matrix clock!
- Overflow: the combination of auto and Felx
- The content of the source code crawled by the crawler is inconsistent with that in the developer mode
猜你喜欢
What is torch NN?
Position encoding practice in transformer
What is the catalog of SAP commerce cloud
QT graphical view frame: element movement
PR FAQ: how to set PR vertical screen sequence?
Common knowledge of unity Editor Extension
[Previous line repeated 995 more times]RecursionError: maximum recursion depth exceeded
Detailed process of DC-2 range construction and penetration practice (DC range Series)
Opencv learning -- geometric transformation of image processing
Penetration test --- database security: detailed explanation of SQL injection into database principle
随机推荐
[Chongqing Guangdong education] National Open University spring 2019 1248 public sector human resource management reference questions
Overview of convolutional neural network structure optimization
Will the memory of ParticleSystem be affected by maxparticles
[North Asia data recovery] a database data recovery case where the disk on which the database is located is unrecognized due to the RAID disk failure of HP DL380 server
Array filter fliter in JS
Accounting regulations and professional ethics [11]
Expression #1 of ORDER BY clause is not in SELECT list, references column ‘d.dept_ no‘ which is not i
Filtered off site request to
AutoCAD - set color
Preliminary practice of niuke.com (10)
Intranet penetrating FRP: hidden communication tunnel technology
如何为ONgDB核心项目源码做贡献
Position encoding practice in transformer
Communication mode based on stm32f1 single chip microcomputer
c# 实现定义一套中间SQL可以跨库执行的SQL语句
C language: implementation of daffodil number function
最大子数组与矩阵乘法
高度剩余法
.Net 应用考虑x64生成
对人胜率84%,DeepMind AI首次在西洋陆军棋中达到人类专家水平