Computer >> Hướng Dẫn Máy Tính >  >> Hệ Thống >> Android

Thành thạo SOLID: Hướng dẫn toàn diện thiết kế phần mềm vững chắc

Series ứng dụng Kriptofolio - Phần 1

Phần mềm luôn trong trạng thái thay đổi. Mỗi thay đổi có thể tác động tiêu cực đến toàn bộ project. Vì vậy, điều thiết yếu là ngăn chặn thiệt hại khi implement thay đổi mới.

Với app "Kriptofolio" (trước "My Crypto Coins"), tôi sẽ tạo nhiều code mới từng bước và muốn bắt đầu tốt. Muốn project chất lượng solid. Trước hết hiểu nguyên tắc nền tảng tạo phần mềm hiện đại. Chúng gọi là nguyên lý SOLID. Tên gọi bắt tai! 😄

Nội dung Series

  • Giới thiệu: Lộ trình xây dựng app Android hiện đại 2018–2019
  • Phần 1: Giới thiệu nguyên lý SOLID (bạn đang ở đây)
  • Phần 2: Bắt đầu xây dựng app Android: Mockup, UI, XML layouts
  • Phần 3: Tất cả về kiến trúc: khám phá pattern và cách dùng
  • Phần 4: Triển khai Dependency Injection với Dagger 2
  • Phần 5: Xử lý RESTful Web Services với Retrofit, OkHttp, Gson, Glide và Coroutines

Slogan nguyên lý

SOLID là acronym mnemonic. Giúp định nghĩa 5 nguyên lý thiết kế object-oriented cơ bản:

  1. Single Responsibility Principle (Nguyên lý trách nhiệm đơn nhất)
  2. Open-Closed Principle (Nguyên lý mở-đóng)
  3. Liskov Substitution Principle (Nguyên lý thay thế Liskov)
  4. Interface Segregation Principle (Nguyên lý tách biệt interface)
  5. Dependency Inversion Principle (Nguyên lý đảo ngược phụ thuộc)

Tiếp theo thảo luận từng nguyên lý. Mỗi nguyên lý cung cấp ví dụ code xấu vs tốt. Ví dụ viết cho Android dùng Kotlin.

Single Responsibility Principle

Một class nên có chỉ một trách nhiệm duy nhất.

Mỗi class/module chịu trách nhiệm một phần functionality của app. Khi handle một việc, chỉ có một lý do chính để thay đổi nó. Nếu class/module làm hơn một việc, tách functionality ra riêng.

Hiểu rõ nguyên lý này, ví dụ con dao đa năng Thụy Sĩ (Swiss Army knife). Đổi tên cho nhiều chức năng bên cạnh lưỡi dao chính. Có tool tích hợp: tuýp vít, khai hộp, và nhiều khác.

Câu hỏi tự nhiên: tại sao tôi gợi ý dao này làm ví dụ single functionality? Chỉ suy nghĩ một chút. Tính năng chính khác của dao là di động, size túi. Dù cung cấp vài chức năng khác, nó vẫn fit mục đích chính: đủ nhỏ mang theo thoải mái.

Cùng quy tắc áp dụng cho lập trình. Khi tạo class/module, nó có mục đích global chính. Cùng lúc không overplay khi cố gắng simplify quá mức bằng tách functionality. Nhớ: giữ cân bằng.

Thành thạo SOLID: Hướng dẫn toàn diện thiết kế phần mềm vững chắc

Ví dụ kinh điển: method onBindViewHolder thường dùng khi build RecyclerView adapter.

❌ BAD CODE EXAMPLE:

class MusicVinylRecordRecyclerViewAdapter(private val vinyls: List<VinylRecord>, private val itemLayout: Int) : RecyclerView.Adapter<MusicVinylRecordRecyclerViewAdapter.ViewHolder>() { ... override fun onBindViewHolder(holder: ViewHolder, position: Int) { val vinyl = vinyls[position] holder.itemView.tag = vinyl holder.title!!.text = vinyl.title holder.author!!.text = vinyl.author holder.releaseYear!!.text = vinyl.releaseYear holder.country!!.text = vinyl.country holder.condition!!.text = vinyl.condition /** * Đây vi phạm Single Responsibility Principle!!! * Dù trách nhiệm chính và duy nhất là adapt VinylRecord object * sang view representation, nó cũng thực hiện data formatting. * Có nhiều lý do thay đổi trong tương lai, sai. */ var genreStr = "" for (genre in vinyl.genres!!) { genreStr += genre + ", " } genreStr = if (genreStr.isNotEmpty()) genreStr.substring(0, genreStr.length - 2) else genreStr holder.genre!!.text = genreStr } ... }

✅ GOOD CODE EXAMPLE:

class MusicVinylRecordRecyclerViewAdapter(private val vinyls: List<VinylRecord>, private val itemLayout: Int) : RecyclerView.Adapter<MusicVinylRecordRecyclerViewAdapter.ViewHolder>() { ... override fun onBindViewHolder(holder: ViewHolder, position: Int) { val vinyl = vinyls[position] holder.itemView.tag = vinyl holder.title!!.text = vinyl.title holder.author!!.text = vinyl.author holder.releaseYear!!.text = vinyl.releaseYear holder.country!!.text = vinyl.country holder.condition!!.text = vinyl.condition /** * Thay vì thực hiện data formatting ở đây, chuyển trách nhiệm sang * class khác. Thực tế đây là gọi trực tiếp top-level function * convertArrayListToString - tính năng mới Kotlin. Tuy nhiên đừng nhầm, * vì Kotlin compiler behind the scenes vẫn tạo Java class, * và top-level function chuyển thành static method. Vậy mỗi class single responsibility. */ holder.genre!!.text = convertArrayListToString(vinyl.genres) } ... }

Code thiết kế với Single Responsibility Principle sẽ gần với các nguyên lý khác sẽ thảo luận.

Open-Closed Principle

Thực thể phần mềm nên mở cho mở rộng, nhưng đóng cho sửa đổi.

Nguyên lý nói khi viết software parts (class, module, function), làm cho chúng mở cho extension nhưng closed cho modification. Nghĩa là gì?

Giả sử tạo class hoạt động. Không cần tweak class nếu cần thêm functionality hoặc thay đổi. Thay vào đó, extend class bằng subclass mới thêm feature cần thiết. Feature nên parameterized để subclass override.

Xem ví dụ tạo class FeedbackManager đặc biệt show custom message type khác nhau cho user.

❌ BAD CODE EXAMPLE:

class MainActivity : AppCompatActivity() { lateinit var feedbackManager: FeedbackManager override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) feedbackManager = FeedbackManager(findViewById(android.R.id.content)); } override fun onStart() { super.onStart() feedbackManager.showToast(CustomToast()) } } class FeedbackManager(var view: View) { // Giả sử cần thêm type feedback message mới. Sẽ xảy ra gì? // Cần modify manager class. Nhưng để follow Open Closed Principle cần viết code // adapt tự động cho requirement mới không rewrite old class. fun showToast(customToast: CustomToast) { Toast.makeText(view.context, customToast.welcomeText, customToast.welcomeDuration).show() } fun showSnackbar(customSnackbar: CustomSnackbar) { Snackbar.make(view, customSnackbar.goodbyeText, customSnackbar.goodbyeDuration).show() } } class CustomToast { var welcomeText: String = "Hello, this is toast message!" var welcomeDuration: Int = Toast.LENGTH_SHORT } class CustomSnackbar { var goodbyeText: String = "Goodbye, this is snackbar message.." var goodbyeDuration: Int = Toast.LENGTH_LONG }

✅ GOOD CODE EXAMPLE:

class MainActivity : AppCompatActivity() { lateinit var feedbackManager: FeedbackManager override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) feedbackManager = FeedbackManager(findViewById(android.R.id.content)); } override fun onStart() { super.onStart() feedbackManager.showSpecialMessage(CustomToast()) } } class FeedbackManager(var view: View) { // Cùng tình huống - cần thêm type feedback message. Viết code adapt cho requirement mới // không thay đổi old class implementation. Giải pháp: focus extend functionality bằng interface // tuân thủ Open Closed Principle. fun showSpecialMessage(message: Message) { message.showMessage(view) } } interface Message { fun showMessage(view: View) } class CustomToast: Message { var welcomeText: String = "Hello, this is toast message!" var welcomeDuration: Int = Toast.LENGTH_SHORT override fun showMessage(view: View) { Toast.makeText(view.context, welcomeText, welcomeDuration).show() } } class CustomSnackbar: Message { var goodbyeText: String = "Goodbye, this is snackbar message.." var goodbyeDuration: Int = Toast.LENGTH_LONG override fun showMessage(view: View) { Snackbar.make(view, goodbyeText, goodbyeDuration).show() } }

Open-Closed Principle tóm tắt mục tiêu của 2 nguyên lý dưới. Tiếp tục.

Liskov Substitution Principle

Object trong chương trình nên thay thế được bằng instance của subtype mà không làm thay đổi tính đúng đắn của chương trình.

Nguyên lý tên theo Barbara Liskov — nhà khoa học máy tính xuất sắc. Ý tưởng: object nên replaceable bằng instance của subtype không thay đổi behavior chương trình.

Giả sử app có MainClass phụ thuộc BaseClass, kế thừa SubClass. Tóm lại, để follow nguyên lý, code MainClass và app nói chung nên hoạt động seamless không vấn đề khi đổi instance BaseClass sang SubClass.

Thành thạo SOLID: Hướng dẫn toàn diện thiết kế phần mềm vững chắc

Hiểu rõ hơn, ví dụ kinh điển Square và Rectangle inheritance.

❌ BAD CODE EXAMPLE:

class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val rectangleFirst: Rectangle = Rectangle() rectangleFirst.width = 2 rectangleFirst.height = 3 textViewRectangleFirst.text = rectangleFirst.area().toString() // Kết quả area rectangle đầu = 6, đúng vì 2 x 3 = 6. // Liskov Substitution Principle nói subclass (Square) nên override // parent class (Rectangle) cách không break functionality từ consumer perspective. Xem. val rectangleSecond: Rectangle = Square() // User assume là rectangle, set width/height như bình thường rectangleSecond.width = 2 rectangleSecond.height = 3 textViewRectangleSecond.text = rectangleSecond.area().toString() // Kết quả mong đợi rectangle 2 = 6, nhưng thực tế = 9. // Vậy approach OOP Square extends Rectangle sai. } } open class Rectangle { open var width: Int = 0 open var height: Int = 0 open fun area(): Int { return width * height } } class Square : Rectangle() { override var width: Int get() = super.width set(width) { super.width = width super.height = width } override var height: Int get() = super.height set(height) { super.width = height super.height = height } }

✅ GOOD CODE EXAMPLE:

class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // Cách tổ chức Rectangle và Square class tốt hơn để meet Liskov Substitution Principle. Không còn unexpected result. val rectangleFirst: Shape = Rectangle(2,3) val rectangleSecond: Shape = Square(3) textViewRectangleFirst.text = rectangleFirst.area().toString() textViewRectangleSecond.text = rectangleSecond.area().toString() } } class Rectangle(var width: Int, var height: Int) : Shape() { override fun area(): Int { return width * height } } class Square(var edge: Int) : Shape() { override fun area(): Int { return edge * edge } } abstract class Shape { abstract fun area(): Int }

Luôn suy nghĩ trước khi viết hierarchy. Như ví dụ, object thực tế không luôn map đến cùng OOP class. Cần tìm approach khác.

Interface Segregation Principle

Nhiều interface client-specific tốt hơn một interface general-purpose.

Tên nghe phức tạp nhưng nguyên lý dễ hiểu. Nói client không bao giờ bị forced depend trên method hoặc implement interface không dùng. Class thiết kế nên có ít method/attribute nhất. Tạo interface, đừng làm to. Thay vào đó tách thành interface nhỏ hơn để client chỉ biết method relevant.

Hiểu nguyên lý, tạo lại bad vs good code example với robot bướm và robot người. 😄

Thành thạo SOLID: Hướng dẫn toàn diện thiết kế phần mềm vững chắc

❌ BAD CODE EXAMPLE:

/** * Tưởng tượng tạo robot undefined. Quyết định tạo interface với all possible functions. */ interface Robot { fun giveName(newName: String) fun reset() fun fly() fun talk() } /** * Tạo butterfly robot implement interface đó. */ class ButterflyRobot : Robot { var name: String = "" override fun giveName(newName: String) { name = newName } override fun reset() { // Gọi reset command cho robot. Software robot nào cũng nên reset được. // Hợp lý, implement này. TODO("not implemented") } override fun fly() { // Gọi fly command. Chức năng specific butterfly robot. // Chắc chắn implement. TODO("not implemented") } override fun talk() { // Gọi talk command. // SAI!!! Butterfly robot không talk, chỉ fly! Tại sao implement này? // Vi phạm Interface Segregation Principle: forced implement method không dùng. TODO("???") } } /** * Tạo humanoid robot làm action như con người, cũng implement same interface. */ class HumanoidRobot : Robot { var name: String = "" override fun giveName(newName: String) { name = newName } override fun reset() { // Gọi reset command. Software robot nào cũng reset được. // Hợp lý, implement. TODO("not implemented") } override fun fly() { // Gọi fly command. // Vấn đề! Không bao giờ định humanoid robot bay. // Vi phạm Interface Segregation Principle: forced implement method không dùng. TODO("???") } override fun talk() { // Gọi talk command. Chức năng specific humanoid robot. // Chắc chắn implement. TODO("not implemented") } }

✅ GOOD CODE EXAMPLE:

/** * Tưởng tượng tạo robot undefined. Nên tạo generic interface với all possible functions * common cho all robot types. */ interface Robot { fun giveName(newName: String) fun reset() } /** * Robot specific bay nên có interface riêng. */ interface Flyable { fun fly() } /** * Robot specific nói nên có interface riêng. */ interface Talkable { fun talk() } /** * Tạo butterfly robot implement generic interface và specific interface. * Như thấy không còn required implement function không liên quan robot! */ class ButterflyRobot : Robot, Flyable { var name: String = "" override fun giveName(newName: String) { name = newName } override fun reset() { // Gọi reset command. Software robot nào cũng reset được. // Hợp lý, implement. TODO("not implemented") } // Gọi fly command. Chức năng specific butterfly robot. // Chắc chắn implement. override fun fly() { TODO("not implemented") } } /** * Tạo humanoid robot làm action như người, implement generic interface và specific cho type. * Như thấy không còn required implement function không liên quan robot! */ class HumanoidRobot : Robot, Talkable { var name: String = "" override fun giveName(newName: String) { name = newName } override fun reset() { // Gọi reset command. Software robot nào cũng reset được. // Hợp lý, implement. TODO("not implemented") } override fun talk() { // Gọi talk command. Chức năng specific humanoid robot. // Chắc chắn implement. TODO("not implemented") } }

Dependency Inversion Principle

Nên "phụ thuộc vào abstraction, [không phải] concretion."

Nguyên lý cuối: high-level module không nên depend trên low-level module. Cả hai nên depend trên abstraction. Abstraction không depend trên detail. Detail depend trên abstraction.

Ý chính: không direct dependency giữa module/class. Cố gắng làm depend trên abstraction (interface) thay thế.

Đơn giản hơn: nếu dùng class A trong class B, class B depend trên class A inject. Vi phạm nguyên lý, không nên làm. Cố gắng decouple tất cả class.

❌ BAD CODE EXAMPLE:

class Radiator { var temperatureCelsius : Int = 0 fun turnOnHeating(newTemperatureCelsius : Int) { temperatureCelsius = newTemperatureCelsius // Bật heating cho radiator cần step cụ thể cho device này. // Radiator có procedure kỹ thuật riêng. Implement ở đây. TODO("not implemented") } } class AirConditioner { var temperatureFahrenheit: Int = 0 fun turnOnHeating(newTemperatureFahrenheit: Int) { temperatureFahrenheit = newTemperatureFahrenheit // Bật heating cho air conditioner cần step riêng cho device này, // procedure khác radiator, implement ở đây. TODO("not implemented") } } class SmartHome { // Smart home control system thêm radiator control. var radiator: Radiator = Radiator() // Sau nếu đổi radiator thành air conditioner? // var airConditioner: AirConditioner = AirConditioner() // SmartHome class depend trên Radiator, vi phạm Dependency Inversion Principle. var recommendedTemperatureCelsius : Int = 20 fun warmUpRoom() { radiator.turnOnHeating(recommendedTemperatureCelsius) // Nếu bỏ qua principle có thể lỗi quan trọng, như này. // Pass recommended temp celsius nhưng air conditioner expect Fahrenheit. // airConditioner.turnOnHeating(recommendedTemperatureCelsius) } }

✅ GOOD CODE EXAMPLE:

// Trước tạo abstraction - interface. interface Heating { fun turnOnHeating(newTemperatureCelsius : Int) } // Class implement Heating interface. class Radiator : Heating { var temperatureCelsius : Int = 0 override fun turnOnHeating(newTemperatureCelsius: Int) { temperatureCelsius = newTemperatureCelsius // Radiator procedure kỹ thuật bật heating implement ở đây. TODO("not implemented") } } // Class implement Heating interface. class AirConditioner : Heating { var temperatureFahrenheit: Int = 0 override fun turnOnHeating(newTemperatureCelsius: Int) { temperatureFahrenheit = newTemperatureCelsius * 9/5 + 32 // Air conditioner procedure bật heating implement ở đây. TODO("not implemented") } } class SmartHome { // Smart home control system thêm radiator control. var radiator: Heating = Radiator() // Câu trả lời: sau nếu đổi radiator thành air conditioner. Class depend trên interface thay vì injected class. // var airConditioner: Heating = AirConditioner() var recommendedTemperatureCelsius : Int = 20 fun warmUpRoom() { radiator.turnOnHeating(recommendedTemperatureCelsius) // Vì depend trên common interface, không còn cơ hội lỗi. // airConditioner.turnOnHeating(recommendedTemperatureCelsius) } }

Tóm tắt ngắn gọn

Nếu suy nghĩ tất cả nguyên lý, nhận thấy chúng bổ sung lẫn nhau. Tuân thủ SOLID mang lại nhiều lợi ích: app reusable, maintainable, scalable, testable.

Tất nhiên không luôn follow hoàn toàn mọi nguyên lý, mọi thứ phụ thuộc situation khi viết code. Nhưng作为 developer nên biết chúng để quyết định khi nào áp dụng.

Repository

Phần 1 học và plan project thay vì viết code mới. Link Part 1 branch commit, cơ bản là "Hello world" initial code project.

View Source On GitHub

Hy vọng giải thích SOLID principles tốt. Để comment bên dưới tự do.

Ačiū! Cảm ơn đã đọc! Bài gốc đăng trên blog www.baruckis.com ngày 23/2/2018.