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.setOutputFile(new File(context.getCacheDir(), "MediaUtil#micAvailTestFile").getAbsolutePath());
        boolean available = true;
        try {
        catch (IOException exception) {
            available = false;
        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<ResolveInfo> speechActivities = packageManager.queryIntentActivities(speechIntent, 0);
        if (speechActivities.size() != 0) return true;
        return false;

1 Answer 1

  • Returning boolean

    A pattern

        if (condition) return true;
        return false

    is 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 {
            } catch (IOException exception) {
                return null;
            return recorder;
  • 3
    \$\begingroup\$ Also, using isEmpty is more natural than checking if size is 0 \$\endgroup\$
    – janos
    Dec 2, 2015 at 22:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.