有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

mongodb缩短java源代码

下面的代码打算在我的项目中创建一个搜索列。但我高度怀疑代码的效率,因为它相当长。是否有可能通过减少代码行数来执行与代码相关的任务

package kelas_java;
public class searchingDariSemuaKolom {

public static void main(String[] args) {
    BasicDBObject sortOrder = new BasicDBObject();
    MongoClient mongoClient;
    DB db;

    DBCollection table, table2;
    DBCursor cur = null, cur2 = null;
    try {
        mongoClient = new MongoClient("localhost", 27017);
        db = mongoClient.getDB("face");
        boolean auth = db.authenticate("aku", "kamu".toCharArray());
        Pattern regex = Pattern.compile("1");
//start1
table = db.getCollection("titles");
        DBObject clause1 = new BasicDBObject("link", regex);
        DBObject clause2 = new BasicDBObject("title", regex);
        DBObject clause3 = new BasicDBObject("body", regex);
        DBObject clause4 = new BasicDBObject("date", regex);
        BasicDBList or1 = new BasicDBList();
        or1.add(clause1);
        or1.add(clause2);
        or1.add(clause3);
        or1.add(clause4);
        DBObject query = new BasicDBObject("$or", or1);
        cur = table.find(query);
        while (cur.hasNext()) {
            System.out.println(cur.next().get("title"));
        }
//end1
//start2
table2 = db.getCollection("news");
        DBObject clause5 = new BasicDBObject("link", regex);
        DBObject clause6 = new BasicDBObject("title", regex);
        DBObject clause7 = new BasicDBObject("body", regex);
        DBObject clause8 = new BasicDBObject("date", regex);
        BasicDBList or2 = new BasicDBList();
        or2.add(clause1);
        or2.add(clause2);
        or2.add(clause3);
        or2.add(clause4);
        DBObject query2 = new BasicDBObject("$or", or2);
        cur2 = table2.find(query2);
        while (cur2.hasNext()) {
            System.out.println(cur2.next().get("title"));
        }
//end2
 } catch (Exception ex) {

    } finally {
        cur.close();
        cur2.close();
    }
}
}  

共 (2) 个答案

  1. # 1 楼答案

    编辑:拉赫马特比我抢先一步,但我想我还是发帖为好

    你的问题是冗长而不是效率

    只有在有不可预测的失败原因的情况下,才能尝试/抓住机会。然后只放可能会失败的那一行,而不是所有的代码。然后,在“catch”中,指定预期的错误,以及要对此执行的操作

    阅读文件,分析里面的信息,等等,都是为了抓住机会

    就我个人而言,我不喜欢创建额外的变量,因为它们不会被多次使用或有助于澄清。但这取决于你

    还有,你从来没用过巫师。而且类名应该大写,不过没什么大不了的

    package kelas_java;
    public class SearchingDariSemuaKolom {
    
        public static void main(String[] args) {
    
           // Not sure which of these need to be in here
           try {
               MongoClient mongoClient = new MongoClient("localhost", 27017);
               DB db = mongoClient.getDB("face");
               boolean auth = db.authenticate("aku", "kamu".toCharArray());
           } catch (Exception ex) {
               System.out.println("Error: " + ex.getMessage());
           }
    
            Pattern regex = Pattern.compile("1");
    
            String[] stuffToAdd = {"link", "title", "body", "date"};
    
            BasicDBList or1 = method2(db, "titles", stuffToAdd);
            BasicDBList or2 = method2(db, "news", stuffToAdd);
        }
    
        public BasicDbList method2(DB db, String str, String[] stuffToAdd) {
           BasicDBList or = createDbList(stuffToAdd);
           DBCollection table = db.getCollection(str);
           DBCursor cur = table.find(new BasicDBObject("$or", or));
           while (cur.hasNext())
               System.out.println(cur.next().get(str));
           cur.close();
           return or;
        }
    
        public BasicDbList createDbList(String[] toAdd) {
            BasicDbList or = new BasicDbList();
            for(String newString : toAdd)
                or.add(new BasicDbObject(newString, regex));
            return or;
        }
    
    }
    
  2. # 2 楼答案

    始终使用方法缩短代码。当您需要多次执行相同的工作时,只需调用您的方法并向其传递真参数

    下面是对代码的一些更改,我删除了从数据库打印一些数据的重复代码,并创建了一个名为doPrint的方法,该方法包含四个参数

    • 字符串数组命名键,它的值将被分配给BasicDBObject
    • 将分配给BasicDBObject的值
    • 您与之连接的数据库
    • 以及要从中读取数据的集合(表)名称

    然后,您只需调用doPrint

    doPrint(keys , regex , db , "titles");
    

    希望能有帮助

    package kelas_java;
    public class searchingDariSemuaKolom {
    
        static void doPrint(String keys, Object value, DB db, String collectionName) {
            BasicDBList or = new BasicDBList();
            for (String key : keys) {
                or.add(new BasicDBObject(key, value));
            }
            DBObject query = new BasicDBObject("$or", or);
            DBCollection table = db.getCollection(collectionName);
    
            try {
                DBCursor cur = table.find(query);
                while (cur.hasNext()) {
                    System.out.println(cur.next().get("title"));
                }
            } catch (MongoException e) {
                System.out.println("Error: "+e.getMessage());
            } finally {
                cur.close();
            }
        }
        public static void main(String[] args) {
            BasicDBObject sortOrder = new BasicDBObject();
            MongoClient mongoClient;
            DB db;
    
            String strs[] = {
                "link", 
                "title",
                "body", 
                "date", 
            };
            try {
                mongoClient = new MongoClient("localhost", 27017);
                db = mongoClient.getDB("face");
                boolean auth = db.authenticate("aku", "kamu".toCharArray());
                Pattern regex = Pattern.compile("1");
    
                //start1
                doPrint(keys , regex , db , "titles");
                //start2
                doPrint(keys , regex , db , "news");
            } catch (Exception e) {
                System.out.println("Error: "+e.getMessage());
            }
        }
    }