I'm running into more and more naming clashes between Android activities and other classes. I was wondering if you could tell me how you avoid these. Sadly, my particular naming problems are not covered in the related questions on SO.
First example
I have an activity that displays a level of the game. However, the data required for that level (background artwork, entities etc.) is stored in a separate class. Naturally, I would call the latter class Level. However, I would call the activity Level as well, because it displays levels.
Second example
I have an activity that plays back a cut scene. It basically displays several images in a row. The information which image is shown for how long is stored in a separate class. As in the previous case, I would naturally call both classes CutScene.
How would you solve these naming issues? Name the activities LevelActivity and CutSceneActivity? Name the representation classes LevelModel and CutSceneModel? Something else?
I solve those problems by either prefixing or postfixing classes with their "type", like you suggested at the end of your question :
LevelActivity, GameActivity, MainActivity, ...
CommentsListAdapter, ...
CheckNewCommentsService, ...
and so on.
But I generally do an execption for the model classes, which are the objects that contain that data : I would still name my Level model class Level, and not LevelModel, to indicate I'm manipulating, and working with, a Level.
Another solution (longer to type ^^) might be to use fully-qualified names (see here) when referencing your classes :
com.something.yourapp.activity.Level
com.something.yourapp.model.Level
With this, you always know which class is really used.
In general the best way to name android application components is to add its "component type" as suffix.
Example :-
LevelActivity (LevelActivity extends Activity)
InboxUpdateService (InboxUpdateService extends Service)
ContactsContentProvider (ContactsContentProvide extends ContentProvider)
SMSBroadcastReceiver (SMSBroadcastReceiver extends BroadcastReceiver)
By naming using above method there will be minimal chances of losing track when you're working on big code flow with lots of similar names in your application.
So, name your Activities with suffix "Activity".
And name the Class which provides Data to your LevelActivity as Level.
In Contradiction to second part of Pascal MARTIN's answer, you can also use LevelActivity and LevelInfo together. Because they offer clear difference as quoted below:
Distinguish names in such a way that the reader knows what the
differences offer
- Robert. C. Martin, author of Clean Code
But the suffix are often redundant on cognitive basis. Using only the word Level clearly emphasises that class Level offers information about Level.
So, use Level for class that provides data about Level.
NOTE : If you're using suffixes, choose one word per concept.
For Example: If you're using the suffix Info to identify classes that offer information then only Info should be used (not Data or Model) throughout your application to avoid confusions.
Related
In this Q&A, it says there's no difference. And some people says annotation is better or using constructor(mockk<*>()) is better.
For me, if they are equivalent, less line of code(not using annotation) is better.
Many sample code shows #MockK is used for the values that pass to Class such as ViewModel/Activity or Fragment. On the other hand, mockk<*>() is used for the classes that have its behaviour or data class, etc
There must be some differences since one is annotation and the other is using constructor. And there must be some reasons why each of them are created, not only one of them.
If you know this, could you please answer it?
Ive been searching the internet for a while now but cant find a good page for good habit examples in android programming. For examples im interested in things like how to name classes or xml files (what case letters, where to use _) and also in file things like naming variables and fields or edittexts, prefixes and everything like that.
If someone could help me with a link i would be very grateful!1
Android developers has its answer for this.
If you need anything elaborated I'll update my answer from your comments :-)
For Classes use Java naming convention:
First letter capitalized, no "_" in the class names but start with capitalized letter for each new word ei:
MyActivity or MySettingsActivity
For xml object naming you have some other limitations as in, first letter cannot be capitalized, therefor I suggest your either use the general java naming convention for methods (First letter decapitalized, and then new words capitalized like: buttonQuit or quitButton), if it should be button first or last is up to you, but stick with 1 style. don't name 1 item: nameTextView (or nameTxtVw) and then something else buttonSubmit (Have the indicators in the same orders).
For xml files, use lower case separated with underscore "_".
Why a lot java files are called Activity in the end. It is to describe in the name that they inherit from from the superclass "Activity". It is a principle that came became big with Android, which uses it a lot, examples if these classes are inherited:
(super class = end of their heirs name)
AsyncTask = Task
Service = Service
Activity = Activity
Handler = Handler
I could go on :)
For xml files, belonging to activities I personally like to call them the name before Activity, so MainActivity's xml layout would be main.xml
If you are looking for some coding guidelines, have a look at Code Style Guidelines for Contributors
If you want to enforce this rules without remembering all of them, and you are using eclipse then you can use formatting rules provided by Android team: android-formatting.xml. Just import it into eclipse using Preferences->Java->Code Style->Formatter, click Import.
You should learn Java code conventions, and so read this:
java style
It's good to practice always name classes upper camel style (e.g CustomerService)
Class names should be noun,
For naming variables you should use lower Camel Style (e.g myVariable)
Xml file shoudl be lower case and words should be separated by under score
please read the above links!
[Edited] this part added after the first comment!
I don't know any good reference for good naming convention and things like this but those are things that you can find out be practicing! for example:
"activity" prefix may be not useful in case if all your layouts are for activities. but if there is bunch of other style (e.g dialog layouts) it could help to put "activity" prefix.
another example: I prefer to put "Activity" prefix for all classes that extends Activity, because eclipse shows classes base on name, and this could help to somehow a better management (but it's against Java naming convention! because you should suffix your class name with super class name)
For naming Id: You could prefix the resource with the name of what it is (e.g titleStatus), it doesn't really matters! but you for better managing your Ids and not losing in lots of name, always follow the same rule, if your name some element in your status like "statusTitle" the other element should be "statusDescription" but not "descriptionStatus"!
I have been creating Spinner controls (Combo boxes/Drop downs) in one of my apps, and was surprised to find out how difficult it was to achieve all of the following features:
User facing Strings are externalized, taking advantage of strings.xml internationalisation (I18N) feature of Android.
Spinner selections operate using a System view, which facilitates not having to work with or map Strings to meaningful values (yuck).
User view to System view mapping should be easy, automated and minimal (i.e not hand rolled for every component).
Others have attempted solutions to this, but universally as far as I could see they suffer from one or many of the following problems:
UI code is creeping into their enum class which doesn’t belong there (messy), nearly all existing solutions suffered from this.
Hardcoded User facing Strings in their enum classes. Because these are not externalized you cannot do I18N using the stock Android features.
Authors typically make the Fragment or Activity an OnItemSelectedListener which perpetuates a common problem of inheritance for convenience, where composition is more appropriate.
I have developed my own solution which does this: http://www.androidanalyse.com/android-spinner-externalize-user-strings-mapped-to-system-enum/
My question is, have I missed something? This seems like something that should not have been this hard (which makes me feel like I'm possibly reinventing the wheel).
Below is some example code showing my solution in-use (which is available Apache 2 license from the link above).
String none = getString(R.string.none);
String light = getString(R.string.light);
String medium = getString(R.string.medium);
String strong = getString(R.string.strong);
SpinnerUtil.createNewSpinner(view, R.id.wind, Arrays.asList(none, light, medium, strong), WindLevel.values(),
new SpinnerItemSelectedListener<WindLevel>() {
public void onItemSelected(Spinner item, WindLevel value) {
// Take whatever action you wish to here.
}});
I would just use ArrayAdapter<WindLevel>. Yes, you created a custom typed listener, but the regular event listener gets the position and can call getItem() on the ArrayAdapter<WindLevel> to get a WindLevel properly typed.
IMHO, the vast majority of Spinner widgets will be populated with material read in from a database, the Internet, or some other dynamic data source, rather than populated by some sort of enum with display values coming from static strings that can be internationalized ahead of time.
This is not to say that your code is useless: if you find it useful, then it was worth writing. And I am sure that there are apps out there that contain your targeted pattern (i.e., a Spinner backed by an enum or equivalent where the display values are known in advance and can be internationalized) who might find your solution useful as well. Every developer who writes enough code cooks up these sorts of helper classes and the like that help map an OS or framework model into something that better fits the developer's own mental model. So long as you are not perceiving any performance issues, it's all good.
Also, note that OnItemSelectedListener is an interface; implementing that interface on an existing class is not inheritance.
I believe the reason nobody answered you is :
What problem are you trying to solve ? Spinners existed prior to your well designed attempt.
Why reinvent them in exactly the same way they exist in Android ?
http://developer.android.com/guide/topics/ui/controls/spinner.html
It is a beautiful wheel indeed you designed, but still, it is just a wheel :)
UPDATE :
I think I begin to understand what you did. This is interesting. I'm not sure why you did not go to the pattern implemented by the ListPreference with its entries and entryvalues.
In fact, I'm not sure I understand why the Android team did not go that route either.
In any case, it is worth proposing your idea to the Android framework. It is after all open source.
I have a common library where I've put classes that are used between multiple Android projects. However, now I encountered a situation where I have to make minor changes to the functionality of the class in one project. How should I organize the classes, keeping in mind easy readability of code and future extension possibilities?
Should I
Extend the class (MyClass) with modifications that are special to the subproject (MyClassSub extends MyClass)? What about if I have references to MyClass in the library classes, but in this special subproject MyClassSub should be called?
Have switch OR if clauses for each special part in the class file? And then pass some variable to the class?
Some other option?
This is probably a trivial question, but I am quite new to java and can't quite figure it out.
Definately 1.
Create a library (jar) containing the base class, and then use that jar in the projects that need its base functionality. Each project should provide the specialized class that extends the base.
If the new functionality is specific to the one project, I would avoid putting the functionality in the library. Go with a subclass or a replacement class. If later you find that this extended behavior is more widely usable, you can migrate it to the library (perhaps creating an entire new version of the library, much in the same way that the Java API evolves.)
Unfortunately the answer is "it depends."
Specifically, a class hierarchy should be designed such that the behavior of the base class holds for all subclasses of the class. One way to look at this is to say that the subclass may expand the behavior of the base class. The corollary is that a subclass should not restrict the behavior of the base class. So a Square IS NOT A Rectangle.
Also consider "favor composition over inheritance" unless the base class is specifically designed for inheritance, as a change to the base class might BREAK the subclass.
Have fun!
What are some layout file naming conventions people have come up with.
I haven't found anything online, but thought about using the following convention.
What does everyone think?
- activity_*
- dialog_*
- list_item_*
That's all I have worked with so far.
Also, what about the naming of the activity against its layout? For example:
-> res
-> layout
-> activity_about_us.xml
-> src
-> activity
-> AboutUs.java
Strangely enough, trying to google this question brings only this page as meaningful result...
For the past half year I am using naming convention similar to yours but with shorter prefixes. For example:
For activity that shows "About us" screen:
Class name: ActAboutUs. Prefixing class is kind of overkill but it clearly distinguishes activity classes from the others. Initially I used separate directory for all the activities (similar to your approach) but after some time I realized that for bigger apps may be it is better to group in directories by feature than by superclass (i.e. Activity). It is easier for me to work in single directory for example /src/settings/ when I work on Settings. That way all java files that I need are in a single dir so i don't have to wander around:
/src/settings/ActSettingsGlobal.java
/src/settings/ActSettingsNet.java
/src/settings/Settings.java
/src/settings/SettingsDBAdapter.java
/src/settings/etc...
This approach also helps to split the work among different developers, i.e. each one is working in his own dir on separate feature so no stepping on each other's feet :-).
Some people preffer suffixes but I found them less useful. Prefixes help to group things alphabetically like in the example above: Act* prefix is sorted first so all activities are conveniently at the top.
I am even considering of using Act_ as a prefix which is more readable although it is in conflict with java naming conventions...
Layout filename: act_about_us.xml. In res/layout/ we don't have the "luxury" of subdirs which is quite unfortunate so the only way to group things is using appropriate prefix like act_, dlg_, etc...
String IDs: <string name="act_about_us_dlg_help1_title" ...
string.xml is the place where we have most problems with duplicate names. It is very easy to create duplicates if naming convention like activity_element_item is not used. It adds a lot of additional typing but it saves you from a lot of confusion later on.
For global (application wide) strings we use prefix "global_", for example global_btn_ok, global_msg_no_inet_conn. Usually we make one person responsible for all global_ strings so if someone needs new string or change he needs to sync with him in order to avoid creating a mess.
(now I am realizing that activity__element__item (two underscores) is more clear and readable than activity_element_item)
All in all I still can't get rid of the feeling that there is something wrong with my approach because I can't believe that google devs created such an inconvenient framework when it comes to working with files, IDs, names, etc...
i think following naming convention should be follow
for activity
if our activity name is
DisplayListActivity
then our layoutname should be
display_list_activity.xml
for list items we can include category in list item layout name
country_list_item.xml
and for dialogboxes their action can be included
delete_country_dialog.xml
When looking for a group of layouts, which is how I tend to work on them, I find it effective to always prepend the class name and follow up with any sub-layouts. For Instance:
Class Name: AboutActivity.java
Layout Name: about_activity.xml
Sub-layout Name: about_activity_menu.xml
Sub Sub-layout Name: about_activity_menu_item.xml
Your activity will always be at the top of each grouping and hunting for non-activities becomes less of a chore. Anyone know why sub-folders aren't a thing yet? I expect for efficiency and simplicity on the back-end, but I imagine it wouldn't hurt too much.
This is a good read https://jeroenmols.com/blog/2016/03/07/resourcenaming/
Basically, you follow WHAT WHERE DESCRIPTION SIZE
For example, layout file
activity_main: content view of the MainActivity
fragment_articledetail: view for the ArticleDetailFragment
strings
articledetail_title: title of ArticleDetailFragment
feedback_explanation: feedback explanation in FeedbackFragment
drawable
- all_infoicon_large: large version of generic info icon
- all_infoicon_24dp: 24dp version of generic info icon
The first part of a layout file name should always be the type of the corresponding class.
For example if we have a class MainActivity (type is Activity in this case), the corresponding layout file should be called activity_main.xml
That means that lets say we have a dialog called WarningDialog, the corresponding layout file should be called dialog_warning.xml, same goes for fragments etc.
This might seem familiar because thats also how the activity/layout files are named when creating a new project in Android Studio (MainActivity -> activity_main.xml).
For me, naming should fix two important requirements:
it should give you a hint about files' content and type (for example activity_login/login_activity or movie_list_item/list_item_movie)
it should visually group related items together to minimize jumping back and forth
For the second requirement, most people define "related" as type related which gives you something like this:
activity_login
activity_movie_list
activity_user_list
activity_settings
fragment_movie_list
fragment_user_list
item_movie
item_user
etc.
I prefer to do grouping by feature since you'll almost never work on all activities or all fragments, but instead, you'll work on movies feature or setting feature.
so, my prefered way is this:
login_activity
movie_list_activity
movie_list_fragment
movie_list_item
user_list_activity
user_list_fragment
user_list_item
settings_activity
Source files are following xml naming but in CamelCase, so there will be
LoginActivity
MovieListActivity
MovieFragment
etc.