[Summary] Why make it object-oriented?

0. Introduction

One of the many masterpieces of the "Why Series" books, [** Why make it object-oriented **](https://www.amazon.co.jp/%E3%82%AA%E3%83%] 96% E3% 82% B8% E3% 82% A7% E3% 82% AF% E3% 83% 88% E6% 8C% 87% E5% 90% 91% E3% 81% A7% E3% 81% AA% E3% 81% 9C% E3% 81% A4% E3% 81% 8F% E3% 82% 8B% E3% 81% AE% E3% 81% 8B-% E7% AC% AC2% E7% 89% 88-% I read E5% B9% B3% E6% BE% A4-% E7% AB% A0 / dp / 4822284654 /), so I have summarized the points that were helpful and I would like to use for education.

1. Why make it object-oriented?

The question that is also the title of the book.

--To improve the reusability of the program. --To flexibly respond to changes. --To make the program easy to understand. ... etc

There are various things, but if you crush it a little, you can say ** to make software easier **.

2. Why is it said that object orientation is difficult?

Object-oriented is difficult and is sometimes said to be difficult to get along with. The reasons for this are as follows.

2-1. Flood of terms

"Inheritance, superclasses, interfaces, attributes, overrides ..." There are so many terms that it's hard to remember at first. However, object-orientation covers a large area, so it can't be helped. It seems to be bad if you don't remember it.

2-2. Abuse of metaphor

"Animal is superclass, dog is subclass ..." "Send a message to the human object to tell me your age ..." I think you often see such examples. However, the metaphor remains as a strong impression and is misinterpreted by the actual mechanism and the beliefs of the learner.

2-3. Anything Object Syndrome

"Human, company, computer, vending machine, PET bottle, event ..." As long as it exists in this world, it can be expressed as an object. Such an extreme abstraction creates the misconception that the real world can be expressed in a program as it is.

3. Object-oriented and the real world are different

Object-oriented programming is sometimes thought of as "a representation of the real world in software." That idea is confusing in return. ** Object-oriented and the real world are similar and different **.

3-1. Things cannot be made from class

-** Object-oriented ** There is a class as a mechanism for creating an instance. Also, the instance belongs to one class. -** In the real world ** There is a concrete instance (ex. Human) first, and it is classified (class) according to the difference of the viewer. If you go to the office, you will be an office worker, if you go home, you will be a father, and so on.

3-2. In the real world, messages alone do not act

-** Object-oriented ** When you hear the message "Cry!", You will hear "Meow" and "One". Object-oriented does not go against instructions.

-** In the real world ** When you get the message "Cry!", You may hear "Meow" or "One", but you may ignore it. You may bite. In the real world, it's against orders.

Software is not meant to represent the real world, but to cover part of human work. It's about letting the computer do the ** "remembering" and "fixed work" ** that the computer is good at.

4. History of object-oriented programming

Programming technology has been devised and improved many times, and object-oriented has been born. The history of the evolution of programming technology is as follows.

4-1. Machine language

Computers can only understand ** machine language **. In the early days, humans wrote programs in machine language.

A10010
8B160210
01D0
A10410

4-2. Assembly language

** Assembly language ** has been introduced to make machine language a little easier to understand. In assembly language, machine language is replaced with human-friendly symbols.

MOV AX, X
MOV DX, Y
ADD AX, DX
MOV Z,  AX

4-3. High-level language

** High-level languages ** have emerged to make the expression even more human-friendly. With the advent of high-level languages, the productivity and quality of programming have greatly improved. However, with the explosive growth of computers, the needs did not meet. This was called the ** Software Crisis **.

Z = X + Y

4-4. Structured programming

To respond to the software crisis, ** Structured Programming ** was introduced by ** Dijkstra ** in the Netherlands. The idea of structured programming is that "in order to create a program that works correctly, it is important to have an easy-to-understand structure." To make it easier to understand, the following methods were specifically mentioned.

-** GOTO statement abolished ** The logic is expressed only by three structures: sequential progression, conditional branching, and repetition. For this reason, structured programming languages are also called ** GOTO-less programming languages **.

-** Increase the independence of subroutines ** Subroutines themselves have already been invented, but when using subroutines, it was common to pass values using global variables. Global variables reduce the maintainability and debuggerability of your program. In order to deal with this problem and make subroutines more versatile, a mechanism for ** local variables ** and ** argument pass by value ** was devised.

Structured programming languages have become commonplace for programmers, but there are still two problems that structured programming languages cannot solve.

-** Global variables ** Local variables disappear after the subroutine is called. Data that needs to be retained beyond the execution agency of the subroutine must be treated as a global variable.

-** Poor reuse ** Basic processing (subroutines) such as calculations and string processing could be reused, but that alone was insignificant given the scale of the growing application.

5. The emergence of object orientation

Object-oriented has emerged to address the problem of global variables and poor reuse. In object-oriented programming, three unprecedented mechanisms "class", "polymorphism", and "inheritance" have been added.

5-1. Class

5-1-1. Summarize

It is a mechanism to combine variables and subroutines with strong ties into one class. With this mechanism, the number of lines in one source code (part) can be reduced. It also makes it easier to name subroutines because they are grouped together as classes.

<Before object-oriented>
・ TextFileOpen()
・ TextFileClose()
・ TextFileRead()
・ JsonFileOpen()
・ JsonFileClose()
・ JsonFileRead()

<In the case of object orientation>
■ Text class
・ FileOpen()
・ FileClose()
・ FileRead()
■ Json class
・ FileOpen()
・ FileClose()
・ FileRead()

5-1-2. Hide

It is a mechanism to hide variables and subroutines defined in a class from other classes (private). By hiding it, it prevents it from being used unintentionally from the outside.

5-1-3. Make a lot

By defining a class, you can create any number of instances from it. Since the user calls the subroutine by specifying the instance, it is possible to specify which instance is to be processed.

5-2. Polymorphism

Polymorphism means "to change into various forms." Subroutines are a mechanism to standardize the logic of the called side, while polymorphism is a mechanism to standardize the calling side. Specifically, let's take a look at the following example. With the polymorphism mechanism, you can use GetNameCount () and Special Attack () for both Human and Monster. Also, if you have new creatures, you don't need to modify these methods at all.

Untitled-1.png

hoge.cs


//Count names
public int GetNameCount(Creature creature)
{
    return creature.GetName().Length;
}

//Everyone special attack!
public void AllSpecialAttack(IEnumerable<Creature> creatures)
{
    foreach (var creature in creatures)
    {
        creature.SpecialAttack();
    }
}

5-3. Inheritance

(Although I got a glimpse of the example of polymorphism) It is a mechanism to create another class by collecting the commonalities of classes of similar people. In other words, you can eliminate code duplication.

6. More advanced object orientation

In programming such as Java and C #, even more advanced functions have been created. Typical examples are "packages", "exceptions", and "garbage collection".

6-1. Package

It's a mechanism for organizing classes, like a folder. It is also possible to nest packages to create a hierarchical structure.

6-2. Exception

It is a mechanism that returns a special error from the method in a form different from the return value. Exceptions are often used for "network failure", "disk access failure", "DB deadlock", etc. In the past, the method of using an error code was common, but there were the following problems.

--It is necessary for the application to perform the error code determination process. If you forget to write the judgment process, it will be difficult to identify the cause when a bug occurs. --Error code judgment processing is scattered, resulting in a redundant program.

In the case of an exception, if you forget to write the post-processing (catch) of the exception, a run-time error will occur. Also, for methods that do not require post-processing, you only need to declare that an exception will occur. The exception mechanism has two effects: to eliminate waste and to prevent mistakes.

6-3. Garbage collection

It is a mechanism that automatically deletes unnecessary instances and frees memory. It comes with Java and C #. If you don't have garbage collection, you need to explicitly free memory. If you accidentally delete the required instance, it will lead to a bug, and if you forget to delete it, it will lead to a memory leak. Garbage collection can help you in this area.

7. Object-oriented reuse

Object orientation has brought about two reuse technologies. That is "software reuse" and "idea reuse".

7-1. Software reuse

7-1-1. Library

It is a collection of classes with general-purpose functions. In traditional programming languages, subroutines were the only reusable component, but object-orientation allows you to:

--Create an instance from a library class and use methods and variables. ···class --Replace the logic called from the library with application-specific processing. ... Polymorphism --Create a new class from the library class and add methods and variables. ・ ・ ・ Inheritance

7-1-2. Framework

It is an image of a semi-finished product of the application. It is used to call an application from the framework, as opposed to a library. The basic flow is provided by the framework and the application incorporates its own processing.

7-2. Reuse of ideas

7-2-1. Design pattern

It is a collection of good design ideas. Created by ** Eric (Erich) Gamma **, ** Richard Helm **, ** Ralph Johnson **, ** John Brisidis **. They were called ** GoF **, and the 23 design patterns they came up with were called ** GoF design patterns **. See below for more information on GoF design patterns.

-** GoF design pattern summary **

  1. UML UML stands for Unified Modeling Language and is translated as "Unified Modeling Language". Created by ** Grady Booch **, ** James Rumbaugh **, ** Ivar Jacobson **. These three people are familiarly called ** Three Amigo **. UML is used as follows.

8-1. How to use UML

8-1-1. Representing object orientation

UML is used to represent object-oriented program structures and behaviors. It is suitable for the human brain because it visually captures a two-dimensional figure. In short, UML is a ** tool for viewing intangible software **. Typical diagrams include ** class diagrams **, ** sequence diagrams **, and ** communication diagrams **. * Detailed explanation of each figure is omitted here. In software development, it is used in design.

8-1-2. Representing non-object-oriented

Information that cannot be expressed in object orientation is also expressed in UML. Typical diagrams include ** Use Case Diagram **, ** Activity Diagram **, and ** State Machine Diagram **. * Detailed explanation of each figure is omitted here. In software development, it is used for business analysis (organizing real-world work) and requirement definition (determining the scope of work to be entrusted to a computer).

8-2. UML helps communication

Natural language is used for communication between humans, and computer language is used for humans to give commands to computers. Since natural language and computer language are expressed using letters, the expression becomes complicated and the amount becomes enormous. On the other hand, UML is expressed using diagrams, so it can be understood intuitively. UML is also a language that makes up for the shortcomings of natural and computer languages. So don't try to express everything in UML, feel free to use it as a way to help communication!

9. Object-oriented design tips

The key points for creating software that is easy to maintain and easy to reuse are as follows.

9-1. Eliminate duplication

The more duplicates there are, the harder it is to understand, modify, and test the program. Duplicates tend to result in more copy and paste. In other words, be careful if you have a lot of copies. Care should be taken to avoid duplication during the design phase.

9-2. Increase the independence of parts

The trick to making complex things easier to understand is to "divide." A high degree of independence makes the function of the part clearer and easier to understand. The idea for increasing independence is as follows.

-** Cohesion ** Indicates the degree of cohesion of functions. The stronger the better the design.

-** Coupling ** Indicates the degree of connection between parts. The weaker the better the design.

Here are some tips for increasing independence.

--Make class names and method names easy to understand. --Minimize the information that the class exposes to the outside world. --Make small classes and methods.

9-3. Do not circulate dependencies

Dependencies are when one part utilizes another. None of the examples below can be compiled independently. Also, if you modify any of them, you need to check all the other Components. 1.png

In the example below, "Component C" can be used alone. Also, if you use "Component A", you do not need to check other components. 2.png

10. Conclusion

I'm the type of person who learned object-orientation through projects, so this book helped me organize the basics. In the book, the memory and development process are also described in an easy-to-understand manner, but I wanted to make it a separate article, so I omitted it here. If you are interested in object-oriented programming, please take a look at the books.

Also, I hope you can also read the following articles in the same reason series.

-** [Summary] Why does the program work **

Recommended Posts

[Summary] Why make it object-oriented?
Reading Memo "Why make it object-oriented"
[Book Review] Why make it object-oriented, 2nd edition
Object-oriented summary
Object-oriented summary by beginners (Java)
[Java] Make it a constant
Divide by Ruby! Why is it 0?
Priority Queue max Make it a queue
Summary of object-oriented programming using Java