我在这里违反了得墨忒耳法吗?

时间:2012-04-29 02:12:31

标签: java jsp el

这违反了Law of Demeter权利?请参阅下面的${book.author.name}${book.category.name}。可以在带有表达式语言的JSP中执行此操作吗?

<c:set var="book" value="${book}" />

<table>
    <tr>
      <td>Title:</td><td><c:out value="${book.title}" /></td>
    </tr>   
    <tr>
        <td><c:out value="${book.description}" /></td>
    </tr>
    <tr>
        <td>Price: </td><td><c:out value="${book.price}" /></td>
    </tr>
    <tr>
        <td>Author: </td><td><c:out value="${book.author.name}" /></td>
    </tr>
    <tr>
        <td>Category: </td><td><c:out value="${book.category.name}" /></td>
    </tr>
</table>

</body>
</html>

${book}属性是Book个对象。 BookServlet

String id = request.getParameter("id");

BookService bookService = new BookService();
Book book = bookService.getBookById(Integer.valueOf(id));

request.setAttribute("book", book);
来自findBookById()

BookService -> BookDao

public Book findBookById(int id) throws DaoException {

Book book = null;
Connection con = null;
PreparedStatement ps = null;
ResultSet rs = null;

try {
    con = this.getConnection();

    ps = con.prepareStatement(FIND_BOOK_BY_ID);
    ps.setInt(1, id);

    //Using a PreparedStatement to execute SQL...
    rs = ps.executeQuery();
    while (rs.next()) {
        int bookId = rs.getInt("book_id");
        String title = rs.getString("title");
        String desc = rs.getString("description");
        int authorId = rs.getInt("author_id");
        String authorName = rs.getString("author_name");
        int categoryId = rs.getInt("category_id");
        String categoryName = rs.getString("book_category_name");
        double price = rs.getDouble("price");

        book = new Book(bookId);
        book.setTitle(title);
        book.setDescription(desc);
        book.setPrice(price);

        Author author = new Author(authorId);
        author.setName(authorName);
        book.setAuthor(author);

        Category category = new Category(categoryId);
        category.setName(categoryName);                
        book.setCategory(category);
}
} catch (SQLException e) {
    throw new DaoException("findBookById() " + e.getMessage());
} finally {
    try {
        if (rs != null) {
            rs.close();
        }
        if (ps != null) {
            ps.close();
        }
        if (con != null) {
            freeConnection(con);
        }
    } catch (SQLException e) {
        throw new DaoException(e.getMessage());
    }
}
return book;

}

2 个答案:

答案 0 :(得分:1)

严格来说,你违反了Law of Demeter:你正在调用Book方法返回的对象上的方法,暴露了Author和Category类的内部结构。

另一方面,我没有看到你的代码是有害的,而且你对Demeter Law的违法行为似乎很幼稚。我已经在书籍和生产代码中多次看到像你这样的JSP文件,并且没有任何伤害。

但是,如果你仍然想要遵守法则,你可以使用类似于Data Transfer Object的东西,它只有你需要显示的属性。需要额外的工作来填充DTO实例。书籍,作者和类别类别的信息。

答案 1 :(得分:1)

这是对jsp的完全有效使用。这样做需要做更多的工作而不是它的价值。严格遵守COBOL仍然受欢迎时编写的编码原则仅在学术界很有意思。