[JAVA] Object-oriented that can be understood by fairies

Overview

In this article, I will explain the basics of object-oriented programming with "Fairy-san" as metaphor (</ rp> and </ rt> ) </ rp> </ ruby>. .. The programmers reading this are Fairy's Summoner (</ rp> Summoner </ rt> ) </ rp> </ ruby>. It is also the ruby> main (</ rp> master </ rt> ) </ rp> </ ruby>. Shaking ruby makes me feel cool. Let's learn what kind of fairy is a good fairy so that you can call a nice fairy.

Let's get to know the fairy

Let's take a playing card as an example.

Card.java


public class Card {
    //Field (= member variable)
    private Suit suit; //mark(Hearts, spades, diamonds, clubs)
    private int number;//Numbers(1~13)

    //Method (= function)
    public Card(Suit suit, number) {//constructor
        this.suit = suit;
        this.number = number;
    }

    public Suit getSuit() {
        return this.suit;
    }

    public int getNumber() {
        return this.number;
    }
}

Object = fairy

A fairy is an object in object orientation. A fairy is an entity that dwells in things and controls (= controls) things. In other words, all fairies are in charge of XX, XX, and XX. All human beings, such as a fairy who cleans in the middle of the night, a fairy who stays in shoes and helps people who wear them, and [Densetsu's fairy](https://wiki.ducca.org/wiki/legendary Suzuki). They will help us.

Class = magic circle

It is the magic circle that decides what kind of fairy to call. In the magic circle, not only the fairy himself but also the contract with the fairy is written. A magic circle is an object-oriented class. The fairy is ** serious and obedient **, so he will do exactly what the magic circle says. If you can write the magic circle, let's summon the fairy. The spell is "Summon! Fairy!". In the Java source code, new is the summoning spell.

//Fairy summon spell
Fairy alice = new Fairy();

Field = what you have and what you know

The field (= member variable) represents the fairy's "what he has" and "what he knows". Fairies can remember what they are and who other fairies are willing to help them. ** Fairies don't like being able to stare at their contents. ** ** It's the same as a high school girl who says, "Hey! I'm no makeup right now! It's embarrassing> <". Therefore, it is desirable that the field (= member variable) is private rather than publuc. The reason is that if it is public, you will not know when the fairy was impressed or what you are doing now, which will cause unexpected bugs. At the beginning, if you get lost, you can leave it private for the time being. If you want to see or change what the fairy has, let's exchange it via the getter / setter (named get ○○○ and set ○○○) functions.

Method = what you can do and what you can do

The method (= function) represents the "what you can do" and "what you can do" of the fairy. You can do various things such as "do this job" or "answer questions". Yes, you can write it in the magic circle (= class).

Actually, the above Trump fairy has not become a fairy yet. Just having a value and putting it in and out is just a container, and you are still interacting with things and people. Here is an example.

public staric main(String[] args) {
    Card heart = new Card(Suit.HEART, 7);//Suit is an Enum type.

    if(heart.getNumber() >= 5) {
        System.out.println("This card is 5 or above.");
    } else {
        System.out.println("This card is less than 5.");
    }
}

Next, let's take a look at the interaction between the fairy and the person.

Card.java


public class Card {
    // ...Fields and other functions are the same as above, so omitted...

    public boolean isOver(int number) {
        return this.getNumber() >= number;
    }
}
public staric main(String[] args) {
    Card heart = new Card(Suit.HEART, 7);

    if(heart.isOver(5)) {
        System.out.println("This card is 5 or above.");
    } else {
        System.out.println("This card is less than 5.");
    }
}

At best, you might think it's just one more function, but ** Fairy wants to be able to do her job on her own. ** It's not just a thing, so you can think and act for yourself. Therefore, it is better to leave the decisions related to what the fairy knows to the fairy, rather than thinking about it as a master. Create a new function and give it a nice short, easy-to-understand name.

Argument = teaching

The argument represents "teaching" to the fairy. Let's teach the fairy what you need through the arguments. As I mentioned earlier, fairies want to be able to do their jobs on their own, so less teaching (= arguments) is better. If you want to teach the same thing over and over again, it is better to teach it through the constructor, add ○○○ function, and set ○○○ function in advance so that you can use what you have learned. Let's leave the work to the fairy ~~ throwing the whole thing ~~. That way, both the fairy and the master will be happy.

Error = dangerous things and things you shouldn't do

Errors (= exceptions) are "dangerous things" for the fairy and the master, and "don't do" for the fairy. The fairy is a hard worker, but as a result of trying too hard, the master may be in trouble. I'm very worried if I get lost or go where I shouldn't. It is an error to prevent it. If the fairy is about to do something dangerous, stop it. However, it is best to write a magic circle (= class) so that dangerous things do not happen in the first place, rather than stopping if there is a dangerous thing.

A good fairy is small and beautiful

A good fairy is small and slim. Being small means that the code is short. The more work a fairy is in charge of, the longer the source code will be, and the bigger the fairy will be. Another reason for the fairy to get fat is the duplication of code. Let's diet by creating a function to put together the overlapping part or sharing the work with a new fairy. The goal is to be able to answer the question "What does this fairy do?" In one sentence. It's better to let a lot of little fairies do the work than to let a fat fairy do a lot of work. Let's make a fairy harem. On the other hand, a very fat fairy becomes ** God </ font> **.

  • Image image *

God Fairy is a troublesome fairy who is entrusted with the work but does not understand why it is moving. It is the existence that the ancient masters call and scare the active masters. If you try to get God Fairy to do something new, you will create a huge number of bugs and their possibilities, and it will be a pain to fix, no, a hundred. So when writing a new magic circle, don't make a ** god. ** ~~ This line is cool ... ~~ This kind of "do not know" in programming is called ** anti-pattern **. Conversely, the recommended methodology is called ** Design Pattern **. The most famous is called GoF (Gang of Four), and there are 23 in total. Once you understand the syntax of your program, it's a good idea to look it up.


Clean code is code that is easy for the master to read (highly readable). Programmers have aesthetics in their source code, just as mathematicians find beauty in mathematical formulas. There are various techniques such as shallow indentation and proper name. The trick to making a small and beautiful fairy is to search and learn with ** refactoring **.

Summary

The fairy wants to think and act on her own. Let's leave the work to the fairy as much as possible. And let's try to create a mechanism so that many small and beautiful fairies can cooperate.

in conclusion

I think it's better to study refactoring first than to study object-orientation **. Knowing what to do makes it easier to understand what object orientation is for. I learned about refactoring after studying the basics of object-oriented programming and design patterns, but after studying refactoring, I became able to understand those patterns and ideas more clearly.

Well then, we look forward to your likes, impressions and comments.

Recommendations & References

① After reading this article, I thought that there are people who have the same idea, so I decided to write this commentary. You can also see what kind of philosophy object-oriented was created from. https://qiita.com/s_yuche/items/d46c7c843a56e6b2ebb7

② It will tell you what kind of fairy is good as seven virtues. I can't say that everything is so, but there are many things that I can understand. https://www.kaitoy.xyz/2015/10/28/seven-virtues-of-good-object/

③ I studied refactoring in [this book](https://www.amazon.co.jp/ refactoring-safely improve existing code-OBJECT-TECHNOLOGY-Martin-Fowler / dp / 427405019X) .. I highly recommend it. However, there were some places where the code was omitted and the contents were a little old. Therefore, we recommend this one with almost the same content. [[Amazon] Introduction to Refactoring Learned in Java Language](https://www.amazon.co.jp/ Introduction to Refactoring Learned in Java Language-Hiroshi Yuki / dp / 4797337990 /)

Recommended Posts

Object-oriented that can be understood by fairies
Basic functional interface that can be understood in 3 minutes
Java (super beginner edition) that can be understood in 180 seconds
Mecab installation that can be done almost by typing a command
Introduction to Java that can be understood even with Krillin (Part 1)
Organize methods that can be used with StringUtils
[Ruby] Methods that can be used with strings
Try to save the data that can be read by JavaFX as PNG
Write a class that can be ordered in Java
"Inheritance" that even beginners of object-oriented programming can understand
About the matter that hidden_field can be used insanely
Private methods can or cannot be overridden by public methods
Polymorphism that even beginners of object-oriented programming can understand
Convenient shortcut keys that can be used in Eclipse
I tried a puzzle that can only be solved by the bottom 10% of bad engineers
Summary of css selectors that can be used with Nookogiri
List of devices that can be previewed in Swift UI
Create a page control that can be used with RecyclerView
Create a jar file that can be executed in Gradle
Firebase-Realtime Database on Android that can be used with copy
Problems that can easily be mistaken for Java and JavaScript
Introduction to Rakefile that can be done in about 10 minutes
Find a Switch statement that can be converted to a Switch expression
It seems that MDC can be propagated between applications by using context together with Spring WebFlux.
Object-oriented design that can be used when you want to return a response in form format
How to make a key pair of ecdsa in a format that can be read by Java