I’m trying to get the most knowledge by my own, with reading lots of examples, documentations and asking here. I would like to improve my style, to avoid smelly code and write efficient.
I have here a small part of code and I would like to know if its okay in view of the throw exception, open and close database connection or if its crap and I could improve a lot.
I have 2 classes Database and Main.
The Database class looks like:
public class Database {
private String dbName = "";
private SqlJetDb db = null;
public Database(String dbName) {
this.dbName = dbName;
}
public void CreateDatabase() throws SqlJetException {...}
public void OpenDatabaseConnection() throws SqlJetException {...}
public void CloseDatabaseConnection() throws SqlJetException {...}
private void InsertRecord(String file) throws SqlJetException {...}
public void GetDirectoryContent(String dir) {
File directory = new File(dir);
if (directory.isDirectory()) {
String[] content = directory.list();
for (String s : content) {
GetDirectoryContent(dir + "\\" + s);
}
} else {
String file = directory.toString();
String extension = file.substring(file.lastIndexOf("."));
if (extension.equals(".h")) {
try {
InsertRecord(file);
} catch (SqlJetException e) {
e.printStackTrace();
}
}
}
}
}
In my Main class I call
Database db = new Database("test.db");
try {
db.CreateDatabase();
db.OpenDatabaseConnection();
db.GetDirectoryContent("C:\\test");
} catch (SqlJetException e) {
e.printStackTrace();
} finally {
try {
db.CloseDatabaseConnection();
} catch (SqlJetException e) {
e.printStackTrace();
}
}
}
I’m really interesting in writing clean and efficient code it would be great if someone has further information for me, how I could improve this.
Edit
Swap GetDirectoryContent
Database db = new Database("test.db");
Fileaccess fa = new Fileaccess();
ArrayList<String> al = new ArrayList<String>();
try {
db.createDatabase();
db.openDatabaseConnection();
fa.findDirectoryContent("C:\\test");
al = fa.getDirectoryContent();
for (String s : al) {
db.insertRecord(s);
}
} catch (SqlJetException e) {
e.printStackTrace();
} finally {
try {
db.closeDatabaseConnection();
} catch (SqlJetException e2) {
e2.printStackTrace();
}
}