Cohesion and Coupling is essential in Software Development to improve maintainability, scalability, and realibility. It is a fundamental that every software developers that should know to work with modules in software architecture. In this article, i will explain with some examples using Javascript.
Cohesion
Cohesion is a grouped module that each element inside a module is belong together. The more high level of cohesion, the more good it is. High level of cohesion have a strong readibility and more maintainably code. For example class of users is only allowed to have functions that related to its class, setting email and getting email, we dont need function that out of the class name context like validate email or get email token, because of that things is can be defined on another class like `Users Managers`
1class User {
2 constructor(name, email){
3 this.name = name;
4 this.email = email;
5 }
6
7 getUserEmail() {
8 return this.email;
9 }
10
11 setUserEmail(email) {
12 this.email = email;
13 }
14}the code above is the example of high level of cohesion because it's functions remains of it class
1class User {
2 constructor(name, email){
3 this.name = name;
4 this.email = email;
5 }
6
7 getUserEmail() {
8 return this.email;
9 }
10
11 setUserEmail(email) {
12 this.email = email;
13 }
14
15 //out of context function
16 validateEmail() {
17 //....validate email code
18 }
19}the second one is low level one example, it has validateEmail which is should not being in the `User` class. It's not recomended to write code like the second examples.
Types of Cohesion
There are several different types of cohesion used to describe how closely the elements within a module are related. These types range from the lowest level of cohesion (least desirable) to the highest level of cohesion (most desirable). Although there are many, I will focus on seven of the most commonly discussed types.
Communicational Cohesion
Communicational cohesion is one of the higher and more desirable levels of cohesion. It occurs when the components of a module are grouped together because they operate on the same data or contribute to the same output. In this type of cohesion, the functions are related by the information they use or produce, which makes the module more organized, purposeful, and easier to maintain.
1function processUserData(user) {
2 validateUser(user);
3 saveUserToDatabase(user);
4 sendConfirmationEmail(user);
5}
6
7function validateUser(user) {
8 if (!user.username || !user.email) {
9 throw new Error("Data user tidak valid");
10 }
11}
12
13function saveUserToDatabase(user) {
14 console.log(`Menyimpan user ${user.username} ke database:`);
15}
16
17function sendConfirmationEmail(user) {
18 console.log(`Mengirim konfirmasi email ke ${user.email}`);
19}
20
21const user = {
22 username: "yasuko_hanaoka",
23 email: "yasuko@gmail.com"
24};
25
26processUserData(user);
27Procedural Cohesion
Procedural cohesion is similar to sequential cohesion, but with one important difference: although the module’s elements must be executed in a specific order, the output of one function is not required to serve as the input for another. The tasks are related simply because they follow a particular procedure or step-by-step sequence. Procedural cohesion is considered a mid-level to higher-level form of cohesion, typically ranked as the fourth level in the hierarchy.
1export function startServer(port) {
2 if (!port) {
3 throw new Error("port is must be setted")
4 }
5
6 setPort(port)
7 runServer(port)
8 displayHome()
9}
10
11function setPort(port) {
12 console.log(`setting port to ${port}`)
13 return true
14}
15
16function runServer(port) {
17 console.log(`server is running at port ${port}`)
18}
19
20function displayHome() {
21 console.log("diplaying home...")
22}Coupling
Coupling refers to the degree of connection or dependency between two components, systems, or elements in a larger structure. When coupling is high, the parts rely heavily on each other, meaning a change in one component will likely affect the other; this can make the overall system harder to modify or maintain. When coupling is low, the components interact minimally and operate more independently, making the system more flexible, easier to update, and more resilient to change. The concept of coupling appears in many fields—such as software engineering, electronics, physics, and chemistry—but in all cases it describes how strongly two things are linked and how much influence they have on one another.
Control Coupling
Control coupling occurs when one module or function influences or directs the execution logic of another module. This typically happens through the use of flags, condition variables, status codes, or specific input parameters that tell the receiving module how it should operate. Because one component is controlling the internal behavior of another, control coupling is considered a tighter and less desirable form of coupling.
1
2function displayPage(page) {
3 if (page === "home") {
4 displayHome()
5 } else {
6 displayNotFound()
7 }
8}
9
10function displayHome() {
11 console.log("displaying home...")
12}
13
14function displayNotFound() {
15 console.log("displaying not-found....")
16}
17
18displayPage("home")Stamp Coupling
Control coupling occurs when one module or function dictates the behavior or flow of execution of another module. This usually happens through the use of flags, condition variables, status codes, or specific input parameters that tell the receiving module what to do or how to behave. Because one module influences the internal logic of another, control coupling is considered undesirable and indicates tighter dependency between modules.
1// struktur data kompleks
2const data = {
3 header: "How to become a software engineer in 3 mins",
4 body: "Lorem ipsum dolor sit amet constrecteur.",
5 thumbnail: "https://cdn.imageasset.net/QIOHsqhWDWsdk",
6 createdAt: "12/08/2022",
7 updatedAt: "12/08/2022"
8}
9
10function displayItem(data) {
11 const { header, body } = data
12 // hanya membutuhkan sebagian data saja
13 return {
14 header,
15 body
16 }
17}
18
19displayItem(data)
20