dimanche 5 mars 2017

Using non direct reference of implementor classes, what's the benefit?

I'm struggling to express my question through the title, I'm lack of jargons. I'm constructing the following codes by myself, not necessarily good. I'm just trying to deliver my point. I see this kind of design many times in the enterprise Java level.

I have a repository class:

import java.util.*;
public interface ProductRepository {
    public List <Product> getAllProducts();
}

A the implementor class

public class ProductRepositoryImp implements ProductRepository {
    private List<Product> products = new ArrayList<Product>();
    public ProductRepositoryImp() {
        products.add(new Product("Blackberry", 24000));
        products.add(new Product("Nokia", 45000));
        products.add(new Product("Samsung", 91000));
    }
    @Override
    public List<Product> getAllProducts() {
        return this.products;
    }
    public int localMethod(){
    return 2;
    }

}

A main/controller class

public class ProductController {
    static ProductRepository productRepository;
    public static void main(String[] args) {
        ProductRepository = new ProductRepositoryImp();

        for (Product p : productRepository.getAllProducts()) {
            System.out.println(p.getNama());
            System.out.println(p.getHarga());
            System.out.println("");
        } } }

My questions : - In the ProductController, I don't use "ProductRepositoryImp" instance but Instead "ProductRepository" (an interface),

The point is (I took from a book, somehow related) : It is not the best practice to connect two layers (controller and persistence) with a direct reference. Instead, we can, in future, have an interface reference in the controller so that we can easily switch to different implementations of the repository without doing any code changes in the controller class.

  • What's the benefit of accessing .getAllProducts() from the ProductRepository instance instead of an instance of ProductRepositoryImp?

  • what's the point of "without doing any code changes" switching in the quote above? I know it's something related if we have lets say "AnotherProductRepositoryImp"?.

  • What if I want to heavly access some .localMethod() instead which is inside the ProductRepositoryImp instance ?

Aucun commentaire:

Enregistrer un commentaire