Widgets vs helper methods

Posted on:June 4, 2022

สำหรับคนที่เขียน flutter มาได้สักพัก อาจจะพบเจอ code smell ที่ชื่อว่า long method จาก life cycle ของ build method

Figure 1.1 shows a long method

ShowsALongMethod.

Refactoring

จาก Figure 1.1 จะทำการ refactor code โดยตัดสินใจจาก code ที่สามารถ re-use ได้ จากตัวอย่างก็คือ container widget ที่ alignment ที่ส่งไปเหมือนกัน มีแค่ name สำหรับแสดงผลที่ต่างกัน จากประสบการณ์ของผู้เขียนมักจะเจอ 2 possibilities สำหรับ extract code block นี้

👉 First option

Extract Method คือการสร้าง method ขึ้นมาใหม่ภายใต้ widget นั่น หรือที่จะเรียกกันว่า “helper method” พร้อมกับส่ง alignment name ที่ต่างกันเข้าไป จะได้ดังรูป Figure 1.2

Figure 1.2 shows a extract new method

ExtrActNewMethod.

👉 Second option

Extract Widget แทนที่จะย้าย code ไปเป็น method ภายใต้ widget เราจะสร้าง widget ใหม่ แล้วค่อยนำ child widget ไปเรียกใช้ที่ parent widget อีกที

Figure 1.3 shows a extract new widget

ShowsAExtractNewWidget.

จาก 2 ตัวเลือกนี้ปกติคุณใช้อะไร 🧐

ส่วนตัว ผู้เขียนจะใช้ท่า extract new widget จริงๆ แล้วในช่วงแรกๆ ผู้เขียนเองก็ใช้ท่า helper method และมีเหตุผลที่ทำให้เลิกใช้

Let’s dive into it.

Figure 1.4 state build context instance

StateBuildContextInstance.

Remi Rousselet ผู้สร้าง​ Provider, Freezed เขาได้สรุปไว้ประมาณนี้

RemiRousselet.