HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaMinor

Jar console application serializing key-value pairs based on specific commands

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
applicationserializingcommandsjarvaluebasedspecificconsolepairskey

Problem

I was assigned a task to make a simple jar that can handle 2 console commands -> create key value, read key. I have 4 classes, where my main logic is implemented. Eg. create bulgaria sofia, creates a record in a serialized file with a key - bulgaria and value - sofia. Any feedback about the code and the idea are more than welcome.

```
public class MapUtility {

public static final String FILE_NAME = "hashmap";

// Finds a value based on its key
public static String findByKey(String key) throws ExceptionUtil,
IOException {
Map map = deserializeMap(OSUtility
.getFilePathForSerialization(FILE_NAME));

for (String k : map.keySet()) {
if (key.equals(k))
return map.get(k);
}

throw new ExceptionUtil(1);
}

public static Map serializeMap(String key, String value,
String fileName) throws IOException {

String pathToMap = OSUtility.getFilePathForSerialization(fileName);
Map map = deserializeMap(pathToMap);

if (map == null) {
map = new TreeMap();
}

map.put(key, value);

try (FileOutputStream fois = new FileOutputStream(pathToMap);
ObjectOutputStream oos = new ObjectOutputStream(fois)) {
oos.writeObject(map);
} catch (IOException ioe) {
ioe.printStackTrace();
}

return map;
}

// Deserialize a map object
public static Map deserializeMap(String pathToMap) {
Map map = null;

try (FileInputStream fis = new FileInputStream(pathT

Solution

User input and validation

Instead of having your own implementation to parse user input in a CLI, consider using a third-party library such as Apache Commons-CLI to simplify the approach.

Exception names

Exception names are usually in the form of ...Exception, hence your class ExceptionUtil has an atypical name. Also, Exceptions are usually created with a known message already, and I think your approach of using a static Map that is only referenced when getMessage() is called is a bit convoluted.

Map access

I am not sure why your MapUtility.findByKey() method is so verbose, when a simple statement will suffice:

return deserializeMap(OSUtility.getFilePathForSerialization(FILE_NAME)).get(key);

Code Snippets

return deserializeMap(OSUtility.getFilePathForSerialization(FILE_NAME)).get(key);

Context

StackExchange Code Review Q#94426, answer score: 2

Revisions (0)

No revisions yet.