2. ABOUT CLEAN CODE
Robert C. Martin (Uncle Bob)
Clean Code
Why is Clean Code?
You are programmer
You want to be a better programmer
3. WHAT IS CLEAN CODE?
Bjarne Stroustup
I like my code to be elegant and
efficient.
The logic should be straightforward
The dependencies minimal
Clean code does one thing well.
Bjarne Stroustup, người phát minh ra C++ và là tác giả của cuốn The C++ Programming Language
4. CHAPTER1: WHAT IS CLEAN CODE?
Dave Thomas
Clean code can be read.
It has meaningful names.
It has unit test and customer tests.
Dave Thomas cha đẻ của chiến lược Eclipse
5. CHAPTER2: MEANINGFUL NAMES
Use Intention-Revealing Names
public List<int[]> getThem() {
List<int[]> list1 = new ArrayList<int[]>();
for (int[] x : theList){
if (x[0] == 4)
list1.add(x);
} return list1;
}
6. CHAPTER2: MEANINGFUL NAMES
Use Intention-Revealing Names
public List<int[]> getThem() {
List<int[]> list1 = new ArrayList<int[]>();
for (int[] x : theList) {
if (x[0] == 4)
list1.add(x);
}
return list1;
}
public List<Cell> getFlaggedCells() {
List<Cell> flaggedCells = new ArrayList<Cell>();
for (Cell cell : gameBoard) {
if (cell.isFlagged())
flaggedCells.add(cell);
}
return flaggedCells;
}
8. CHAPTER2: MEANINGFUL NAMES
Make Meaningful Distinctions
public static void copyChars(char a1[], char a2[]) {
for (int i = 0; i < a1.length; i++) {
a2[i] = a1[i];
}
}
9. CHAPTER2: MEANINGFUL NAMES
Use Pronounceable Names
class DtaRcrd102 {
private Date genymdhms;
private Date modymdhms;
private final String pszqint = “102”;
/* ... */
};
class Customer {
private Date generationTimestamp;
private Date modificationTimestamp;
private final String recordId = “102”;
/* ... */
};
10. CHAPTER2: MEANINGFUL NAMES
Use Searchable Names
for (int j=0; j<34; j++) {
s += (t[j]*4)/5;
}
int realDaysPerIdealDay = 4;
int NUMBER_OF_TASKS = 34;
int WORK_DAYS_PER_WEEK = 5;
int sum = 0;
for (int j=0; j < NUMBER_OF_TASKS; j++) {
int realTaskDays = taskEstimate[j] * realDaysPerIdealDay;
int realTaskWeeks = (realdays / WORK_DAYS_PER_WEEK);
sum += realTaskWeeks;
}
11. CHAPTER2: MEANINGFUL NAMES
Avoid encodings
public class Part {
private String m_dsc; // The textual description
void setName(String name) {
m_dsc = name;
}
}
public class Part {
String description;
void setDescription(String description) {
this.description = description;
}
}
12. CHAPTER2: MEANINGFUL NAMES
Avoid encodings
for (a = 0; a < 10; a++) {
for (b = 0; b < 10; b++) {
…………..
}
}
for (i = 0; i < 10; i++) {
for (j = 0; j < 10; j++) {
…………..
}
}
13. CHAPTER2: MEANINGFUL NAMES
Class Names
A class name should not be a verb.
Classes and objects should have noun or noun phrase
names like: Customer, WikiPage, Account, and
AddressParser.
Avoid words like: Manager, Processor, Data, or Info in
the name of a class.
15. CHAPTER2: MEANINGFUL NAMES
Add Meaningful Context
// a good solution
firstName, lastName, street, city, state, zipcode
// a better solution
addrFirstName, addrLastName, addrState
// a best solution
Class Address
16. CHAPTER2: MEANINGFUL NAMES
Don’t Add Gratuitous Context
Address
// is a fine name for a class
AccountAddress, CustomerAddress
// are fine names for instances of the class Address
// but could be poor names for classes
MAC addresses, port addresses, Web addresses
// not good solution
PostalAddress, MAC, URI
// a better solution
17. CHAPTER3: FUNCTION
Small
Should be small
Should be smaller than that
< 150 characters per line
< 20 lines
Do One Thing
// FUNCTIONS SHOULD DO ONE THING. THEY
SHOULD DO IT WELL.
// THEY SHOULD DO IT ONLY.
public static String renderPageWithSetupsAndTeardowns(
PageData pageData, boolean isSuite) throws Exception {
if (isTestPage(pageData)) {
includeSetupAndTeardownPages(pageData, isSuite);
}
return pageData.getHtml();
}
18. CHAPTER3: FUNCTION
One Level of Abstraction per Function
In order to make sure our functions are doing “one
thing,” we need to make sure that the statements within
our function are all at the same level of abstraction.
// high level of abstraction
getHtml()
// intermediate level of abstraction
String pagePathName = PathParser.render(pagePath);
// remarkably low level
.append("n")
19. CHAPTER3: FUNCTION
Reading Code from Top to Botom
We want the code to read like a top-down narrative.
We want every function to be followed by those at the
next level of abstraction so that we can read the
program, descending one level of abstraction at a time
as we read down the list of functions.
=> I call this The Stepdown Rule.
20. CHAPTER3: FUNCTION
Switch Statements
// not good solution
public Money calculatePay(Employee e) throws InvalidEmployeeType {
switch (e.type) {
case COMMISSIONED:
return calculateCommissionedPay(e);
case HOURLY:
return calculateHourlyPay(e);
case SALARIED:
return calculateSalariedPay(e);
default:
throw new InvalidEmployeeType(e.type);
}
}
21. // a better solution
public abstract class Employee {
public abstract boolean isPayday();
public abstract Money calculatePay();
public abstract void deliverPay(Money pay);
}
public interface EmployeeFactory {
public Employee makeEmployee(EmployeeRecord r) throws … ;
}
public class EmployeeFactoryImpl implements EmployeeFactory {
public Employee makeEmployee(EmployeeRecord r) throws … {
switch (r.type) {
case COMMISSIONED:
return new CommissionedEmployee(r) ;
case HOURLY:
return new HourlyEmployee(r);
case SALARIED:
return new SalariedEmploye(r);
default:
throw new InvalidEmployeeType(r.type);
}
}
}
22. CHAPTER3: FUNCTION
Function Argument
The ideal number of arguments for a function is zero
(niladic).
Next comes one (monadic), followed closely by two
(dyadic).
Three arguments (triadic) should be avoided where
possible.
More than three (polyadic) requires very special
justification and then shouldn’t be used anyway.
23. FUNCTION ARGUMENT
Common Monadic Forms
// if a function is going to transform its input argument,
the transformation should appear as the return value
// not good
StringBuffer transform(StringBuffer in)
// is better than
void transform(StringBuffer out)
24. FUNCTION ARGUMENT
Argument Objects
When a function seems to need more than two or three
arguments, it is likely that some of those arguments
ought to be wrapped into a class of their own.
// is more than two arguments
makeCircle(double x, double y, double radius);
// to be wrapped into a class
Circle makeCircle(Point center, double radius);
25. FUNCTION ARGUMENT
Argument Lists
Sometimes we want to pass a variable number of
arguments into a function.
String.format("%s worked %.2f hours.", name, hours);
public String format(String format, Object... args)
26. CHAPTER4: COMMENTS
Comments Do Not Make Up for Bad Code
don’t comment bad code, rewrite it!
Explain Yourself in Code
// Check to see if the employee is eligible for full benefits
if (employee.flags && employee.age > 65) {
if (employee.isEligibleForFullBenefits()) {
………
}
}
27. CHAPTER4: COMMENTS (STIMULATE)
Legal Comment
// Copyright (C) 2011 by Osoco. All rights reserved.
// Released under the terms of the GNU General Public License
// version 2 or later.
Informative Comment
// huanlt 20150930 renaming the function:responderBeingTested
// Returns an instance of the Responder being tested.
protected abstract Responder responderInstance();
// format matched kk:mm:ss EEE, MMM dd, yyyy
Pattern timeMatcher = Pattern.compile(
"d*:d*:d* w*, w* d*, d*");
28. CHAPTER4: COMMENTS (GOOD)
Explanation of Intent
Clarification
//This is our best attempt to get a race condition
//by creating large number of threads.
for (int i = 0; i < 25000; i++) {
WidgetBuilderThread widgetBuilderThread =
new WidgetBuilderThread(widgetBuilder, text, failFlag);
Thread thread = new Thread(widgetBuilderThread);
thread.start();
}
assertTrue(a.compareTo(b) == -1); // a < b
assertTrue(b.compareTo(a) == 1); // b > a
29. CHAPTER4: COMMENTS (GOOD)
Warning of Consequences
TODO Comment
public static SimpleDateFormat makeStandardHttpDateFormat() {
//SimpleDateFormat is not thread safe,
//so we need to create each instance independently.
SimpleDateFormat df = new SimpleDateFormat("dd MM yyyy");
df.setTimeZone(TimeZone.getTimeZone("GMT"));
return df;
}
//TODO-MdM these are not needed
// We expect this to go away when we do the checkout model
30. CHAPTER4: COMMENTS (BAD)
Mumbling
try {
String propertiesPath = propertiesLocation + "/" +
PROPERTIES_FILE;
FileInputStream propertiesStream =
new FileInputStream(propertiesPath);
loadedProperties.load(propertiesStream);
}
catch(IOException e) {
// No properties files means all defaults are loaded
}
31. CHAPTER4: COMMENTS (BAD)
Redundant Comment
// Utility method that returns when this.closed is true.
// Throws an exception if the timeout is reached.
public synchronized void waitForClose
(final long timeoutMillis) throws Exception {
if(!closed) {
wait(timeoutMillis);
if(!closed)
throw new Exception("MockResponseSender
could not be closed");
}
}
32. CHAPTER4: COMMENTS (BAD)
Mandated Comment
/**
* @param title The title of the CD
* @param author The author of the CD
* @param tracks The number of tracks on the CD
* @param durationInMinutes The duration of the CD in minutes
*/
public void addCD(String title, String author,
int tracks, int durationInMinutes) {
CD cd = new CD();
cd.title = title;
cd.author = author;
cd.tracks = tracks;
cd.duration = durationInMinutes;
}
33. CHAPTER4: COMMENTS (BAD)
Journal Comment
* Changes (from 11-Oct-2001)
* --------------------------
* 11-Oct-2001 : Re-organised the class and moved it to new
* package com.jrefinery.date (DG);
* 05-Nov-2001 : Added a getDescription() method, and
* eliminated NotableDate class (DG);
* 12-Nov-2001 : IBD requires setDescription() method, now
* that NotableDate class is gone (DG); Changed
* getPreviousDayOfWeek(),
* getFollowingDayOfWeek() and
* getNearestDayOfWeek() to correct bugs (DG);
* 05-Dec-2001 : Fixed bug in SpreadsheetDate class (DG);
* 29-May-2002 : Moved the month constants into a separate
* interface (MonthConstants) (DG);
35. CHAPTER4: COMMENTS (BAD)
HTML Comments
Nonlocal Information
Too Much Information
Unobvious Connection
Function Headers
// short functions don’t need much description
Javadocs in Nonpublic Code
// extra formality of the javadoc comments
36. CHAPTER4: COMMENTS (BAD)
HTML Comments
Nonlocal Information
Too Much Information
Unobvious Connection
Function Headers
// short functions don’t need much description
Javadocs in Nonpublic Code
// extra formality of the javadoc comments
37. CHAPTER5: FORMATTING
Vertical Formatting
Vertical Density
// vertical density implies close association
Vertical Distance
// variables should be declared as close to their usage as
possible
// instance variables should be declared at the top of the
class
// dependent functions if one function calls another, they
should be vertically close, and the caller should be
above the called
// conceptual affinity certain bits of code want to be near
other bits
39. CHAPTER5: FORMATTING
Breaking Indentation
Break after a comma.
Break after an operator.
Prefer higher-level breaks to lower-level breaks.
40. CHAPTER5: FORMATTING
Team Rules
// every programmer has his own favorite formatting rules
// but if he works in a team
// then the team rules
46. DON'T RETURN NULL
List<Employee> employees = getEmployees();
if (employees != null) {
for(Employee e : employees) {
totalPay += e.getPay();
}
}
List<Employee> employees = getEmployees();
for(Employee e : employees) {
totalPay += e.getPay();
}
public List<Employee> getEmployees() {
if( .. there are no employees .. )
return Collections.emptyList();
}
If you code this way, you will minimize the chance of NullPointerExceptions and
your code will be cleaner.
47. CHAPTER6: ERROR HANDLING
Don't Pass Null
Returning null from methods is bad, but passing null into
methods is worse.
public class MetricsCalculator {
public double xProjection(Point p1, Point p2) {
return (p2.x – p1.x) * 1.5;
}
}
public double xProjection(Point p1, Point p2) {
if (p1 == null || p2 == null) {
throw InvalidArgumentException ("Invalid argument
for MetricsCalculator.xProjection");
}
return (p2.x – p1.x) * 1.5;
}
48. DON'T PASS NULL
Is this better? It might be a little better than a null pointer
exception.
But remember, we have to define a handler for
InvalidArgumentException.
public class MetricsCalculator
{
public double xProjection(Point p1, Point p2) {
assert p1 != null : "p1 should not be null";
assert p2 != null : "p2 should not be null";
return (p2.x – p1.x) * 1.5;
}
}
The rational approach is to forbid passing null by default.
49. CHAPTER1: WHAT IS CLEAN CODE?
Code simple, efficient
Logic logic clear
Dependencies minimal
Class, method does one thing well
Meaningful names
Error handling
Comments
Rename code before commit
Refractor code before commit
Format code before commit
Unit test
Clean Code: A Handbook of Agile Software Craftsmanship là một trong những cuốn sách thuộc bộ sách Robert C. Martin Series của Robert C. Martin, tên đường phố là Uncle Bob (chú Bob).
Chú Bob hay “Uncle Bob” là tên “đường phố” của Robert C. Martin, một tay tổ trong giới lập trình, tác giả của hàng loạt tập sách (Robert C. Martin Series) thuộc loại gối đầu giường cho coder. Là người nhiệt thành đến cực đoan trong việc thúc đẩy một quan điểm “nâng tầm” nghề lập trình, đòi hỏi cả coder lẫn những người khác phải nhìn nhận lập trình như một nghề chuyên nghiệp đáng trân trọng, và phải đầu tư nghiêm túc, từ chuyên môn tới trách nhiệm và đạo đức.
Đầu tiên, bạn là một lập trình viên. Thứ hai, bạn muốn trở thành một lập trình viên tốt hơn. Tốt rồi. Chúng ta cần lập trình tốt hơn.
Bjarne Stroustup, người phát minh ra C++ và là tác giả của cuốn The C++ Programming Language
- Tôi thích mã của tôi thanh lịch và hiệu quả.
Lô-gic nên đơn giản để làm cho nó khó gặp những lỗi ẩn
Có tối thiểu những sự phụ thuộc để dễ dàng bảo trì
Mã sạch là mã làm tốt một việc.
Dave Thomas “Vĩ đại”, sáng lập viên của OTI, cha đẻ của chiến lược Eclipse
Mã sạch là mã có thể được đọc và cải tiến bởi một nhà phát triển bất kỳ chứ không phải chỉ tác giả của nó mới đọc nổi.
Mã sạch có những tên có ý nghĩa.
Nó phải có cả kiểm thử đơn vị ở phía lập trình viên lẫn kiểm thử chấp chận do khách hàng thực hiện.
Michael Feathers, tác giả của Working Effectively with Legacy Code
Mã sạch bao giờ cũng trông như được viết bởi những người có TÂM.
Sử dụng tên mang tính gợi tả nhằm mục đích giúp người đọc code hiểu được phần nào mục đích của biến, đối tượng, phương thức …
Ở ví dụ trên là một hàm trong trò chơi DÒ MÌN chúng ta đọc công mà không thể trả lời được:
1. theList thuộc loại nào?
2. Nghĩa của chỉ số bắt đầu từ không của một phần tử trong theList là gì?
3. Số 4 có nghĩa gì?
4. Tôi sử dụng danh sách trả về như thế nào?
Chúng ta thấy bảng chứa danh sách các ô được gọi là theList => Hãy đặt lại tên thành gameBoard.
Mỗi ô trên bảng được biểu diễn bởi một mảng.
Chúng ta cũng thấy rằng chỉ số thứ 0 là vị trí của một trạng thái và giá trị trang thái 4 có nghĩa là “được đánh dấu” (flagged).
Bằng cách đưa ra những tên khái niệm chúng ta có thể cải tiến đáng kể đoạn mã trên
Trong đó còn tồn tại mảng int và 2 constants STATUS_VALUE và FLAGGED như một con số ma thuật
=> Tiếp tục cải tiến bằng cách: Thay vì sử dụng mảng số nguyên, ta tạo ra một lớp đối tượng đơn giản cho các ô. Lớp này chứa một hàm gợi tả (gọi là isFlagged) để ẩn đi các con số ma thuật.
Tránh sai lạc
- Chúng ta nên tránh những từ có nghĩa khác với ý định thực của mình. Ví dụ, hp, aix, sco là những tên biến kém bởi chúng là những cái tên mô tả trong hệ điều hành Unix hay các phiên bản của nó.
- Không nên gọi một nhóm các tài khoản (account) là accountList trừ khi nó lưu trữ danh sách (list) thật sự. Từ danh sách (list) có nghĩa là một cái gì đó cụ thể cho các lập trình viên. Vì vậy cái tên accoutGroup hoặc bunchOfAccounts chỉ ra danh sách chủ tài khoản vẫn tốt hơn.
- Một ví dụ thực sự khủng khiếp của tên gây hiểu sai khi sử dụng ký tự thường của L hoặc ký tự hoa của o làm tên biến. Tất nhiên vấn đề ở chỗ là chúng ta nhìn thấy các biến này gần giống con số 1 hoặc 0.
Tạo nên sự khác biệt rõ ràng
Đặt tên cho một dãy số là (a1, a2, …, aN) là ngược lại với việc đặt tên có chủ đích. Những tên này không làm cho trình biên dịch hiểu sai, nhưng chúng cũng không có thông tin. Chúng không cung cấp manh mối về ý tưởng của tác giả.
Sử dụng tên đọc được
Nếu bạn không thể phát âm những cái tên, bạn không thể thảo luận về nó mà không suy nghĩ gì không khác nào một tên ngốc.
Một công ty mà tôi biết là genymdhms (ngày thành lập, tháng, năm, giờ, phút, giây) họ đi xung quanh và nói “gen why emm dee aich emm es”. Tôi có thói quen không tốt khi phát âm các vấn đề như văn bản, do vậy tôi bắt đầu nói “gen-yah-mudda-hims”.
Sử dụng thuật ngữ, tên tiếng anh phù hợp thay vì sử dụng những cái tên ngớ ngẩn kiểu như “genymdhms”.
Sử dụng tên tìm kiếm được
So sánh 2 đoạn mã trên ta thấy, nếu thực hiện đặt tên là một từ đơn hoặc hằng số thì việc tìm kiếm sẽ rất khó khăn, ta không thể tìm thấy đoạn code ta mong muốn bằng từ khóa “34” hay “5” được, thay vào đó ta sẽ đặt tên cho các hằng số => ta dễ dàng tìm kiếm bởi các từ khóa cụ thể như:
“NUMBER_OF_TASKS”
“WORK_DAYS_PER_WEEK”
Tránh mã hóa
This is a problem with single-letter variable names.
Certainly a loop counter may be named i or j or k if its scope is very small and no other names can con-flict with it.
This is because those single-letter names for loop counters are traditional.
However, in most other contexts a single-letter name is a poor choice;
Tên một lớp không nên là một động từ
Tên lớp và Tên đối tượng nên có danh từ hoặc cụm danh từ như: Customer, WikiPage, Account, và AddressParser.
Tránh dùng những danh từ như: Manager, Processor, Data, Infor trong tên của một lớp.
Phương thức nên có động từ hoặc cụm động từ như postPayment, deletePage, hoặc save.
Các phương thức truy xuất, không ổn định nên được đặt tên cho giá trị của chúng và tiền tốt get, set và is theo chuẩn của javabean.
Khi phương thức khởi tạo được nạp chồng, dùng phương thức tính với tên mô tả đối số truyền vào. (trong trường hợp phương thức khởi tạo là Private)
Thêm bối cảnh có ý nghĩa
- Hãy tưởng tượng bạn có các biến với tên như sau: firstName, lastName, street, houseNumber, city, state và zipcode. Đặt chúng cạnh nhau thì rất rõ là sẽ tạo thành một địa chỉ. Nhưng biến state có nghĩa gì nếu bạn thấy nó một mình trong một phương thức? Liệu bạn có hiểu ngay đó là một phần của một địa chỉ?
- Bạn có thể thêm bối cảnh bằng cách sử dụng tiền tốt: addrFirstName, addrLastName, adddrState, v.v. Ít nhất người đọc sẽ hiểu rằng những biến này là phần của một cấu trúc lớn hơn.
- Giải pháp tốt hơn nữa là tạo một lớp có tên là Address. Lúc đó thì thậm chí trình biên dịch cũng biết là những biến này thuộc một câu trúc lớn hơn.
Đừng thêm những bối cảnh vô căn cứ
Tên ngắn thường tốt hơn tên dài, nếu chúng rõ ràng thì việc không thêm bối cảnh là cần thiết.
accountAddress và customerAddress là tên tốt cho những thể hiện của lớp Address, nhưng lại là tên lớp tồi. Address là tên lớp tốt.
VD: Nếu ta đặt tên các class trong project MED mà thêm tiền tố mô tả bối cảnh MEDBAS001U1, MEDBAS001U2, MEDBAS001U3 … thì bạn đang làm việc chống lại công cụ (IDE) của chính mình, khi bạn gõ MED và phím cách để gợi ý thì bạn nhận được một danh sách rất dài các lớp trong hệ thống.
Trong thập niên 80 các kỹ sư cho rằng một function không nên vượt quá một màn hình đầy đủ, tại thời điểm đó một màn hình vào khoảng 24 dòng và 80 cột.
Ngày nay với phông chữ đẹp hơn, màn hình lớn hơn sẽ được khoảng 150 ký tự trên một dòng, và khoảng hơn 100 dòng trên một màn hình.
Năm 1999 tác giả tới thăm Kent Beck, cả 2 ngồi xuống làm một số chương trình với mỗi function chỉ dài 3 hoặc 4 dòng, nhận thấy sự minh bạch rõ ràng
=> Một Function hầu như không bao giờ được dài quá 20 dòng.
Viết code để cho người đọc code như đọc văn xuôi từ trên xuống, các chức năng được sếp theo sau bởi các thứ tự tiếp theo của abstraction và referencing
- First, it’s large, and when new employee types are added, it will grow.
- Second, it very clearly does more than one thing.
- Third, it violates the Single Responsibility Principle (SRP) because there is more than one reason for it to change.
- Fourth, it violates the Open Closed Principle (OCP) because it must change whenever new types are added.
Comment nhảm nhí
Comment dư thừa, rườm rà, chỉ comment các logic phức tạp, không comment những điều hiển nhiên thuộc về đặc điểm của ngôn ngữ lập trình
Comment theo kiểu ủy thác, tham số truyền vào title là title của CD ….
Comment kiểu nhật ký
Không nên comment ở đằng sau dấu ngoặc nhọn
Không comment code
- Sourcefiles: Đặt tên file và phần mở rộng theo 1 chuẩn có thể giúp tối ưu hóa tìm kiếm.
- Organization: Sắp xếp các item khác nhau theo thứ tự trong source code.
- Khi một biểu thức không phù hợp trên một dòng đơn ta thực hiện xuống dòng theo quy tắc.
Mỗi Function chỉ làm 1 việc, và mỗi Error Handing cũng chỉ bắt 1 lỗi, mục đích cho việc bắt lỗi được tường minh
Nếu từ khóa Try được sử dụng trong 1 Function thì nó phải là từ được viết đầu tiên, và không nên viết code khi đã kết thúc bằng từ khóa Catch hoặc Finally
Việc đầu tiên được nhắc đến trong các cuộc thảo luận về xử lý lỗi là Return null, có rất nhiều Function mà trong đó gần như tất cả số dòng code là để check null như ví dụ trên.
Nếu chúng ta làm việc với những demo đơn giản thì việc này chưa thể hiện được tính xấu tới bạn và ứng dụng của bạn (bad code). Vì khi chúng ta return null bản chất là chúng ta đang tạo ra công việc cho bản thân và nguy cơ tạo ra vấn đề cho người gọi hàm đó. Tất cả đều phải thực hiện check null hoặc chỉ với 1 lần thiếu check null thì hậu quả sẽ là lỗi và vượt qua tầm kiểm soát. Như ví dụ trên điều gì sẽ xảy ra nếu peristentStore là null?
Trong thực tế việc bắt lỗi và xử lý check null là dễ dàng, vấn đề là nó có quá nhiều
Thực tế trong nhiều trường hợp để chữa cháy cho những trường hợp null là không khó, tuy nhiên ta xem ví dụ trên và thử thay đổi để hàm getEmployee không return null là return một list rỗng
Return null từ một phương thức là tệ rồi thì truyền vào một giá trị null thì điều đó còn tối tệ hơn. Trừ khi bạn đang làm việc với một API mà kết quả mong mốn là vượt qua các trường hợp null
Đi vào ví dụ cụ thể “hàm tính toán số liệu của 2 điểm” bên trên để thấy rõ tại sao. Chuyện gì sẽ xảy ra nếu truyền vào tham số là null?
Chúng ta sẽ nhận được NullPointerException. Làm thế nào để fix lỗi này? => tạo một ngoại lệ và ném Exception vào đó.
Tất nhiên ném ra ngoại lệ tốt hơn so với việc để bug null pointer exception xảy ra.
Nhưng chúng ta cần phải bắt và không cho truyền vào những tham số không phù hợp thì tốt hơn.