Merge two very similar methods
I have this theoretical situation:
a form with
2 inputs [attributes
attr1
,attr2
of objectitem
] **<h:inputText id="attr1" value="#{bean.item.attr1}"/> <h:inputText id="attr2" value="#{bean.item.attr2}"/>
2 submit buttons [searching by
attr1
,attr2
in dtb] in foo.xhtml:<h:commandButton id="search1" action="#{bean.search1}" /> <h:commandButton id="search2" action="#{bean.search2}" />
and two very similar methods in bean.java:
public void search1(){
try
{
session = DaoSF.getSessionFactory().openSession();
Criteria criteria = session.createCriteria(Foo.class);
criteria.add(Restrictions.like("attr1", item.getAttr1()));
dataList = criteria.list();
}
catch (Exception e) {...}
}
public void search2(){
try
{
session = DaoSF.getSessionFactory().openSession();
Criteria criteria = session.createCriteria(Foo.class);
criteria.add(Restrictions.like("attr2", item.getAttr2()));
dataList = criteria.list();
}
catch (Exception e) {...}
}
Is there some way to merge these two methods开发者_开发问答 to one?
UPDATE: and also merge action of commandButtons?
SOLUTION:
private void search(String field, String value)
action="#{bean.search('attr2', bean.item.attr1)}"
Just pass what's different as a parameter:
public void search(String param, Attr attr){
try
{
session = DaoSF.getSessionFactory().openSession();
Criteria criteria = session.createCriteria(Foo.class);
criteria.add(Restrictions.like(param, attr));
dataList = criteria.list();
}
catch (Exception e) {...}
}
Sure: look for what's the same, and what's different. You don't provide enough info to know whether or not this is possible:
public void search(String sAttr, T attr) {
try {
session = DaoSF.getSessionFactory().openSession();
Criteria criteria = session.createCriteria(Foo.class);
criteria.add(Restrictions.like(sAttr, attr));
dataList = criteria.list();
} catch (Exception e) {...}
}
If the attribute types aren't the same, it's a bit more irritating, and the joy that is Java rears its ugly head.
At some point you'll end up with a method that takes a Criteria
and you either create those on-the-fly and pass them in to something that wraps up the try/catch and list, or you end up creating an interface and passing an implementation in to the same.
On a side note, IMO creating side-effect dependencies like setting dataList
inside a search method will eventually lead to tears: consider returning the list from the method instead, even if you just set it to a property to get passed along to whatever uses it.
You could create a third method and call it from within those methods:
private void doSearch(String field, String value) {
session = DaoSF.getSessionFactory().openSession();
Criteria criteria = session.createCriteria(Foo.class);
criteria.add(Restrictions.like(field, value));
dataList = criteria.list();
}
public void search1() {
doSearch("attr1", item.getAttr1());
}
public void search2() {
doSearch("attr2", item.getAttr2());
}
精彩评论