Web Application Fundamentals — Part 1

Photo credit: pexels.com

Introduction

When I started learning programming in school, I was introduced to FORTRAN 93. Back then, developing a FORTRAN program to solve quadratic equations using the almighty formula was a cool big deal (actually we were only writing the code in the textbook with our Plato IDE :innocent: ). The experience was an eye opener to my curious mind; when it dawned on me the vast possibilities of what I can do. I can change the world! (especially being able to do cool stuffs I had seen in movies). Back then, all my programs are limited to working on desktop computers.
Fast forward to 2017, a lot of things has changed. Most programs now run on mobile and web platforms. A pivot is required! Though I had learned #Java programming, I had developed calculator apps with varying complexities, and even designed an educational app for desktop platform that won a local award; something seems to still be missing. I don’t develop websites yet! I am discombobulated by terms like server, host, web app, templates, content management systems, etc.

Audience

This article is going to be a series. It is targeted at people who have acquired the fundamentals of programming in their language of choice and want to start developing web applications (and of course, with scale in mind).

Methodology

This is a not a ‘how to’ tutorial as it were. Rather, it is a ‘What is tutorial’. It seeks to explain the different concepts associated with web application development. Some of the terms you will be encountering as you learn different web frameworks and languages.

Prerequisites

It is desirable (but not mandatory) that you the reader would have at least learn the basics of a programming language of choice and you are seeking to advance your knowledge into web development. However, if all you want to do is just to have the knowledge, please read on too.

Programming Paradigm Associated with Web Application Development — MVC, OOP, TDD

There are generally acceptable way of doing (and organising) things in the world of web application development. In fact, this is true for software development as a whole. Come to think of it, wholisitically, software is just a set of agreed upon set of rules and thought pattern. (*have you ever imagined why 0 and 1 are used and not 2 and 3? just saying*)
So I will start by elucidating on some of these generally acceptable ways of doing things in web application development

NOTE:
I will be using a simple web applications that manage record of Students for explaining different concepts. The web app in its simplest form allows you to add new student record, update and delete student record, and also viewing all the students.

Model-View-Controller (MVC) Patter/Paradigm

The MVC software architecture pattern group all the components of a web application (or other applications that follow the pattern, but we are focused on web here) into three distinct parts that are interdependent and yet have some level of independence. One of the advantages of MVC is reusable code and separation of concerns. Let’s dive into the details of MVC.

The ‘M’ of MVC

The M stands for Model, it is the component that interface directly with your database. It is an object representation of your database table and columns (usually by a class). It contains logic for connecting to the database and performing data manipulation.
For example, If you want to add a new student to the record in our example application. You will just create a new instance of the Student model and then call a method to save the model.


//java example
Student student = new Student();
student.setFirstName(“Seun”);
student.setLastName(“Matt”);
student.setGender(‘M’);
student.save();

As you can see I didn’t write how the student is going to be persisted (persist simply mean ‘save’) to the database or what column name correlates with the properties I am setting. I also did not write any SQL to insert the data into the database table. All the logic of how to manipulate data are handled by the model.
When other parts of the web application needs to talk to the database, they do it via the model as far as MVC Pattern is concerned.
I can not but mention that, there are some technologies associated with models in MVC. One prominent term that fly around a lot is Object Relational Mapping (ORM)
Before I explain what ORM is, let’s try and implement the save method of our student model above in Java.

.
.
.
public void save() {
String sql = “INSERT INTO students_tbl (first_name, last_name, gender) VALUES (“ + firstName + “,” + lastName + “,” + gender + “)”;
java.sql.Connection con = DBUtil.getConnection();
try {
Statement stm = con.createStatement();
stm.executeQuery(sql);
} catch(Exception e) { e.printStackTrace(); }
finally {
con.close();
}
}

As you can see we actually have to write our logic to persist the data into the database. We wrote SQL and then use the mysql-jdbc connector to send this to the database.
What ORM does is that it takes care of having to write any SQL to interact with the database. So if I were to use Hibernate Java ORM to persist the data. I will not have a save method as part of my model; all I will have is a simple plain Old Java Object like this:


//I have use annotations here for hibernate to understand what’s going on
@Entity
@Table(name = “students”)
public class Student {
@Id
@GeneratedValue
private int id;
private String firstName;
private String lastName;
private String gender;
public Student() {}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
}
and for me to add a new student to the database, I will just do this:
//get a hibernate session
Session session = sessionFactory.openSession();
session.beginTransaction();
//instantiate a new Student object
Student student = new Student();
student.setFirstName(“Seun”);
student.setLastName(“Matt”);
student.setGender(“M”);
//call hibernate’s save method
session.save(student);
//commit my changes and close the db connection
session.getTransaction().commit();
session.close();

The ‘V’ of MVC

Gone are the days when computer outputs are restricted to punched cards, magnetic tapes and so on. Data output presentation has moved on from being just some coloured texts on a dark background console to involving diverse colours, images, and animations. The technology for presenting data as improved as well.Now we have HTML5, Javascript, CSS3 and loads of frameworks built on top of them — all to make data presentation beautiful and aesthetic.

So, the ‘V’ part of MVC actually stands for View. It’s where all the logic that has to do with data presentation resides. For example, in our students record example. Previously, we have been able to add new student record; now we need to see all the records that are in the database. Our application will ask the model (remember, it contains all the logic for interacting with the database) to bring up all records of students in the database (they are binaries 0s and 1s), and then the view will now present them to us, in a human readable format. as described by the View’s logic.

There are other technologies and terms associated with Views. Prominent of these terms is Template(s)/ Template Engines. I will say, a template is just a structured document with placeholders for dynamic values (dynamic values being a major difference between static web sites and web apps). There are quite a number of template engines out there. (Note: Template Engines are just program logic that defines how a view is rendered and the format of the placeholders, no big deal at all — just big tech-jargon).

For Java, we have Freemarker, Velocity Template Engine, handlebars and others. For php, there’s Blade Template Engine for Laravel web framework, CakePhp Templates for CakePhp Web Framework. In Javascript, there’s handlebars, pug (formerly known as jade) etc.
So let’s see the Templates / Template Engine at work. We want to list all the student records in that database, remember? Well that’s what we want to do.
Something like this:

A typical view that will show the table above will have a code like this


<!DOCTYPE html>
<html>
<head>
<style>
table, th, td {
border: 1px solid black;
}
</style>
</head>
<body>
<table style=”width:100%”>
<thead>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Gender</th>
</tr>
</thead>
<tbody>
<tr>
<td>Seun</td>
<td>Matt</td>
<td>50</td>
</tr>
<tr>
<td>Prodster</td>
<td>Bot</td>
<td>F</td>
</tr>
</tbody>
</table>
</body>
</html>

Now the above html code is just for 2 entries in the database. What if another student is added? How will I allow that to reflect on my table? Jump to the html file and edit it manually (also called Hard coding)? Never! That’s where template engines come to play. They let us update our views dynamically. So the same view logic above can be re-written as follows


<html>
<head>
<style>
table, th, td {
border: 1px solid black;
}
</style>
</head>
<body>
<table style=”width:100%”>
<thead>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Gender</th>
</tr>
</thead>
<tbody>
<! — laravel blade template engine →
@foreach($students as $student)
<tr>
<td>{{$student->first_name}}</td>
<td>{{$student->last_name}}</td>
<td>{{$student->gender}}</td>
</tr>
@endforeach
</tbody>
</table>
</body>
</html>

So as you can see, even if we have a thousand student records in the database, they will all be rendered appropriately. Also, we don’t have to change (or hard code) the html code (view logic) to reflect any update to the students database.

The ‘C’ of MVC

Well can you guess what the ‘C’ stands for? Noooo! it’s not ‘Carrot’. The ‘C’ Stands for Controller. You see, MVC paradigm has grouped web app into components with focused task to accomplish — Model talk to the database, View makes data human readable and aesthetic. However, in reality a view doesn’t know when to render and what to render and Model doesn’t know when to go to the database or what to fetch from the database.
Controller is the middle man. It connects the view and model together to make a wholistic web application that can function. For example:


// using Spring MVC — a java web framework
@Controller
public class HomeController {
//when you navigate to localhost:8080/ this method of
//this controller will server the view with the name ‘index’
@RequestMapping(value = “/”, method = RequestMethod.GET)
public String index() {
return “index”;
}
}

It is the controller that contains the majority of what is called business logic. The user interacts with the controller via the view (for example submitting a form) and the controller communicates with the model instructing it to persist the newly submitted user-data to the database.

Conclusion of MVC

Well, next time someone mentioned MVC, you should have a pretty general knowledge of what they are talking about.
MVC stands for Model-View-Controller and it’s a software architectural pattern.

  • The Model is responsible for interacting with the database, and contains logic for doing so. Object Relational Mapping enables you to persist data into a (relational) database with your model without writing any SQL queries or statements.
  • The View is responsible for providing an interface through which a human can interact with the web application. It presents data in human readable format. Template / Template Engines makes the view to be dynamic and reusable.
  • The Controller is the junction-box, the traffic man, that contains business logic for the overall functioning of web applications. It uses the model to get data from the database, process the data and finally output the result to the view for presentation.

In coming series, I will be discussing Test Driven Development (TDD) and Object Oriented Design (OOP). I will be touching on how these concepts affects Web Application Development.

Got questions or contributions? I’d love to read them in the comments. If you enjoy the article and look forward to coming series, let me know in the responses.

Thanks for reading! I’d really appreciate it if you recommend this post (by clicking the ❤ button) so other people can find it. If you have questions or comments, leave them in the response section below or say hello to the Author, Seun Matt
Developer? Join our slack channel Got a project idea and need remote product teams to work on it? Say hello to us via hello@prodsters.com to get started.
Part two of this tutorial can be found here — Object Oriented Programming
Show your support

Clapping shows how much you appreciated Prodsters’s story.