patternjavaMinor
Speech reorganization helper class
Viewed 0 times
helperclassspeechreorganization
Problem
I am working on a speech reorganization project. I have a util class that consists of three methods: check if a microphone exists, check microphone availability, and check text-to-speech availability. Can anyone review my code?
public class MediaUtil {
//returns whether a microphone exists
public boolean getMicrophoneExists(Context context) {
PackageManager packageManager = context.getPackageManager();
return packageManager.hasSystemFeature(PackageManager.FEATURE_MICROPHONE);
}
//returns whether the microphone is available
public static boolean getMicrophoneAvailable(Context context) {
MediaRecorder recorder = new MediaRecorder();
recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
recorder.setOutputFormat(MediaRecorder.OutputFormat.DEFAULT);
recorder.setAudioEncoder(MediaRecorder.AudioEncoder.DEFAULT);
recorder.setOutputFile(new File(context.getCacheDir(), "MediaUtil#micAvailTestFile").getAbsolutePath());
boolean available = true;
try {
recorder.prepare();
}
catch (IOException exception) {
available = false;
}
recorder.release();
return available;
}
//returns whether text to speech is available
public static boolean getTTSAvailable(Context context) {
PackageManager packageManager = context.getPackageManager();
Intent speechIntent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
List speechActivities = packageManager.queryIntentActivities(speechIntent, 0);
if (speechActivities.size() != 0) return true;
return false;
}Solution
-
Returning boolean
A pattern
is to be avoided.
achieves the same in a much more transparent manner. In your case,
-
Testing vs acquisition
Consider the situation: by the time you call
It means there is no point to test for availability. Acquire it as you need it:
Returning boolean
A pattern
if (condition) return true;
return falseis to be avoided.
return condition;achieves the same in a much more transparent manner. In your case,
return speechActivities.size() != 0;-
Testing vs acquisition
Consider the situation: by the time you call
getMicrophoneAvailable it might be available, but later on when your app actually needs it, it's been successfully claimed by some other app.It means there is no point to test for availability. Acquire it as you need it:
public static MediaRecorder getMicrophone(Context context) {
....
try {
recorder.prepare();
} catch (IOException exception) {
return null;
}
return recorder;
}Code Snippets
if (condition) return true;
return falsereturn condition;return speechActivities.size() != 0;public static MediaRecorder getMicrophone(Context context) {
....
try {
recorder.prepare();
} catch (IOException exception) {
return null;
}
return recorder;
}Context
StackExchange Code Review Q#112668, answer score: 5
Revisions (0)
No revisions yet.