---
# System prepended metadata

title: Object Oriented Programming
tags: [Code]

---

Object Oriented Programming
===

Object Oriented Programming helps programmers create complex programs by grouping together `related data and function`.

## Basic

- data structure
- primitive type
- group similar pieces of data together

:::info
Objects are instances of a class
Classes are templates for objects
:::

:::info
`Methods` are the `functions` defined within the class.
:::

## Principles

### Encapsulation

Encapsulation refers to bundling data with methods that can operate on that data within a class.

prevents the program from ending up in any strange or unwanted states.

:::info
Essentially, it is the idea of hiding data within a class, preventing anything outside that class from directly interacting with it.

It's generally best to not allow external classes to directly edit an object's attributes.
:::

:::warning
This `does not mean` that members of other classes cannot interact at all with the attributes of another object.

Each piece should not have access to or rely on the inner workings of `other sections` of code.
:::

### Abstraction

Abstraction refers to only showing essential details and keeping everything else hidden.

:::info
- Important to business logic
- Not Important to business logic (`How` to do)
:::

> Interface segregation principle (ISP): Don't expose methods to your client, methods that they don't use.

:::spoiler 消失的那段
- interface
- implements
:::

### Inheritance

Do not violate [Encapsulation](#Encapsulation)...

### Polymorphism

#### Dynamic

Allows methods to take on many different forms.

#### Static

method overloading

:::warning
Keep in mind that method overloading can cause trouble if you do not keep straight which parameters you need for which implementation.

Using the incorrect argument may not cause an error if it matches that of another form of the method, which can cause issues.
:::

## 及格的深度

教授: 來, 我們 60 分及格
銅學: 可是 60 分好難

:::spoiler `大絕`
$$
大絕(score) = 10\sqrt{score}
$$
:::

<br>

教授: 我們開大絕, 話就說到這阿 :three::six:
銅學: 教授, 我不會 :cry:

教授: 相信大絕可以來個兩次吧, 13 分可以吧
銅學: 我就爛阿 :sob:

教授: 2 分...

### Decorator

```go
func main() {
    考卷s := []已閱之卷{}

    for _, 考卷 := range 考卷s {
        originalScore := 考卷.Score() // 2

        // 這就是 Decorator Pattern
        終於及格了QAQ之分數 := 加分(加分(加分(originalScore))) // 60

        // 加分.還要(加分).還要(加分)(originalScore) // 60
        var 兩分就及格之加分 加分算法 = 加分.還要(加分).還要(加分) // 兩分傳進來就能及格的算法
        兩分也可以及格吧 := 兩分就及格之加分(originalScore) // 60

        assert.Equal(終於及格了QAQ之分數, 兩分也可以及格吧) // true
    }
}

func 加分(int score) int {
    return sqrt(score) * 10
}

// curring

type 加分算法 func(int) int

func (a 加分算法) 還要(加分算法 c) 加分算法 {
    return func (int originalScore) int {
        return c(a)
    }
}

```
