DRY - Don' t Repeat Yourself

As the name implies ,our code should not be repeated .

Bad code - DRY Principle not followed


public class Matrix {

    public static void main(String[] args) {

        int[][] matrix = {
            {1, 2, 3},
            {4, 5, 6},
            {7, 8, 9}
        };
        //Repeated code logic
        for (int i = 0; i < 3; i++) {
            for (int j = 0; j < 3; j++) {
                System.out.print(matrix[i][j] + " ");
            }
            System.out.println();
        }

        int[][] matrix2digit = {
            {11, 12, 13},
            {14, 15, 16},
            {17, 18, 19}
        };
         //Repeated code logic
        for (int i = 0; i < 3; i++) {
            for (int j = 0; j < 3; j++) {
                System.out.print(matrix2digit[i][j] + " ");
            }
            System.out.println();
        }
    }
}

Good Code- DRY Principle followed

public class Matrix {
    public static void main(String[] args) {
        int[][] matrix = {
            {1, 2, 3},
            {4, 5, 6},
            {7, 8, 9}
        };

        int[][] matrix2digit = {
            {11, 12, 13},
            {14, 15, 16},
            {17, 18, 19}
        };

        printMatrix(matrix);
        printMatrix(matrix2digit);
    }
    // No Repeated code - code is reused.
    private static void printMatrix(int[][] matrix) {
        for (int i = 0; i < matrix.length; i++) {
            for (int j = 0; j < matrix[i].length; j++) {
                System.out.print(matrix[i][j] + " ");
            }
            System.out.println();
        }
    }
}
0
Subscribe to my newsletter

Read articles from Palanivel SundaraRajan GugaGuruNathan directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Palanivel SundaraRajan GugaGuruNathan
Palanivel SundaraRajan GugaGuruNathan

Hi , thanks for stopping by! I am full-stack developer and I'm passionate about making complex concepts clear through code and visuals. After all, a picture (and a code snippet) is worth a thousand words! I hope you enjoy my blog.