(For super beginners) Getter / setter and property to think in D language

Java getter / setter I thought it was long and UZEEEEE !!!!, but I found articles like this, which made me think a little. So I'll think about it in my favorite (not good) D language.

About Java getters / setters

Since it is Tama Science and Technology AC, I will explain object-oriented programming and Java for the time being. The main subject is from [here](in #d language).

Object-oriented programming is one of the guidelines for software design, and is the idea that "everything is an object (an entity that can group related data and perform assignments, conversions, functions, etc.)". According to Alan Kay, who used the word for the first time,

  1. Everything is an object.
  2. Objects communicate by receiving and answering messages.
  3. The object has its own memory.
  4. Every object is an instance of a class, and a class is also an object.
  5. The class has a shared behavior for all its instances. Instances are the form of objects in a program.
  6. When the program runs, control is passed to the first object and the rest is treated as its message.

It seems.

Access right

The blueprint for an object is the class, and nothing starts without writing it first.

Test1.java


class Student{
    public String name;
    public int number;

    Student(String name, int number){
        this.name = name;
        this.number = number;
    }
}

public class Test1{
    public static void main(String[] args){
        Student taro = new Student("Teraoka Taro",27);
        Student jiro = new Student("Yamashita Jiro",35);
        System.out.println("taro's name:" + taro.name);
        System.out.println("jiro's number:" + String.valueOf(jiro.number));
    }
}

It's a different story that Java wrote String as string after a long time.

Student is a ** blueprint ** of student data, and the new taro and jiro in main are ** objects (instances) ** that are the entities. The data organized by class is called ** member **. Name and number in Student are also members (member variables). Probably the name and student number respectively. There is a method called Student (string, int) in the Student class. The method with the same name as the class is called the constructor, and it is called when the object is created (this time at new Student (~) ...).

The keyword public is prepended to the member variables. These are called access modifiers. There are several types, but for the time being

--public: accessible from anywhere --private: Can only be accessed from within your class.

All you have to do is hold it down. If name and number of Test1.java are set to private

Test2.java


class Student{
    private String name;
    private int number;

    Student(String name, int number){
        this.name = name;
        this.number = number;
    }
}

Tried to compile


$ javac Test2.java
Test2.java:15:error:name is privately accessed by Student
        System.out.println("taro's name:"+taro.name);
                                              ^
Test2.java:16:error:number is privately accessed by Student
        System.out.println("jiro's number:"+String.valueOf(jiro.number));

It will be.

Encapsulation

If all the members are public, it will be a lot of trouble. For example, for Test1.java, you can also do this.

taro.number = -23;
jiro.name = null;

Schools that use negative values for student numbers have a good personality twist. It's even more ridiculous to have a null name. Anyway, a programmer's mistake (or malicious intent) may cause such a bug.

Therefore, it is conceivable to make all member variables private and prepare another member method to access them.

Test3.java


class Student{
    private String name;
    private int number;

    Student(String name, int number){
        this.name = name;
        this.number = number;
    }

    public String getName(){return name;}
    public void setName(String name){
        assert name != null;
        this.name = name;
    }

    public int getNumber(){return number;}
    public void setNumber(int number){
        assert number > 0;
        this.number = number;
    }
}

public class Test3{
    public static void main(String[] args){
        Student taro = new Student("Teraoka Taro",27);
        Student jiro = new Student("Yamashita Jiro",35);
        jiro.getNumber(-5)
        System.out.println("taro's name:" + taro.getName());
        System.out.println("jiro's number:" + String.valueOf(jiro.getNumber()));
    }
}

Tried to run


$ javac Test3.java
$ java -ea Test3
Exception in thread "main" java.lang.AssertionError
	at Student.setNumber(Test3.java:18)
	at Test3.main(Test3.java:27)

You can check it when you reset it properly (although you can do it with the constructor). Such member methods are called getters / setters.

getter / setter long

Now, let's try adding scores for Japanese, math, and English to the Student class.

Test3add.java


class Student{
    private String name;
    private int number;
    private int japanese;
    private int math;
    private int english;

    Student(String name, int number){
        this.name = name;
        this.number = number;
    }   

    public String getName(){return name;}
    public void setName(String name){
        assert name != null;
        this.name = name;
    }   

    public int getNumber(){return this.number;}
    public void setNumber(int number){
        assert number > 0;
        this.number = number;
    }   

    public int getJapanese(){return japanese;}
    public void setJapanese(int japanese){
        assert japanese >= 0 && japanese <= 100;
        this.japanese = japanese;
    }   

    public int getMath(){return math;}
    public void setMath(int math){
        assert math >= 0 && math <= 100;
        this.math = math;
    }   
    public int getEnglish(){return english;}
    public void setEnglish(int english){
        assert english >= 0 && english <= 100;
        this.english = english;
    }
}

Cusso If this were 10 subjects ... hell. So let's get back to the beginning.

In D language

property For the time being, let's rewrite Test3.java using property.

test3.d


class Student{
    private string _name;
    private int _number;

    @property{
        void name(string _name){
            assert(_name!=null);
            this._name=name;
        }
        string name(){return _name;}

        void number(int _number){
            assert(_number>0);
            this._number=_number;
        }
        int number(){return _number;}
    }

    this(string _name, uint _number){
        this._name=_name;
        this._number=_number;
    }   
}

Hmmm, the length of the cord doesn't change much, right? However, property allows you to easily manipulate variables as if you were playing with them directly.

test3.d(Continued)


void main(){
    import std.stdio;
    Student saburo=new Student("Mukai Saburo",18);
    saburo.name.writeln;
    saburo.number=-1;
    saburo.number.writeln;
}

Run


$ ./test3
Mukai Saburo
[email protected](16): Assertion failure
(The following is omitted)

I also got an Assert Error.

invariant However, it is not so much as it is. So, I learned about the existence of ʻinvariant` that can determine the invariant condition of a member, so I will use it. The inside of invariant is called at the following times.

--After executing the constructor, before executing the destructor --Before and after executing the member function

test4.d


class Student{
    private string _name;
    private int _number;

    invariant{
        assert(_name!=null);
        assert(_number>0);
    }   

    @property{
        void name(string _name){
            this._name=name;
        }
        string name(){return _name;}

        void number(int _number){
            this._number=_number;
        }
        int number(){return _number;}
    }   

    this(string _name, uint _number){
        this._name=_name;
        this._number=_number;
    }   
}

void main(){
    import std.stdio;
    Student saburo=new Student("Mukai Saburo",18);
    saburo.name.writeln;
    saburo.number=-1;
    saburo.number.writeln;
}

Run


$ ./test3
Mukai Saburo
[email protected](9): Assertion failure
(The following is omitted)

Good work. Of course, you can also check the constructor, so you don't have to put ʻassert` there. By the way, it seems that this way of writing is also possible from v2.081.0 of dmd.

invariant(_name!=null);
invariant(_number>0);

reference

Qiita: Do you need getters / setters after all? Don't you need it? dlang.org: Contract Programming

Recommended Posts

(For super beginners) Getter / setter and property to think in D language
[For super beginners] The minimum knowledge you want to keep in mind with hashes and symbols
[For beginners] How to debug in Eclipse
[Java] [For beginners] How to insert elements directly in a 2D array
[For super beginners] How to use autofocus: true
[For beginners] DI ~ The basics of DI and DI in Spring ~
[For beginners] Minimum sample to display RecyclerView in Java
Introduction to Java for beginners Basic knowledge of Java language ①
How to use GitHub for super beginners (team development)
How to use the getter / setter method (in object orientation)
Store in Java 2D map and turn with for statement
[For beginners] Explanation of classes, instances, and statics in Java
[Java] Change language and locale to English in JVM options
[For super beginners] DBUnit super introduction
[For super beginners] Ant super introduction
[For super beginners] Maven super introduction
[For beginners] Here are some references related to technology and career.
[Tips] How to solve problems with XCode and Swift for beginners
[For beginners] Minimum sample to update RecyclerView with DiffUtils in Java
How to install the language used in Ubuntu and how to build the environment
[For beginners] Introducing the procedure to Hello, World in C/C ++ language using Visual Studio Code on Ubuntu