Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bad practice in this spring tutorial?

I'm following the spring tutorial.

In section "3.2. Add some classes for business logic" an interface ProductManager is created:

package springapp.service;

import java.io.Serializable;
import java.util.List;

import springapp.domain.Product;

public interface ProductManager extends Serializable{

    public void increasePrice(int percentage);

    public List<Product> getProducts();

}

Then a SimpleProductManager implementation class is created:

package springapp.service;

import java.util.List;

import springapp.domain.Product;

public class SimpleProductManager implements ProductManager {

    public List<Product> getProducts() {
        throw new UnsupportedOperationException();
    }

    public void increasePrice(int percentage) {
        throw new UnsupportedOperationException();        
    }

    public void setProducts(List<Product> products) {
        throw new UnsupportedOperationException();        
    }

}

The implementation class adds an extra method setProducts(). Should the interface ProductManager not also have a setProducts method to allow classes which use setProducts to instantiate SimpleProductManager polymorphically. Currently this is not possible -

ProductManager p = new SimpleProductManager();
p.setProducts();
like image 796
blue-sky Avatar asked Jan 08 '12 19:01

blue-sky


People also ask

Can we use @bean without @configuration?

@Bean methods may also be declared within classes that are not annotated with @Configuration. For example, bean methods may be declared in a @Component class or even in a plain old class. In such cases, a @Bean method will get processed in a so-called 'lite' mode.

Why is spring boot so hard?

Which makes it incredibly hard when you just get started. You have to learn too many things at once and will eventually feel overwhelmed and frustrated. When you go Spring Boot first, much of the complex configuration part is taken care of for you.


1 Answers

The interface does not include setProducts because the clients of that interface (probably an MVC controller) are not supposed to call it. The interface defines only those operations that clients are supposed to use, rather than defining all of the methods that the implementation may have.

The setProducts method will be accessible to the beans configuration (e.g. using <property name="products">), which allows the products to be statically configured at start up. After that, client code refers to the bean via its restricted interface.

Your p.setProducts() example should never be called in this example, since the products are only configured in the beans config, not by business logic.

like image 140
skaffman Avatar answered Oct 03 '22 00:10

skaffman