Things to note for newcomers to write readable code during Java development

Introduction

As a university and graduate student, I was involved in Java for the first time after joining the company. After training for newcomers, I have only one and a half years of Java development experience, so I would like to share the points to be aware of when writing source code in the projects I have participated in, and the points pointed out in the review.

Make class names, method names, and variable names easy to understand

① Follow the existing source code naming convention

The projects I have been involved in for the past year and a half are mostly the creation of new functions or batch creation of existing systems. Before creating a new class, it is important to first read the existing source code to understand the naming rules. For now, read the existing code before you get started!

Example: OldProductDeleteBatch.java ⇒ Existing `` `CampaignFileStopBatch.java``` ⇒ New

The naming rule is noun + verb + Batch.

② Make the variable name easy to understand even if it is long

errorAndmessageAndidThe variable names are short, but if you think about it carefully, you won't get any information. What error? What kind of message? Where id? No one knows except the person who wrote it.

More specifically `FormatError```, if there is a format display error For warning messages, ``` warningMessage```, File ID `fileId``` Let's write.

③ Try to write correct English

Of course, there are people who are not good at English, but I think that correct English is necessary to convey the intention correctly to those who read the source code.

For example: ① Boolean variable that determines if the file exists boolean fileexist ⇒boolean fileexists

② Variable to store the campaign file ID string campignfileid ⇒ string campaignfileid

Write comments positively

For veteran engineers, it may be better not to write comments frequently, but I think it is better for beginners to write positively.

At the beginning, the processing contents were listed in comments as shown below, and the code was written after grasping the whole picture. I think we can sort out what to do in this way.

comment.java


/*--------------------------------------------------------------------------------------------------------------
Examine each line of the uploaded TSV file
	0.id		1.Name 2.Student number
						
* The student ID number listed in the TSV file is the DB number int._number

If an error occurs, call the following method to put the error message line by line in the sheet
・ AddErrorRow():If all data is null
・ AddStudentErrorRow(): If the school registration information is in error
--------------------------------------------------------------------------------------------------------------*/
for(){
    //Write specific processing
}

And one more thing, as an engineer, I often forget what I wrote over time. In this case, if you have a comment, you can understand the contents of the source code immediately.

Write similar processes together

While creating some batch processes, I noticed that I wrote a similar process.

For example, the process of creating the following Excel sheet:

ExcelFormat.java


    public static Workbook newWorkbook(){
		Workbook newWorkbook = new SXSSFWorkbook();
		
		CellStyle styleHeaderLabel = null;
		CellStyle styleHeaderValue = null;
		CellStyle styleHeaderValue = null;
		
		DataFormat format = newWorkbook.createDataFormat();
		
		//font settings
		Font font = newWorkbook.createFont();
		font.setFontName("MS gothic");
		font.setFontHeightInPoints((short)9);
		
		//Formatting for header string display
		styleHeaderLabel = newWorkbook.createCellStyle();
		styleHeaderLabel.setBorderBottom(CellStyle.BORDER_THIN);
		styleHeaderLabel.setBorderTop(CellStyle.BORDER_THIN);
		styleHeaderLabel.setBorderLeft(CellStyle.BORDER_THIN);
		styleHeaderLabel.setBorderRight(CellStyle.BORDER_THIN);
		styleHeaderLabel.setFillForegroundColor(HSSFColor.LIGHT_CORNFLOWER_BLUE.index);
		styleHeaderLabel.setFillPattern(CellStyle.SOLID_FOREGROUND);
		styleHeaderLabel.setVerticalAlignment(CellStyle.VERTICAL_TOP);
		styleHeaderLabel.setWrapText(true);
		styleHeaderLabel.setFont(font);
		
		addHeader(newWorkbook);
		
		return newWorkbook;
	}
	
	public static void addHeader(Workbook workbook){
		//Initialize the sheet and set the name of the sheet
		Sheet mainSheet = workbook.createSheet();
		mainSheet.createFreezePane(0, 1);
		workbook.setSheetName(SHEET_NO, SHEET_NAME);

		int colNumber = 1;
		int rowNumber = 1;
		Row row = mainSheet.createRow(rowNumber);
		Cell cell = null;
		CellStyle styleHeaderLabel = workbook.getCellStyleAt((short)(workbook.getNumCellStyles()-3));

		//Insert header
		for(String headerName : HEADER_LIST){
			cell = row.createCell(colNumber++);
			cell.setCellStyle(styleHeaderLabel);
			cell.setCellType(Cell.CELL_TYPE_STRING);
			cell.setCellValue(headerName);
		}

		int maxColNumber = 0;

		//Adjust the size of the column
		for(int i = 1; i < colNumber; i++) {
			mainSheet.setColumnWidth(i, 5000);
			maxColNumber = i;
		}

		//Set the header line to autofilter
		mainSheet.setAutoFilter(new CellRangeAddress(1,1,1,maxColNumber));
	}

Actually, there are quite a few similar processes in batch processing, and if you group them into one class and standardize the processing, the source code will be shorter and readability will be improved. When there are two or more similar processes in your source, think about "whether this process can be shared" or "whether it can be summarized somewhere".

Let's write with high independence

Take a look at the source code below.

file.java


for(int i=0;i<file.arrtibuteSize();i++){
    if("00000000".equals(file.getAttribute(i).getId()) && !file.getAttribute(i).getValue().isEmpty()){
         ids.add(file.getAttribute(i).getValue());
         
         break;
    }
}

The `! File.getAttribute (i) .getValue (). IsEmpty ()` way of writing here is that the value of `file.getAttribute (i) .getValue ()` is not always null. Premise is required. (Because `` `NullPointerException``` will occur if null is set) This time, the referenced object was set so that the value here is not null, but you must also consider the situation when it is not set.

It is safer to write in such a way that it will not fall even if something is set when referencing it in an object created by such an independent process.

Fixed:

file_2.java


for(int i=0;i<file.attributeSize();i++){
    var fileAttr = file.getAttribute(i);
    if(!"00000000".equals(fileAttr.getId())){
        continue;
    }

    var value = fileAttr.getValue();
    if(value != null && !value.isEmpty()){
          ids.add(value);

          break;
    }
}

Writing this would avoid `` `NullPointerException```.

Unify the writing style

It's a very detailed story, but I think it's better to set personal rules when you first start writing the source code. Example:

rule.java


for(int i =0;i<ids.length;i++) {
 //なにかの処理を書く
}

The above source code may be confusing, but write the arguments after for()I didn't put a space after for, but I put a space after the parentheses. Display the arguments after such for and if()Let's unify whether or not to leave a half-width space.

rule2.java


for(int i=0;i<ids.length;i++){
 //なにかの処理を書く
}

#Summary What did you think.

At first, I was doing my best just to move the source code, but I am gradually thinking about readability and creation rules. For me, "studying programming is not the purpose" is the most important thing to note. I think the important thing is to have motives such as "I want to make something" and "What kind of function I want to realize", and to investigate and program accordingly.

Recommended Posts

Things to note for newcomers to write readable code during Java development
Things to watch out for in future Java development
Sample code collection for Azure Java development
Java Development Basics ~ How to Write Programs * Exercise 1 ~
Things to watch out for in Java equals
java: How to write a generic type list [Note]
Java development for beginners to start from 1-Vol.1-eclipse setup
[Java] Things to note about type inference extended in Java 10
How to build Java development environment with VS Code
Things to be aware of when writing code in Java
Eclipse installation and code completion enhancements (Mac for Java development)
Java 14 new features that could be used to write code
How to write good code
How to write java comments
[Note] How to write Dockerfile/docker-compose.yml
Write Java8-like code in Java8
[RSpec on Rails] How to write test code for beginners by beginners
Basics of Java development ~ How to write programs (variables and types) ~
[Note] Java: Is it necessary to override equals for equality judgment?
Studying Java # 6 (How to write blocks)
[Java] Points to note with Arrays.asList ()
Build Java development environment (for Mac)
How to write Java variable declaration
My note: Introducing Java to Ubuntu
How to write easy-to-understand code [Summary 3]
Java development environment (Mac, VS Code)
Things to note in conditional expressions
[Android] Convert Android Java code to Kotlin
[RSpec] How to write test code
Introduction to Java development environment & Spring Boot application created with VS Code