Rules You Should Follow When Building Web Apps

Writing software code that is clean and maintainable will make your life and other developers’s lives that may work on your project later easier and sometimes improve the application performance and decrease the memory space it consumes, let me demonstrate more…

Note: The upcoming examples are written in PHP but it can be applied to any programming language.

1. Do not create additional variables if it is not necessary:

Let’s say you have an action in your controller that gets the user id from the request and sends it to a view, so you may write it like this:

class ProfileController{
// GET or POST request
private $request;
public function profile() { $user_id = $this->request['id']; return view('profile', $user_id); }
}

Problem: having additional variables that you don’t need that takes an extra space in the memory.

Solution: send the id directly to the view without creating new variables.

public function profile(){    return view('profile', $this->request['user_id']);}

2. DRY(Do not Repeat Your code):

My college professor always said:

“If you are copying and pasting code know that you are doing something wrong.”

Let’s say that you have a variable in your views that is responsible for printing any message coming from the their controllers, so your views may look like this:

register.view.php:

/* Some code */
<?php if (isset($message)): ?> <h3><?= $message ?></h3><?php endif; ?>/* The rest of code */

login.view.php:

/* Some code */
<?php if (isset($message)): ?> <h3><?= $message ?></h3><?php endif; ?>
/* The rest of code */

Problem: duplicate code.

Solution: create a file called message.php and require it in both views:

<?php if (isset($message)): ?>    <h3><?= $message ?></h3><?php endif; ?>

and both views will look something like this:

/* Some code */<?php require 'message.php' ?>/* The rest of code */

Another Example: let’s say you have two controllers that needs a request as a dependency, you may write your code like this:

class RegisterController{
// GET or POST request
protected $request;
// Inject the request into your controller
public function __construct($request) { $this->request = $request;
}
// Create a new object from the RegisterController public static function load($request) { return new static($request); }
/* Some other methods... */}class ValidationController{ protected $request;
public function __construct($request) { $this->request = $request;
}
public static function load($request) { return new static($request); }
/* Some other methods... */}

Problem: repeated some code in both controllers makes the code less maintainable and less readable.

Solution: create an abstract class that contains the shared code and let both controllers inherit from this class.

abstract class BaseController{ 

// GET or POST request
protected $request;
// Inject the request into your controller public function __construct($request) { $this->request = $request;
}
public static function load($request) { return new static($request); }}class RegisterController extends Controller
{
/* Controller methods */}class ValidationController extends Controller
{
/* Controller methods */}

3. If you need a dependency in most/all of your class methods, inject it in the constructor not in the methods:

Let’s say you have a user model that needs the data to insert it into the database, so you have two options to inject the request into the model:

The Wrong Way:

class User
{
private function getUserAddress($request)
{
// Some code
}

private function getUserInformation($request)
{
// Some code
}
}

Problem: it’s very overwhelming to do that because you need to inject $request in every method that needs it.

Solution: inject it in the class constructor.

class User
{
private $request; public function __construct($request) { $this->request = $request; } private function getUserAddress()
{
// Some code that uses $this->request
}

private function getUserInformation()
{
// Some code that uses $this->request
}
}

4. Visibility:

-If you only use the attributes and methods in the class itself make them private, but the question is when to make the method private?

The answer: when you need it in another method but you don’t need it outside the class.

-Make them protected if you wish to use them in the sub-classes.

5. Naming conventions:

  • Variables and Functions should follow the camelCase convention.
  • Classes should follow the PascalCase convention.
  • Database names, tables names, columns names should follow the underscore convention: product_details.
  • Foreign Keys: always end them with _fk: role_fk
  • Constants should follow all-upper convention: PI_NUMBER

6. Try to make your methods generic as possible:

Let’s you want to create a method that inserts data into database tables, instead of creating a method for every table, create a generic one:

public function insert($table, $parameters){    $sql = sprintf(        "INSERT INTO %s (%s) VALUES (:%s)",         $table,                  implode(', ', array_keys($parameters)),         implode(', :', array_keys($parameters))    );    $this->pdo->prepare($sql)->execute($parameters);}

The sql statement will look something like this:

“INSERT INTO users (name, age, email) VALUES (:name, :age, :email)

And this will help you write less code.

AAAAAAND That’s it.

I wanna say that Jeffrey Way helped me a lot in writing cleaner code, so if anyone wants to learn PHP and Laravel, check these two series(FREE):

  1. The PHP Practitioner
  2. Laravel From Scratch