Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
724 views
in Technique[技术] by (71.8m points)

java - Encapsulation and Getters

I was reading this article on why getter and setters are evil. The article doesn't say not to use them ever, but, it's telling you to think in a way that limits the use of those methods, or to quote the article:

Don't ask for the information you need to do the work; ask the object that has the information to do the work for you.

what happens when you need to display data in a GUI, but don't have getter methods? The article covers this briefly, but not fully. It mentions passing a JComponent to the class, but if you're GUI changes, it could lead to a lot of work to fix.

Take for example, you have a Book class (making this example limited to keep it readable).

public final class Book {

    private String title;
    //Authors is class with the attributes authorFirstname, authorLastname
    private List<Author> listofAuthors;


    public Book(String title, List<Author> listofAuthors)
    {
        //initialization
    }

    //other methods that do work
}

If I have a GUI that has a JTextField to display the book title and a JTable to display the list of authors, how would I write my method to "do the work" for me and display the result? Is this one of those times where a getter is necessary?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Think of it this way: Getters (public functions) are a bridge for private attributes.

I'll write you a simple example to modify your TextField using OOP.

Book class:

public final class Book {
private String title;
//Authors is class with the attributes authorFirstname, authorLastname
private List<Author> listofAuthors;


public Book(String title, List<Author> listofAuthors)
{
    //initialization
}
public String getTitle() {
return this.title; }
}

GUI:

author1 = new Author("jhon");
author 2 = new Author("alsojhon");
list = new ArrayList();
list.add(author1);
list.add(author2)
b = new Book("stack",list);
JTextField field;
field.setText(b.getTitle());

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...