Introduction
Solidity is an object oriented programming language which we use to write smart contracts on the blockchain. This is the first part of my mini-series about the programming language solidity. The only prerequisite is a little programming experience with another language, if you have that this mini series should be fairly easy, let us dive in:
Contracts
Contracts are the most fundamental building blocks of Ethereum applications. All the functions required to make a smart contract work resides inside a contract. Below is the basic structure of a contract:
contract heyGuys{
}
State variables
State variables are variables that are permanently stored in a contract. Think of this as something similar to writing to a database(the blockchain is similar to a database but it isn't owned by a particular person or entity). I'll show you an example below:
contract heyGuys{
//uint stands for unsigned integer, this means its value must be a non-negative
uint myNumber = 100;
}
Structs
Structs allow us to store my complex data types with multiple properties. Below I'll show you an example of a struct:
struct Me{
uint age;
string name;
}
Arrays
In solidity we have two types of arrays (I'm assuming you already know what an array is so I'll skip that)fixed and dynamic. Below I'll show you an example of both types:
// this is a fixed array. This means that it has fixed length of 5 elements
uint [5] fixedArray;
//this is a dynamic array. This means that the array will have no fixed size, it can keep growing
uint [] dynamicArray;
We can also create an array of structs, this is basically an array that can store complex data types with many different properties. Below I'll show you the syntax for this:
Student[] school;
Functions
I'm assuming that we already know what a function is but if you don't, functions are bits of reusable code we use to limit the amount of lines of code we have to write, when functions are called they perform a specific task and nothing else. Below is how we write functions in solidity:
function myName(){
}
Private and Public
In the solidity programming language functions are public by default, this simply means that anyone can call your contract's functions and execute their code. This comes with drawbacks that we may not want so a good practice is to make your functions private until you're ready to put it on the blockchain. Private functions are functions that can only be used inside of its parent's function or module. Below I'll show you an example of both:
function _myName() private{
}
function myName() public{
}
Notice any difference? if not that's fine, when we are writing private functions in solidity we must adhere to the name conventions of putting an underscore before the name of the function.
Conclusion
I've provided you with the most basic building blocks of solidity code. In the next versions of this mini-series I will go deeper into solidity, stay tuned.