This is a continuation of my earlier blog post titled A Beginner’s Guide to Reading Code - Part 1. If you have not read the Part 1, read that and come back here. It won’t take too long, I promise 😋
I am copy-pasting the list of programming core concepts from the Part 1, just for your reference.
- Constants
- Variables
- Operators
- Conditionals (if, switch)
- Loops (while, for)
- Functions
- Classes
- Objects
Topics 1-4 have been covered already. We will cover from points 5 and 6 in this part. The points 7 and 8 will be covered in the next part.
Outline of this post
5. Loops
Loop is nothing but running the same code multiple times. Almost every programming language has keywords reserved for looping. They are while
and for
. Let us see some examples of these keywords.
// This piece of code is to count the number of candies and stop after 5 candies
int candyCount=1;
while(candyCount <= 5){
System.out.println("You have taken "+ candyCount + " candies.");
candyCount = candyCount + 1;
}
System.out.println("That is enough. No more candies now.");
// This program prints the following:
// You have taken 1 candies
// You have taken 2 candies
// You have taken 3 candies
// You have taken 4 candies
// You have taken 5 candies
// That is enough. No more candies now.
In the above code, the two lines between the {
and the }
will be run as long as the condition inside the while
i.e., candyCount<=5
is true. The moment the condition becomes false, the loop is exited and the next line that prints “No more candies” is executed.
Also, note that we are intentionally incrementing (adding 1) the candyCount
variable in the second line of the loop, i.e., candyCount = candyCount +1
. The same statement can be written as candyCount++
also. This short notation is more common when writing loops.
In the case of Javascript, the same code can be written except for the following two changes.
- Instead of
int
, we usevar
to create the variablecandyCount
- Instead of
System.out.println
, we useconsole.log
Now, let us look at an example of for
loop in Java.
System.out.println("Execution starts here");
for(int candyCount=1; candyCount<=5; candyCount++){
System.out.println("You have taken "+ candyCount + " candies.");
}
System.out.println("That is enough. No more candies now.");
// This program prints the following:
// Execution starts here
// You have taken 1 candies
// You have taken 2 candies
// You have taken 3 candies
// You have taken 4 candies
// You have taken 5 candies
// That is enough. No more candies now.
This code does the same work as the previous code sample.
The for
statement has 3 parts separated by semi-colons (;
)
- The first part is the counter initialization
int candyCount=1
- The second part is the condition upon which the loop should be terminated
candyCount<=5
- The third part is the code that needs to run after the end of every run of the loop. Here, we increment the
candyCount
variable by writingcandyCount++
6. Functions
In theory, we can write one line of code after another, and then another line and then another, and so on. The computer will execute one line after another and our code will accomplish its goal. However, there is a way to make code more readable and avoid duplicate code.
Let us see a concrete example. Take a look at the following code:
var name=""; //Yes, an empty string, just for fun :)
var greeting = ""; //Woah! Another empty string! Someone is feeling fresh today!
name = "John"
greeting = "Hello " + name;
console.log(greeting); //Did you know that this is Javascript code?
name = "Ram"; //Remember? We already initialized name as a String. We can directly assign value now
greeting = "Hello" + name; //if we don't do this, next line will still print John
console.log(greeting);
name = "La Guerta";
greeting = "Hello" + name;
console.log(greeting);
Now, the above code has two lines, namely, greeting = ....
and the console.log
line, repeated multiple times.
What’s the problem here?
The problem with repeating the same code again and again (also called duplicating the code) is that it opens up more opportunity for bugs, as one might change the code only in one place and forget in another place.
Who knows? Our last character in the code, La Guerta, may react badly when Ram is greeted with a “Namaste” (his own language) in the future version of our code, while she doesn’t get greeted in Spanish (her own language).
In order to avoid a few enraged users, the programmers use something called a function
. Function takes an input and returns some output. You can call it any number of times. Write a function once, call it many times.
Let us see the same code example using function
keyword.
//define the function once
// In the line below, greetPerson is our new function's name
// And, name is the input/parameter to the function
function greetPerson(name){
var greeting = "Hello " + name;
return greeting; //This will be returned as result to the caller. The caller can use the returned value for something later.
}
//Run the function multiple times with different inputs
var johnGreeting = greetPerson("John"); //Simplest style of function calling
console.log(johnGreeting);
//There is another style possible. You can write the function call inside another function
console.log(greetPerson("Ram")); //Yaay! The same function is run again
console.log(greetPerson("La Guerta"); //Third run
//This just means that call the greetPerson, pass its return value as input to console.log
The brackets (
and the )
are used to call/execute an already defined function.
And, you guessed it right! console.log()
is also a function, that is already defined in Javascript. Since it is already defined in Javascript, we don’t have to define what it means.
In the case of Java, the syntax is slightly different. You can see people writing the input and output data types also. For example, for the greetPerson
function above,
- Input data type - String - Written inside the brackets
()
- Output (return data type) - String - Written before the function’s name
So, the Java code looks like this:
String greetPerson (String name){
String greeting = "Hello" + name;
return greeting;
}
Note that there is no function
keyword in Java. You can define your functions without using the word function
.
If there was another function that takes two integers as input and one string as return value, you could write the function as follows:
String myFunction (int a, int b){
// ... some code
}
Now, let us do one more exercise. Try to read this function and tell me what it does.
int add(int a, int b, int c){
return a+b+c;
}
Now that you know loops and functions now, it will be easy for you to understand objects classes when you read my next post.
4 More Mindset Hacks
I already told you a few mindset hacks for reading code. Now, let us see some more.
1. Reading code to understand is different from reading code to review
When you read a piece of code to understand what a person has written, it is done to get information. Whereas, while reviewing someone else’s code, it is done to find improvement opportunities. Reviewing code needs you to constantly verify if the code does what it says it does.
For example, while reviewing the following line of code
var interest = calculateInterest();
The reviewer will actively look to prove that the function calculateInterest()
does not actually calculate the correct interest, whereas the person who reads to understand won’t try to actively question everything.
2. Believe what the code tells you (unless proven wrong)
Most of the time, people get too overwhelmed when they see code because they don’t believe what they read.
For example, when you see a line of code that reads
var interest = calculateInterest();
You don’t have to be bothered about if it really calculates the interest or the steps it uses to calculate interest. You can just believe that it calculates the interest correctly and stores it in the variable named interest
. We read code to understand it and not to verify if it was written correctly. Remember that we are trying to read code, not review it.
3. Zoom in only when you can’t progress without zooming in
This is an extension of point #1 above. Every code has multiple layers of truth, more often than not. For example, you may read the code var interest = calculateInterest();
Now, if you zoom in on what the calculateInterest()
function does, you see that it in turn calls findSpecialCaseInterest()
.
And, when you zoom in further on the findSpecialCaseInterest()
it may call some other function in some other class, and this rabbit hole goes deep 😅
Now, all I am saying in this tip is this - Don’t zoom in if you have already understood what the function does, even a vague idea. Zoom only when you cannot understand the code from the name of the variables and functions. This will save you a lot of headaches.
4. It is ok to ignore what you don’t understand and proceed further
Remember? We are trying to read code, not review it. In case we come across a line of code that looks extremely complex, or which does not make any sense, feel free to ignore it and proceed to the next line. Many programmers also do this.
Many times, the cryptic line’s meaning will be understood/inferred after you read the next few lines of code. So, don’t fixate on what you don’t understand. Proceed to read and you will most likely understand what the code does.
Practice Exercises
- Read this code and make sense of it.
- Read this code and make sense of it.
- This one should be a cake walk for you now 😛
In the next post, we will dive into the concepts of Objects & classes. Congratulations for making it upto here 🎉🎉
Hey 👋 liked the stuff here?
Subscribe to updates from Tech Coach Circle here.