Visual Home Home

Keys of Functions

Modularity and Reusability are said to be the reason for functions existence. Think for a moment, that Rect function that you/we call everytime when a rectangle is required has to written manually. On top of it, imagine creating loop around that. How will you code look... Not Pretty!!!

Modular Page

This page is built in a modular style. The texts and the images are sitting inside the imaginary rectangles or squares that are created by calling some functions. Same way we the programmer can write lot more functions to make the awesome ideas we have into reality.

    function draw() {
      background(220);
      //Following code can be a function
      fill(25,250,125)
      circle(loca.x, loca.y, 50)
      stroke(5)
      //this block can be a function
      loca.x += loca.xSpeed
      loca.y += loca.ySpeed
      //let control function be this block
      if (loca.x > width || loca.x < 0){
         loca.xSpeed = -1 * loca.xSpeed;
       }
      if (loca.y > height || loca.y < 0){
        loca.ySpeed = -1 * loca.ySpeed;
       }
    }
  

Did you notice how the block code above looks concise, but the block written with function is more longer. Lets see the power of functions now. How can you increase the balls speed?In the non-functional method, you will have to change the speed values. In case of functions, adding another moves() call to the code will increase the speed try it...

      function draw() {
        background(220);
        //these three can be made into function making
        create()
        //this again is a seperate function of moving
        moves()
        // lets control by using the following code
        control()
      }
      function create(){
        fill(25,250,125)
        stroke(5)
        circle(loca.x, loca.y, 50)
      }
      function moves(){
        loca.x += loca.xSpeed
        loca.y += loca.ySpeed
      }
      function control(){
        if (loca.x > width || loca.x < 0){
          loca.xSpeed = -1 * loca.xSpeed;
        }
        if (loca.y > height || loca.y < 0){
          loca.ySpeed = -1 * loca.ySpeed;
        }
      }
    

Parametric Playing

Reusability!!!Tables can come all sorts of sizes. I real world, it takes lots of time to make a table from plastic, wood or even with paper. If the size needs to change, then work needs to be done. Not in P5 or in Programming.

Function accept Arguments

Unlike regular humans who don't accept our arguments if they not logical, computers do accept the arguments blindly and process it. That is the result of the awkward table there on right top... Our function here doesn't logically check the values that it is getting. In real world, these values needs to be checked befor use.

We have seen different type of function like random() and map() which return values that can be assigned to variables. To write such a function, we need to add a return statement to your own functions,