# 鄰近原則 contiguity principle

## 概念

相關的資訊應該放在鄰近的位置上，避免學習者浪費認知資源在搜尋相關的資訊。

這個議題跟程式碼的組織風格有關，良好的程式碼組織風格可以將相關的資訊整合再一起，不好的程式碼組織風格會讓資訊分散在各處。

因此程式碼組織風格是極為重要的，這裡會介紹兩種常見的程式碼組織風格：

* Stack style
* Entity style

stack style是一種違反鄰近原則的style，是一種浪費認知資源在資訊整合的程式碼組織風格。而entity style是一種基於鄰近原則的style，是一種有效利用認知資源的程式碼組織風格。

## Stack style

Stack style是依據技術的layer去組織程式碼，以mvc架構為例，所有的model、view、controller都會分別放在一起。

> 範例，以stack style為組織方式的school management專案結構：
>
> * model
>   * teacher-model.js
>   * student-model.js
>   * course-model.js
> * view
>   * teacher-view\.js
>   * student-view\.js
>   * course-view\.js
> * controller
>   * teacher-controller.js
>   * student-controller.js
>   * course-controller.js

這樣組織程式碼的方式違反我們大腦認知處理的方式，因為我們是以實體概念而非技術layer的方式去進行認知處理。

當我們要去了解這個系統的時候，我們不會依技術layer為邊界將model、view、controller分別檢視程式碼，而是以實體概念teacher、student、course分別檢視程式碼。

## Entity style

Entity style是依據概念去組織程式碼，以school management為例，所有的teacher、student、course都會分別放在一起。

> 範例，以stack style為組織方式的school management專案結構：
>
> * teacher
>   * teacher-model.js
>   * teacher-view\.js
>   * teacher-controller.js
> * student
>   * student-model.js
>   * student-view\.js
>   * student-controller.js
> * course
>   * course-model.js
>   * course-view\.js
>   * course-controller.js

這個風格的好處是有良好的知識邊界劃分，也符合我們大腦認知處理的方式。當我們要去理解這個系統的時候，我們就可以依據概念的方式去理解整個系統，

entity style符合了鄰近原則，可以有效的利用認知資源，是良好的程式碼組織風格。


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://huang-guo-jun.gitbook.io/ying-yong-xin-li-xue-ti-sheng-cheng-shi-ma-ke-du-xing/she-ji-yuan-ze-yu-xiao-ying/lin-jin-yuan-ze-contiguity-principle.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
