How (or you should) avoid long methods / classes in jsf

I mainly work with legacy code in a JSF-based project, and there are many fairly long classes and methods in beans support.

This constantly annoys me, but when I look at what can be done, most of the time I can find to divide the long method into n small methods. This gives you a very long class, and sometimes even harder to read.

So what do you do to keep your beans support short and concise? Or do you keep one big bean support per page? Are there any best practices?

I assume that this is not directly related to jsf, but to any model where you "support" your view using a controller. Therefore, general advice will also be helpful.

+5
source share
3 answers

Place all the fields in a class, also called the essence of the class or DTO (eg User, Product, Orderetc.) and refer to it. These can be JDBC / JPA objects. Put all the business methods in your class, also called service or domain object (eg UserService, ProductServiceetc.), and instead refers to it. It could be EJB.

eg. so not

public class Bean {

    private Long id;
    private String field1;
    private String field2;
    private String field3;
    // Etc... All model fields.

    @PostConstruct
    public void init() {
        // >20 lines of business/domain code to prefill the fields from DB.
    }

    public void save() {
        // >20 lines of business/domain code to save the fields in DB.
    }

    // Getters/setters for all fields and possibly also all nested fields.
}

But moreover

public class Bean {

    private Long id;
    private Entity entity;

    @EJB
    private EntityService service;

    @PostConstruct
    public void init() {
        entity = service.find(id);
    }

    public void save() {
        service.save(entity);
    }

    // Getter/setter for id and getter for entity.
}

In addition, I also saw code in which nested objects / entities are delegated via additional getters / setters in a bean, for example,

private Entity entity;

public String getField1() {
    return entity.getField1();
}

public void setField1(String field1) {
    entity.setField1(field1);
}

// Etc...

This is completely unnecessary. One getter is sufficient for an entity (a setter is optional!) In conjunction with

<h:inputText value="#{bean.entity.field1}" />

. . street, houseNumber, zipCode, city, country of User /DTO Address User.


, (, Netbeans + Woodstock). , , , .

+7

IMHO, 1 , 1 , , . IDE , .

+3

beans, :

.

+1

All Articles