[JAVA] A PHP engineer who keeps improving legacy code learned about object orientation

What made me decide to write this article

I'm constantly improving my legacy code, but I'm only working on improving my legacy code, so I'd like to learn about object-orientation and output this article.

What is object-oriented?

Combining the processes required to realize the system into parts

Why object thinking is needed

--Problems in writing code

The process becomes too long and the human head does not know what it is doing. Even if you can make something that works, when you do maintenance etc. When I read it back, I don't know what I'm doing and where. → The number one bottleneck in development

The idea of object-oriented programming

――Where and what function ――How to create a system by combining the functions

Object-oriented definition

The idea of assembling the process of developing software into parts

For example, when there is an object called a train Think about what kind of movement is a train.

--The train moves --The train stops --The train door opens --The train door closes

As mentioned above, when I thought about making something called a train Think about what kind of processing is used to make a train

Three important object-oriented elements

We will utilize the above three major elements to think about how to create objects (processes) and how to link them, not what each line of the program is doing.

I will explain each of the three major elements.

Encapsulation

Assuming that there is a Vehicle class like the following, a method called moveOn is prepared.

--You only know that the caller is calling a method called moveOn --It can be said that isMove used in the method is hidden from the outside.

This kind of construction is called encapsulation.

Vehicle.java


public class Vehicle {

    private Boolean isMove = false;

    public void moveOn() {
        this.isMove = true;
        System.out.println("The vehicle moves");
    }

    public void stop() {
        this.isMove = false;
        System.out.println("The vehicle stops");
    }
}

Encapsulation is implemented by restricting reading and writing to fields and calls to methods, so changes inside the object will cause unexpected interference and influence on the outside, making it difficult to break.

Access control has the following four stages.

Strength of restriction(The more black stars, the more severe) name Description method Access permission range
★★★★ private Described as private Only my own class
★★★☆ package private Write nothing Classes that belong to the same package as you
★★☆☆ protected Described as protected Child classes that belong to the same package as you or inherit from you
★☆☆☆ public Described as public All Classes

What is inheritance

There is a Vehicle class and a Train class that inherits it as shown below. In this case, it may be called as follows.

--Vehicle: Parent class, super class --Train: Child class, subclass

Roughly speaking, extending the parent class is called inheritance.

In the Train below, moveOn is overridden and implemented independently, but stop uses the method of the parent class.

Vehicle.java



public class Vehicle {

    protected Boolean isMove = false;

    public void moveOn() {
        this.isMove = true;
        System.out.println("The vehicle moves");
    }

    public void stop() {
        this.isMove = false;
        System.out.println("The vehicle stops");
    }

    public void setIsMove(Boolean isMove) {
        this.isMove = isMove;
    }

    public void info() {
        System.out.println("vehicle(Vehicle)is");
    }
}

Train.java



public class Train extends Vehicle {
    private Boolean isOpenDoor;

    @Override
    public void moveOn() {
        if (this.isOpenDoor) {
            throw new RuntimeException("Exception error");
        }
        super.moveOn();
    }

    public void closeDoor() {
        this.isOpenDoor = false;
    }

    public void openDoor() {
        if (super.isMove) {
            throw new RuntimeException("Exception error");
        }
        System.out.println("I opened the door");
    }

    public void info() {
        System.out.println("Electric train(Train)is");
    }
}

I will actually move it.

Main.java


public class Main {

    public static void main(String[] args) {
        Train train = new Train();
        train.closeDoor();
        train.moveOn();
        train.stop();

    }
}

【result】

Since it inherits Vehicle, it can be seen that stop can be called without any problem.


The vehicle moves
The vehicle stops

Process finished with exit code 0

What is Polymorphism

Polymorphism is the treatment of different things in the same way by taking things in a big way. Simply put, treat the Trains that have appeared so far as Vehicles.

Create a new Car class and treat it as a Vehicle. (* Reuse the Train and Vehicle used for inheritance ...)

Car.java



public class Car extends Vehicle {

    private Boolean isStartEngine = false;
    private String gearMode = "NEUTRAL";

    @Override
    public void moveOn() {
        if (!isStartEngine) {
            throw new RuntimeException("The engine is not running");
        }
        if (gearMode.equals("NEUTRAL")) {
            throw new RuntimeException("I can't proceed in neutral");
        }
        super.moveOn();
    }

    public void setGear(String mode) {

        switch (mode) {
            case "NEUTRAL":
            case "DRIVE":
            case "BACK":
                gearMode = mode;
            default:
                throw new RuntimeException("The specified mode does not exist");
        }
    }

    public void info () {
        System.out.println("car(Car)is");
    }
}

Main.java


public class Main {

    public static void main(String[] args) {

        Vehicle vehicle = new Vehicle();
        Vehicle vehicleCar = new Car();
        Vehicle vehicleTrain = new Train();

        vehicle.info();
        vehicleCar.info();
        vehicleTrain.info();
    }
}

[Result] Since Vehicle is the parent class, Car / Train can be treated as Vehicle, and it can be said that it satisfies polymorphism.

Object-oriented benefits

--Easy to change the program --A part of the program can be easily diverted

Differences between procedural programming and object-oriented programming

--Procedural type that describes as instructions in order from the beginning of the program ――It is object-oriented to think about the program to be realized by parts and divide and combine the processes.

Impressions

I felt it was very important to know the basics of object-orientation in order to write code that was easy to see, understand, and secure in order to create a system that would continue to be used.

I have described the outline without using difficult words, but when actually writing the source code, there are rules for each function, so I would like to utilize them while checking them.

Recommended Posts

A PHP engineer who keeps improving legacy code learned about object orientation
About object orientation
A story about a major SIer engineer who can't write code properly created a blockbuster Android app with 600,000 downloads