Functional And Object-Oriented Programming Paradigm
Table of contents
No headings in the article.
Paradigm in programming means the style of writing code. Two popular paradigms are adopted by programmers while developing solutions:
Functional programming
Object-oriented programming
In functional programming, code is structured and split into various functions, in which each function has a specific thing that it does. Functions and the data they work on are separate. For functions to work on data, data is passed to them in the form of argument. Functions can also return result of their operations. An example is code to calculate a student’s grade in an exam. Student score is stored in variable score, and a function computeGrade receives the score, compute grade before returning it.
let studentScore = 0;
function computeGrade(score){
let grade;
if(score >= 80){
grade = 'AA'
}else if(score >= 60){
grade = 'BB'
}else if(score >= 50){
grade = 'CC'
}else if(score >= 40){
grade = 'D'
}else{
grade = 'F'
}
return grade
}
let grade = computeGrade(40)
console.log(grade)
Object-oriented programming, in contrast, groups both data and functions together to form a single entity called object. An object has sets of properties, and a property is a pair of key and value. Property can also be a function which is called method. Methods are functions that operate on data of the object. Within a method, data can be accessed using this operator, which is a reference to the object itself. Let me implement the student’s grade computation using object-oriented programming paradigm:
const student = {
name: 'Bello Shehu',
score: 30,
grade: '',
computeGrade: function(){
if(this.scorescore >= 80){
this.grade = 'AA'
}else if(this.score >= 60){
this.grade = 'BB'
}else if(this.score >= 50){
this.grade = 'CC'
}else if(this.score >= 40){
this.grade = 'D'
}else{
this.grade = 'F'
}
return this.grade
}
}
student.computeGrade()
console.log(student.grade)
console.log(`${student.name} score ${student.score} and was graded ${student.computeGrade()}`)
Conclusion
Functional programming is easier and more beginner-friendly, but it does not allow association of related data and functions. On the other hand, object-oriented programming is more advanced but allows related data and functionalities to be grouped together.
Kindly like and share. Thanks for reading.