Java方法设计模式

标签 java

我正在开发一个程序,可以从网络上抓取某些数据并将其反馈给数据库。问题是我不想在爬虫第二次运行时重复输入相同的数据。如果某些属性发生变化,但大部分数据仍然相同,我想更新数据库条目而不是简单地添加一个新条目。我知道如何在代码中执行此操作,但我想知道是否可以做得更好。

现在更新的工作方式:

//This method calls several other methods to check if the event in question already exists. If it does, it updates it using the id it returns. 
//If it doesn't exist, -1 is returned as an id.
public static void check_event(Event event)
{
    int id = -1;

    id = check_exact_event(event); //Check if an event exists with the same title, location and time.
    if(id > 0)
    {
        update_event(event, id);
        Logger.log("EventID #" + id + " found using exact comparison");
        return;
    }

    id = check_similar_event_titles(event); //Check if event exists with a different (but similar) title
    if(id > 0)
    {
        update_event(event, id);
        Logger.log("EventID #" + id + " found using similar title comparison");
        return;
    }

    id = check_exact_image(event); //Check if event exists with the exact same image
    if(id > 0)
    {
        update_event(event, id);
        Logger.log("EventID #" + id + " found using image comparison");
        return;
    }

    //Otherwise insert new event
    create_new_event(event);
}

这行得通,但不是很顺眼。解决此问题的最佳方法是什么?

最佳答案

就我个人而言,我看不出您的代码有任何问题,它干净有效。 如果你真的想改变它,你可以在一个 if 语句中完成

public static void check_event(Event event) {
        int id = -1;

        if ((id = check_exact_event(event)) > 0
                || (id = check_similar_event_titles(event)) > 0
                || (id = check_exact_image(event)) > 0) {
            update_event(event, id);
        }
        ;
        create_new_event(event);
    }

但我看不到这样的收获

关于Java方法设计模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37272004/

相关文章:

java - mongoTemplate.findAll() 抛出异常

java - 字符串合并排序出现空指针异常?

java - 使用 Java 的应用程序引擎 : Deferred tasks ignoring retry limit

java - JToolBar 等价于frame.setJMenuBar(ie.createMenuBar()); 的是什么?

java - CDI+OSGI : bundle packages scope

java - 访问请求体中的 json

java - GAE - Javamail API 获取空内容邮件

java - pdf 表单字段在 android 上用 itext 填充后为空

java - 如何在 JPA XML 映射文件中使用 AttributeConverter(JPA 2.1)?

Java:仅使用一个循环打印数组的第一、第四、第七……?