Last active
April 13, 2016 13:56
-
-
Save tomredman/41e4dd6a173d1421d86f7c288a79a362 to your computer and use it in GitHub Desktop.
Code Principle Example: "Explicit is better than Implicit"
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* You've probably heard it before, "explicit is better than implicit". Here's a simple | |
* example of that principle in action. | |
* | |
* In this example, our app has only two Fragments that can be visible at any given | |
* moment: CreateFragment and TrendingFragment. Both examples achieve the same result | |
* when everything is working as expected, however... | |
* | |
* In the explicit example, a final else{} branch would indiciate something's not | |
* quite right with our code somewhere since we know there are only two possible | |
* options: (1) createFragment is visible or (2) trendingFragment is visible. | |
* | |
* If there was a bug in our code that caused neither fragment to be visible, the | |
* explicit example could help us catch that bug earlier. | |
* | |
* Happy coding! | |
*/ | |
/** | |
* IMPLICIT | |
*/ | |
@Override | |
public boolean onPrepareOptionsMenu(Menu menu) { | |
MenuItem shareItem = menu.findItem(R.id.action_share); | |
MenuItem refreshItem = menu.findItem(R.id.action_refresh); | |
if (createFragment.isVisible()) { | |
shareItem.setVisible(true); | |
refreshItem.setVisible(false); | |
} | |
else | |
shareItem.setVisible(false); | |
refreshItem.setVisible(true); | |
} | |
return super.onPrepareOptionsMenu(menu); | |
} | |
/** | |
* EXPLICIT | |
*/ | |
@Override | |
public boolean onPrepareOptionsMenu(Menu menu) { | |
MenuItem shareItem = menu.findItem(R.id.action_share); | |
MenuItem refreshItem = menu.findItem(R.id.action_refresh); | |
if (createFragment.isVisible()) { | |
shareItem.setVisible(true); | |
refreshItem.setVisible(false); | |
} | |
else if (trendingFragment.isVisible()){ | |
shareItem.setVisible(false); | |
refreshItem.setVisible(true); | |
} | |
return super.onPrepareOptionsMenu(menu); | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment