The author | brand to cosette source | alibaba cloud native public number

background

Purpose 1.

To do a good job, sharpen your tools. For r & D students, in the daily development work, we deal with the most is the programming IDE. Being able to use the IDE efficiently and flexibly will play an important role in our work efficiency.

The two main tasks that r & D students do in development are architecture design and coding. The former mainly depends on the accumulation of a large amount of project experience and the depth of personal thinking. As the core competitiveness of R & D, it is difficult to achieve rapid results in a short period of time. The latter depends on daily coding exercises and a certain level of IDE information deficit, which can be quickly replenised and consolidated through a series of techniques described below.

The main purpose of this paper is twofold:

  • On the one hand, the IDE quick operation and efficient skills, combined with their own years of practice and understanding, a systematic summary and combing.

  • Hope that through this article, on the other hand, the systematic comb, can help more students improve the efficiency of research and development, no matter you are just starting soon, or experts with many years of development experience, believe that you can be found in this paper, a new land, so you can have more time and energy to do more meaningful things.

2. The positioning

Many technical websites and personal blogs on the Internet, IDE skills and convenient operation summed up very specific and detailed, for a single point of detail are extremely reference and learning value. But the corresponding problem is that many of these excellent articles, from different handwriting, have their own style of writing, and scattered in the scattered points of various websites, it is difficult to systematize.

My positioning of this paper is to collect and aggregate all kinds of skills in the form of large classification, so as to help us build and improve the overall knowledge system and greatly improve the development efficiency. For each classification point up to the point, instead of chewing, try to use progressive guidance.

3. The general

There are many IDES in the JetBrains family, but there are some others that are not included in the list, such as Google’s secondary development of Android Studio. Although classified as multiple product instances, the kernel of each IDE is the same, with additional language features added on top of the kernel. This article will start with one of the most used IDES – IDEA – as an example. Most of the capabilities and techniques mentioned in this article are equally applicable to other ides.

Postfix Completion

1. Introduction

Postfix Completion is a coding enhancement that adds and applies a preset code template to an expression that has already been output using a. + template Key.

The core problem is to abstract and precipitate some common code structure paradigms in the process of coding, and to wake up and reuse them in the same type of scenarios by way of. + template Key.

For example, we now need to write the following code to null-protect the name parameter:

if (name ! = null) { }Copy the code

In a normal text editor, if twice, name four times, (){}! = a total of 6 times, plus the space Tab and cursor switch, a total of 23 times.

In the IDEA editor, a total of 20 keystrokes are required without Postfix, which can be reduced to 16 without considering code formatting.

In the IDEA editor, when using Postfix, it takes only 8 times, as shown below:

In this example, you can compare the effect before and after using Postfix, which reduces the number of manual keystrokes in the code by half, and the generated code comes with its own formatting. In the actual coding process, projects vary greatly in size and complexity, but when it comes to the programming paradigm of this basic unit, they are all coherent.

With the Postfix parallel to NN in the above example, IDEA presets many other postfixes for us. The following is a review of some postfixes that are used very frequently.

Comb 2.

1) var

Quick definition of a local variable, with IDE type inference:

2) notnull

Quick NPE judgment protection:

3) nn

The same as notnull, short for this, and recommended for convenience:

4) try to catch

Add a quick try catch to the current statement, and the IDE automatically does type inference for exceptions in the catch:

5) cast

Fast type conversion, no need to repeatedly use () package and cursor switch; When used with Instanceof, it can also automatically realize the inference of cast type:

6) if

Code paradigm for fast implementation of if judgment:

7) throw

Fast implementation of throwing exceptions:

8) for

To quickly iterate over collections or arrays:

9) fori

Fast iteration with indexed values of collections or arrays; It also supports integer numbers:

Sout/soutv 10)

Fast implementation of (no parameters/with parameters) print function:

11) return

The value return logic in the fast implementation method:

12) format

Fast string formatting:

3. Advanced usage

Worried that the Postfix preset by the system is not enough to meet our coding requirements, IDEA also provides Postfix customization.

Here I use the custom code paradigm for nullating collections to illustrate the process of customizing Postfix:

  • Go to the IDE Settings screen, and then go to Editor => General => Postfix Completion => Java in the lower left corner of the panel:

  • On the pop-up page, configure as shown in the following image, then save and exit the Settings page.

Postfix isEmpty Postfix isempty Postfix isempty Postfix isempty Postfix

In real development, we can use this custom way to abstract and reuse code that can be formatted based on the expression already entered.

Let’s move on to Live Template, an IDE capability that is much like Postfix but much more flexible.

Live Template

1. Introduction

To begin with, we can look at a short coding process:

In the code above, I used the following three Template capabilities of Live Template:

  • PSFS: Defines string constants
  • Main: Adds an entry function
  • Sout: Implements log output

Here we contrast this with Postfix mentioned above, both of which provide code-level templates. Unlike Postfix, which requires an input expression and a. + Template Key to trigger, Live Template does not require either of these. It only requires a Template Key to trigger.

Live Template provides default Templates that are an order of magnitude higher than Postfix, so I won’t go through all of them here. Instead, we can go to the Settings panel and follow the path to Live Templates, as shown below:

2. Advanced usage

Like Postfix, Live Template supports custom templates, but its custom templates are relatively flexible and open, even allowing us to embed scripts directly. Due to the high flexibility of Live Template, it would take a lot of space to introduce this section alone, so I will expand my ideas from a few practical case scenarios, and I will not introduce the specific customization process in detail.

1) Key value mapping

Query the data of List structure in DB and transform it into the data of Map<K, T> structure according to the Key value mapping, so as to facilitate the subsequent data filling logic:

2) DB batch query

In the data query, we will have the request of batch DB data query according to the ID primary key, as follows:

List<User> users = userMapper.queryUserByIds(userIds);
Copy the code

One drawback of this approach is that the query becomes very time consuming when userIds are of a certain magnitude.

One solution to this problem is to split the large userIds into batches and have the batches queried asynchronously in parallel. Here we use Live Template to extract a code Template for this scenario as follows:

Following this template, our query statement would look like this:

List<User> users = batchQuery(userIds, 100, userMapper::queryUserByIds, null);
Copy the code

It can be seen that, compared with the previous, it can pass a batch size parameter, but also supports the specified asynchronous task scheduler custom configuration, and the return result is exactly the same as the previous query method, no additional external adaptation work.

3) Script implantation

This feature is the main reason I like Live Template and its flexibility and extensibility. It allows us to invoke and execute a script through a ** Template Key **, which means that our custom Live Template Template is programmable, greatly increasing the extensibility of the Template.

The single description function will be a little empty, here I combined with a practical case to introduce, we will implement a cross-computer code sharing function:

  • First, write and start a minimalist server-side application using Python’s Flask framework, providing the simplest push and pull capabilities, as follows:
from flask import Flask, request

DEFAULT = 'nothing'
code = DEFAULT

app = Flask(__name__)

@app.route('/push')
def push():
  global code
  code = request.args.get('code', DEFAULT)
  return 'Success'

@app.route('/pull')
def pull():
  return code

app.run()
Copy the code
  • Next, we will implement a code pull Template using groovy script, which uses the groovy script capabilities of Live Template, as follows:
Def url = new url (' http://127.0.0.1:5000/pull '); def conn = url.openConnection() as HttpURLConnection; def result = conn.inputStream.text; return resultCopy the code
  • Finally, we implement the template for code push as follows (the following code is passed as an input parameter through clipboard assignment) :
def code = _1; Def url = new url (' http://127.0.0.1:5000/push? code=' + new URLEncoder().encode(code)); def conn = url.openConnection() as HttpURLConnection; def result = conn.inputStream.text; return resultCopy the code

At this point, code sharing across devices is complete, so for demonstration purposes, we’ll use the People1 and People2 classes to simulate two separate computers. People1 copies a piece of its own code into the clipboard and uploads it to the Python service application by calling the push interface from the push template; People2 then uses the pull script to call the server’s Pull interface to access the code that People1 uploaded and input it into the current code editor.

The code sharing here is just a start, but there are a lot of interesting scripts we can write, such as checking the weather in the IDE, chatting through the IDE, and so on.

After introducing Live Template, we will introduce the file-level Template, File Template.

File Template

1. Introduction

File Template, as the name implies, corresponds to a File level Template. For this template, we used the script mainly for two scenarios, namely the file header and file customization. The following are the examples.

2. Customize the file header

Change the format of the file header as shown below, and the IDE will automatically generate the corresponding file comment header based on the configuration here when we create a new class or interface.

3. Abstract generic controllers

See the following code, this is a domain for the add, delete, change query interface class:

package com.alibaba.ide.code.controller; import com.alibaba.ide.code.entity.Result; import com.alibaba.ide.code.entity.User; import com.alibaba.ide.code.service.Condition; import com.alibaba.ide.code.service.UserService; import org.springframework.web.bind.annotation.*; import javax.annotation.Resource; import java.io.Serializable; import java.util.List; /** * @author puke * @version 2021/2/9 */ @RestController @RequestMapping("api/user") public class UserController { @Resource private UserService userService; @PostMapping public Result<User> create(@RequestBody User record) { User user = userService.insert(record); return Result.success(user); } @PutMapping public Result<User> update(@RequestBody User record) { User user = userService.update(record); return Result.success(user); } @DeleteMapping("{id}") public Result<Void> deleteById(@PathVariable Serializable id) { boolean success = userService.deleteById(id); return success ? Result.success() : Result.fail(); } @GetMapping("{id}") public Result<User> queryById(@PathVariable Serializable id) { User user = userService.queryById(id); return Result.success(user); } @GetMapping public Result<List<User>> queryByCondition(Condition<User> condition) { List<User> list = userService.queryByCondition(condition); return Result.success(list); }}Copy the code

A close look at this code shows that the basic structure and logic in the code can be reused if another Controller interface class corresponding to the domain is added based on this interface. This is where the File Template comes in. We define a generic Controller Template, abstract the common parts into the Template, and pass in the different parts via the Template input parameter Subject.

#set($SubjectOfLowerFirst = ${Subject.substring(0,1).toLowerCase()} + $Subject.substring(1))
package ${PACKAGE_NAME};

import com.alibaba.ide.code.entity.Result;
import com.alibaba.ide.code.entity.${Subject};
import com.alibaba.ide.code.service.Condition;
import com.alibaba.ide.code.service.${Subject}Service;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.io.Serializable;
import java.util.List;

#parse("File Header.java")
@RestController
@RequestMapping("api/${SubjectOfLowerFirst}")
public class ${Subject}Controller {

    @Resource
    private ${Subject}Service ${SubjectOfLowerFirst}Service;

    @PostMapping
    public Result<${Subject}> create(@RequestBody ${Subject} record) {
        ${Subject} ${SubjectOfLowerFirst} = ${SubjectOfLowerFirst}Service.insert(record);
        return Result.success(${SubjectOfLowerFirst});
    }

    @PutMapping
    public Result<${Subject}> update(@RequestBody ${Subject} record) {
        ${Subject} ${SubjectOfLowerFirst} = ${SubjectOfLowerFirst}Service.update(record);
        return Result.success(${SubjectOfLowerFirst});
    }

    @DeleteMapping("{id}")
    public Result<Void> deleteById(@PathVariable Serializable id) {
        boolean success = ${SubjectOfLowerFirst}Service.deleteById(id);
        return success ? Result.success() : Result.fail();
    }

    @GetMapping("{id}")
    public Result<${Subject}> queryById(@PathVariable Serializable id) {
        ${Subject} ${SubjectOfLowerFirst} = ${SubjectOfLowerFirst}Service.queryById(id);
        return Result.success(${SubjectOfLowerFirst});
    }

    @GetMapping
    public Result<List<${Subject}>> queryByCondition(Condition<${Subject}> condition) {
        List<${Subject}> list = ${SubjectOfLowerFirst}Service.queryByCondition(condition);
        return Result.success(list);
    }
}
Copy the code

Now that the template is defined, let’s see what it looks like in action:

Using Goods as the new domain object, you can see that the generated Controller code already has all the capabilities of UserController, and the generated code is all Goods related apis. This enables horizontal migration of the File Template.

Low frequency efficient shortcut keys

1. Introduction

There are hundreds of shortcut keys in IDEA, and it is hard to remember them all clearly. There are also many corresponding summaries on the Internet. Here I’m going to sort out some of the shortcuts that you use that are relatively low frequency, but very efficient.

Comb 2.

1) Select the repeating element: Control + G

In general, you can use Shift + F6 to make bulk changes to class, method, and variable names, but this shortcut is particularly useful for bulk changes to other elements in all programming languages.

2) Batch box selection: Option + left mouse button drag

There is no optimal solution for batch changes to “aligned” code:

3) Whole line movement: Option + Shift + ↑/↓

Quickly adjust the code execution order, eliminating the tedious cut-and-paste process:

4) Full line/block copy: Command + D

For full line/block copy, efficiency is much higher than pure manual copy and paste:

Or Command + Shift + +/-

The former, quickly show/hide the current method body; The latter gives a quick overview of all the methods of the current class:

6) Modify method signature: Command + F6

This is extremely efficient when methods are called from multiple files or places:

7) View the history clipboard: Command + Shift + V

The PC’s default clipboard can only save one text. This feature is designed to address this pain point:

8) Code extraction

Code extraction is mainly used in code reconstruction to achieve the purpose of extracting a variable and method at the fastest speed.

  • Extract local variables: Command + Option + V

  • Select member variables: Command + Option + F

  • Static constants: Command + Option + C

  • Method input parameters: Command + Option + P

  • Command + Option + M

Code debugging

Code debugging is used a lot in development, and the general one-step, multi-step, in-and-out operations are not specified here.

It is worth mentioning that conditional breakpoints are used to implement run-time code breakpoints, as shown below:

As you can see, when running in Debug mode, we can dynamically change the value of the age variable and output 10 instead of 20.

This is a function I accidentally found in the development, which is a Trick. But this feature is especially useful in real-world development scenarios where some code changes are costly to run again. For example, during Android development, you can dynamically change the style of each element in the page, the request of the interface, the content of the data, and so on, without rearranging the whole package. In the server scenario, if the application supports the Debug mode, the application can dynamically change the context logic without redeployment.

Write in the last

Small steps to a thousand miles, small streams into rivers and seas, development work has size, business needs are urgent, but it will eventually fall to the present, starting from a brick by brick cornerstone, starting from a row of coding, I hope this article can help more research and development students.