Unit 3: Menyusun Fungsi, File, dan Sumber Daya Pemrograman

Mempelajari cara menyusun kode yang modular dan terorganisir dengan struktur direktori yang profesional dan konvensi penamaan yang konsisten.

Estimasi: 6 Jam 3 Sub Materi

Tujuan Pembelajaran

  • Memahami modularisasi kode yang efektif
  • Menyusun struktur direktori profesional
  • Menerapkan konvensi penamaan yang konsisten
  • Menulis komentar kode yang informatif

1. Modularisasi Kode

Prinsip Modularisasi

Modularisasi adalah teknik memisahkan kode menjadi bagian-bagian yang independen dan dapat digunakan kembali.

Separation of Concerns

Setiap modul memiliki tanggung jawab spesifik

Reusability

Kode dapat digunakan di berbagai tempat

Maintainability

Mudah dipelihara dan di-debug

Pemisahan HTML, CSS, dan JavaScript
HTML
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="css/style.css">
</head>
<body>
    <div id="content">
        <h1>Konten</h1>
    </div>
    
    <script src="js/main.js"></script>
</body>
</html>
CSS
/* css/style.css */
#content {
    max-width: 800px;
    margin: 0 auto;
    padding: 2rem;
}

h1 {
    color: #333;
    font-size: 2rem;
    margin-bottom: 1rem;
}
JavaScript
// js/main.js
document.addEventListener('DOMContentLoaded', function() {
    const content = document.getElementById('content');
    
    function initApp() {
        console.log('App initialized');
    }
    
    initApp();
});
Include dan Require di PHP
<?php
// includes/config.php
$host = 'localhost';
$database = 'myapp';
$username = 'user';
$password = 'pass';

// includes/functions.php
function sanitizeInput($data) {
    return htmlspecialchars(trim($data));
}

function formatDate($date) {
    return date('d/m/Y', strtotime($date));
}

// index.php
<?php
require_once 'includes/config.php';
include 'includes/functions.php';
include 'includes/header.php';

// Kode utama aplikasi
$name = sanitizeInput($_POST['name'] ?? '');
echo "Hello, " . $name;

include 'includes/footer.php';
?>
Perbedaan Include vs Require:
  • include: Jika file tidak ditemukan, tampilkan warning dan lanjutkan
  • require: Jika file tidak ditemukan, stop eksekusi (fatal error)
  • include_once/require_once: Hanya include file sekali saja

2. Struktur Direktori Proyek

Struktur Folder Standar

Organisasi folder yang baik membuat proyek mudah dipahami dan dikembangkan oleh tim.

Struktur Proyek Web Sederhana
my-website/
index.html
about.html
contact.html
css/
style.css
responsive.css
js/
main.js
utils.js
img/
logo.png
hero.jpg
assets/
favicon.ico
Struktur Proyek PHP
php-project/
index.php
includes/
config.php
functions.php
header.php
footer.php
pages/
about.php
contact.php
css/
js/
uploads/
database/
schema.sql
Template Header dan Footer
includes/header.php
<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo $pageTitle ?? 'My Website'; ?></title>
    <link rel="stylesheet" href="css/style.css">
</head>
<body>
    <header>
        <nav>
            <a href="index.php">Home</a>
            <a href="pages/about.php">About</a>
            <a href="pages/contact.php">Contact</a>
        </nav>
    </header>
    <main>
includes/footer.php
    </main>
    <footer>
        <p>© <?php echo date('Y'); ?> My Website. All rights reserved.</p>
    </footer>
    
    <script src="js/main.js"></script>
</body>
</html>
Penggunaan Template
<?php
// pages/about.php
$pageTitle = "About Us - My Website";
include '../includes/header.php';
?>

<section class="about">
    <h1>About Us</h1>
    <p>This is the about page content.</p>
</section>

<?php include '../includes/footer.php'; ?>

3. Konvensi Penamaan dan Komentar

Konvensi Penamaan
camelCase

Untuk JavaScript variables dan functions

let userName = "Ahmad";
let isLoggedIn = false;

function getUserData() {
    return userData;
}

function calculateTotalPrice() {
    // calculation logic
}
kebab-case

Untuk CSS classes dan file names

/* CSS */
.header-navigation { }
.user-profile-card { }
.btn-primary { }

/* Files */
user-profile.html
contact-form.php
main-style.css
snake_case

Untuk PHP variables dan database

<?php
$user_name = "Ahmad";
$is_active = true;

function get_user_data() {
    return $user_data;
}

// Database
user_profiles
order_items
Penulisan Komentar yang Efektif
/**
 * Menghitung total harga dengan pajak dan diskon
 * 
 * @param {number} basePrice - Harga dasar produk
 * @param {number} taxRate - Persentase pajak (0-1)
 * @param {number} discount - Persentase diskon (0-1)
 * @returns {number} Total harga setelah pajak dan diskon
 */
function calculateFinalPrice(basePrice, taxRate, discount) {
    // Validasi input parameter
    if (basePrice <= 0 || taxRate < 0 || discount < 0) {
        throw new Error('Invalid input parameters');
    }
    
    // Hitung harga setelah diskon
    const discountedPrice = basePrice * (1 - discount);
    
    // Tambahkan pajak
    const finalPrice = discountedPrice * (1 + taxRate);
    
    return Math.round(finalPrice * 100) / 100; // Bulatkan ke 2 desimal
}

/* 
 * TODO: Tambah validasi untuk mata uang
 * FIXME: Handling untuk nilai negatif
 * NOTE: Function ini digunakan di checkout.js dan cart.js
 */
Good Comments
  • Menjelaskan mengapa, bukan apa
  • Dokumentasi untuk function kompleks
  • Warning untuk kode yang tricky
  • TODO untuk fitur yang akan ditambah
  • Referensi ke dokumentasi eksternal
Bad Comments
  • Mengulangi apa yang sudah jelas dari kode
  • Komentar yang sudah usang/outdated
  • Komentar untuk menutupi kode buruk
  • Terlalu verbose untuk hal sederhana
  • Komentar yang tidak informatif

Praktik Unit 3: Refaktor Proyek Portfolio

Tugas Praktik:
  1. Buat struktur folder yang terorganisir
  2. Pisahkan HTML, CSS, dan JavaScript
  3. Implementasi header dan footer dengan include
  4. Tambahkan komentar pada setiap function
Struktur Proyek yang Direkomendasikan
portfolio-project/
index.php
includes/
config.php
functions.php
header.php
footer.php
pages/
about.php
portfolio.php
contact.php
css/
main.css
responsive.css
js/
main.js
portfolio.js
img/
profile.jpg
portfolio/
assets/
resume.pdf
Template: Modular Portfolio
<?php
// includes/functions.php

/**
 * Sanitasi input dari user untuk mencegah XSS
 * @param string $input - Input yang akan dibersihkan
 * @return string - Input yang sudah aman
 */
function sanitize_input($input) {
    return htmlspecialchars(trim($input), ENT_QUOTES, 'UTF-8');
}

/**
 * Generate navigation menu aktif
 * @param string $current_page - Halaman saat ini
 * @return void
 */
function generate_nav($current_page) {
    $nav_items = [
        'index.php' => 'Home',
        'pages/about.php' => 'About', 
        'pages/portfolio.php' => 'Portfolio',
        'pages/contact.php' => 'Contact'
    ];
    
    echo '<nav class="main-navigation">';
    foreach ($nav_items as $url => $label) {
        $active_class = ($current_page === $url) ? ' class="active"' : '';
        echo "<a href=\"$url\"$active_class>$label</a>";
    }
    echo '</nav>';
}

/**
 * Format tanggal ke bahasa Indonesia
 * @param string $date - Tanggal dalam format Y-m-d
 * @return string - Tanggal terformat
 */
function format_date_id($date) {
    $months = [
        '01' => 'Januari', '02' => 'Februari', '03' => 'Maret',
        '04' => 'April', '05' => 'Mei', '06' => 'Juni',
        '07' => 'Juli', '08' => 'Agustus', '09' => 'September',
        '10' => 'Oktober', '11' => 'November', '12' => 'Desember'
    ];
    
    $parts = explode('-', $date);
    return $parts[2] . ' ' . $months[$parts[1]] . ' ' . $parts[0];
}
?>