Day 8: public, private, internal or external

As you can have noticed, I posted pretty regularly from Day 1 to Day 7.

Even thought there is a 10 day gap between Day 7 and Day 8, there were a few days in between where I studied a little bit…just not enough to make a blog post.

As far as today, I spent a lot of time on Module 49 (Udemy Course 2 – Andrei Dumitrescu). I watched this video very slowly and took notes by hand (as you see below) along the way. In this video, he discussed in great detail the difference between labelling a variable as public, private, internal or external.

I had been seeing these terms since Day 1. And even though I had a vague understanding, I didn’t feel like I knew the terms completely and thought it made sense to MAKE SURE I reeeeeally understood it.

Let’s looking at the following program.

//SPDX-License-Identifier: GPL-3.0
 
pragma solidity >=0.5.0 <0.9.0;
 
contract A{
    int public x = 10;
    int y = 20; // internal by default

function get_y() public view returns(int){
    return y;
}

function f1() private view returns(int){
    return x;
}

function f2() public view returns(int){
    int a;
    a = f1();
    return a;
}

function f3() internal view returns(int){
    return x;
}

function f4() external view returns(int){
    return x;
}

function f5() public pure returns(int){
    int b;
    // b = f4(); //f4() is external
    // Even though f4() wasn’t external it wouldn’t be possible to be called 
    // from within f5() because f5() is pure (it can not read nor write to the blockchain)

    return b;


 }
}
 
contract B is A{
    int public xx = f3();
    // int public yy = f1(); -> f1() is private and cannot be called from derived contracts
}
 
contract C{
    A public contract_a = new A();
    int public xx = contract_a.f4();
    // int public y = contract_a.f1();
    // int public yy = contract_a.f3();
}

I will say the above page is pretty readable, but the second page of notes (below) isn’t. So, I’ll write out the key parts, N1, N2, N3 and N4.

N1 = See NOTES (N4) at the bottom of the page. A contract that deploys another can not call its internal variables, BUT a contract that is derived from another can call its internal variables.

N2 = external variables can’t be called from the contract it was declared. It can only be called from outside contracts and applications. External functions care more efficient in terms of gas consumption.

N3 = This [line of code represents] a contact that deploys another contract

N4 = f4 could be called, but not f1 (because it’s private) and f3 can’t be called (because it’s internal….meaning it can’t be called by other contracts)

Leave a Reply