Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Java

ตั้งชื่อ Method เหมือน Class Name ใน Java ได้ไหม?

ได้ Java อนุญาตให้ตั้งชื่อ Method เหมือน Class Name ไม่มี Compile/Runtime Error แต่ ไม่แนะนำ ตาม Coding Standards (Constructor ชื่อต้องเหมือน Class)

ตัวอย่างโค้ด


public class MethodNameTest {
    private String str = "Welcome to TutorialsPoint";
    
    // Method ชื่อเหมือน Class - Valid แต่ไม่แนะนำ
    public void MethodNameTest() {
        System.out.println("Both method name and class name are the same");
    }
    
    public static void main(String args[]) {
        MethodNameTest test = new MethodNameTest();
        System.out.println(test.str);
        test.MethodNameTest();  // เรียก Method
        // new MethodNameTest()  // เรียก Constructor
    }
}

ผลลัพธ์


Welcome to TutorialsPoint
Both method name and class name are the same

ความสับสนที่อาจเกิดขึ้น

Codeหมายความว่า
new MethodNameTest()เรียก Constructor
test.MethodNameTest()เรียก Method
MethodNameTest()ใน Constructor: เรียก Constructor อื่น (this())

ทำไมไม่แนะนำ?

  • สับสนกับ Constructor (Naming Convention: Constructor = Class Name)
  • ลด Readability ผู้อ่านคาดหวังว่า ชื่อคลาส = Constructor
  • Static Analysis Tools อาจแจ้ง Warning
  • JavaBeans/Reflection คาดหวัง Convention มาตรฐาน

แนวทางปฏิบัติที่ดี

  • Method ใช้ camelCase เริ่มต้นพิมพ์เล็ก: doSomething(), calculateTotal()
  • Class ใช้ PascalCase เริ่มต้นพิมพ์ใหญ่: UserService, OrderController
  • Constructor = Class Name (Enforced by Language)
  • Constants = UPPER_SNAKE_CASE: MAX_SIZE, DEFAULT_TIMEOUT

ข้อยกเว้น (ราร์)

บางครั้งใน Builder Pattern หรือ Factory Method อาจเห็น Method ชื่อคลาส แต่ควรใช้ชื่อชัดเจนกว่า เช่น create(), build(), of()