I am trying to write an Android app using Xtend, however, I am more or less new in both. I have created a couple of Android examples with Java, but I'm still learning.
In these apps i used the android.app.Instrumentation.ActivityMonitor
in order to check that an Activity had started.
I have read that Xtend does not support Nested classes
No var args, no nested classes, no anonymous classes?
Those language features are not mentioned in the docs, and I could not guess a valid syntax. >I assume they are not available, but I could be wrong.
http://blogs.atlassian.com/2011/11/xtend-first-impressions/
Does this mean the ActivityMonitor cannot be accessed when using Xtend or am I just doing something wrong?
It depends how you used the ActivityMonitor. You cannot define inner classes on your own right now, but static inner classes can be accessed from within Xtend. There are issues with non-static inner classes. The syntax is different to Java, though. Instead of the '.' dot as the delimiter of declaring class and inner class, Xtend uses the '$'. A respective import declaration can ease the pain, here, e.g. import android.app.Instrumentation$ActivityMonitor.
Related
My app includes many helper classes like the next ones:
A class TMHttp with an "DownloadFile" or "IsOnline" methods (among others).
A TMEmail class with a "SendEmail" method.
A ImageHelper class with a "TakeScreenshot" or "CropBitmap" methods.
TMImport/TMExport classes with "ImportData" and "ExportData" methods.
A TMSession class with "LoginUser", "LogoutUser" and more such methods.
A TMUtils class with methods like "GenerateRandom".
A TMDialog class with methods like "CreateYesNoDialog" ... and many more.
And what I'd need to know -regarding DI- is if I have to inject them where needed -like I do with repository and services- or just create an instance of them. Do I have to inject every class in my app?
I believe there is no strict answer to this question because it depends on the architecture of your project, the principles the team is using, the purpose and the complexity of the helper/util class, etc.
You need to decide it for each such helper/util class particularly, guided by the following advantages of Dependency injection:
Reusability of classes and decoupling of dependencies: It's easier to swap out implementations of a dependency. Code reuse is improved because of inversion of control, and classes no longer control how their dependencies are created, but instead work with any configuration.
Ease of refactoring: The dependencies become a verifiable part of the API surface, so they can be checked at the object-creation time or at compile time rather than being hidden as implementation details.
Ease of testing: A class doesn't manage its dependencies, so when you're testing it, you can pass in different implementations to test all of your different cases.
For example, I would argue like this:
A TMUtils class with methods like "GenerateRandom"
Likely, it's a quite simple helper method that basically can have a standard single implementation; it doesn't depend on other libraries, so I can freely use it without DI.
A class TMHttp with an "DownloadFile" or "IsOnline" methods (among others).
It's heavy and it depends on a lib and Android SDK then it makes sense to inject.
And so on.
In Java, we have the package protected (default) modifier for classes, which allows us to have many classes in a single package but exposes only a few and keeps the logic encapsulated.
With Kotlin this doesn't seem to be the case. If I want a few classes to be visible to each other but no further, I have to use a private modifier which limits visibility to a single file.
So if you want 10 classes in a package but only one of them to be public, you'd have to have one huge file with all the classes in it (and private all over the place).
Is this normal practice or there is a way to achieve some similar modularity in Kotlin?
I don't understand: if they have the notion of a package, why did they get rid of package protected access?
Update: We might have package protected visibility after all
see the discussion here
Update: If you read through the discussion and still think this is a must-have feature for the language, please vote here
Kotlin, compared to Java, seems to rely on packages model to a lesser degree (e.g. directories structure is not bound to packages). Instead, Kotlin offers internal visibility, which is designed for modular project architecture. Using it, you can encapsulate a part of your code inside a separate module.
So, on top level declarations you can use
private to restrict visibility to the file
internal to restrict visibility to the module
At this point, there is no other option for visibility restriction.
As a workaround for me on android I've created #PackagePrivate annotation and lint checks to control access. Here you can find the project.
Lint checks are obviously not that strict as compiler checks and some setup needed to fail the build on errors. But android studio picks up lint checks automatically and shows error immediately while typing. Unfortunately I don't know a way to exclude annotated members from autocomplete.
Also, as lint is a purely compile-time tool, no checks at runtime performed.
As #hotkeys points out, you can use the internal keyword in a module or you can put all classes that would otherwise belong in a package inside a single file, but sticking several classes in a file may be a questionable design decision.
For me, the package visibility is helpful for its documenting value. I want to know what public interface some package is presenting to the rest of the project, hide factory implementation classes and so on.
So even if it's possible to access package-private classes and methods in Java, I still choose to use the package modifier.
For this I created a project with a single annotation:
package com.mycompany.libraries.kotlinannotations;
import static java.lang.annotation.ElementType.CONSTRUCTOR;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.SOURCE;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
#Documented
#Retention(SOURCE)
#Target({ TYPE, METHOD, CONSTRUCTOR })
/**
* Use in Kotlin code for documentation purposes.
*
* Whenever a Kotlin class or method is intended to be accesible at package level only.
*
*/
public #interface PackagePrivate {
}
Then I can use this annotation in any Kotlin project.
The second step, which I haven't done yet, is creating a PMD rule to enforce this with maven (or any other build tool for that matter) and also be able to see violations of the rule in my IDE with the pmd plugin.
There no is full Kotlin support in pmd at this moment but it seems to be expected at some point.
A near-replacement for package private visibility is available using the opt-in requirements feature (credit to pdvrieze on Kotlin discussions). This is the annotation syntax typically used to flag experimental features in an API.
To use it, create an annotation denoting package private declarations:
#RequiresOptIn(message = "Only to be used in MyPackage")
#Retention(AnnotationRetention.BINARY)
annotation class MyPackagePrivate
Then annotate any methods you want to be package private with it:
#MyPackagePrivate
fun aPackagePrivateMethod() {
// do something private within a package
}
In this way a warning will be generated on any method that calls the annotated method unless the calling method is itself annotated with the corresponding #OptIn annotation, here shown at class level:
#OptIn(MyPackagePrivate::class)
class AClassInThePackage {
fun userOfPackagePrivateMethod() {
aPackagePrivateMethod()
}
}
This, then, produces a similar effect to Java's package private, except that calling methods need to explicitly opt in to using a package private declaration.
If it is desired to generate an error rather than a warning, the level parameter of #RequiresOptIn can be specified:
#RequiresOptIn(level = RequiresOptIn.Level.ERROR, message = "Only to be used in MyPackage")
// annotation declaration as before
Package-based protection is pointless in Kotlin because packages themselves are unprotected
In Java, package was tied to directory structure. So if you put your classes in com\example\yoursecretengine, any attempt (deliberate or accidental) to add a rogue class there would be easily noticeable. This is the kind of security we've depended on.
Kotlin removes the ties between directory and package, so I can put my class in "my" directory (eg.src\java\pl\agent_l\illegalaccess) yet declare its package as com.example.yoursecretengine - and gain access to all the properties you've meant as package private.
In fact, a Kotlin project works perfectly without ANY package declarations. This only highlights that packages are "more what you'd call guidelines than actual rules". They're a convenience feature, useful only to unclutter namespace and nothing more.
Relevant quotes from kotlinlang:
unlike many other languages, Kotlin packages do not require files to have any specific locations w.r.t. itself; the connection between a file and its package is established only via a package header.
And:
an absence of a package header in a file means it belongs to the special root package.
Recently at my company a debate started after reviewing a different approach for writing heavy duty classes.
A big Java class holding component specific logic (no standard OOP principles made sense) had to be rewritten in Kotlin. The solution provided was splitting the logic in categories and the categories into separate files with internal extension functions to the main class.
Example:
Main.kt
class BigClass {
// internal fields exposed to the extension functions in different files
// Some main logic here
}
BusinessLogic.kt
internal fun BigClass.handleBussinessCase() {
// Complex business logic handled here accessing the exposed internal fields from BigClass
}
What are your thoughts on this? I haven't seen it used anywhere maybe for a good reason, but the alternative of thousand lines classes seems worse.
You have to consider that an extension function is nothing more than a function with an implicit first parameter which is referenced with this.
So in your case you'd have something like:
internal fun handleBussinessCase(ref: BigClass)
which would translate to Java as:
static void handleBussinessCase(BigClass ref)
But this could be assumed to be a delegate pattern, which could be encapsulated much cleaner in Kotlin as well.
Since the properties have to be internal anyhow, you could just inject these as a data class into smaller use-cases. If you define an interface around these (which would make the properties public though), you could create a delegate pattern with it and still reference each property with this in your implementation.
Here are some thoughts on making extension functions for the class:
It will be a utility function that will operate with the object you're extending, it will not be an object function, meaning that it will have access to only public methods and properties;
If you're planning to use class that being extended in unit tests, these methods (extensions) will be harder to mock;
Most likely they wont behave as you expect when used with inherited objects.
Maybe I missed something, so please read more about extensions here.
Is there any best practice regarding whether or not nested packages and classes is a good idea?
A) nested packages
i.e. Is it a good idea to have
utils
XXX.java
xxxx
XXX.java
XXX.java
model
view
activity
fragment
dialog (dialogfragment)
errors
sth
B) nested class
i.e. Is it a good idea to have
class Const {
class static HOST {
public final static String STAGING = "";
public final static String PRODUCTION = "";
}
class static Foo {
}
}
I would suggest you to take a look at this GitHub https://github.com/googlesamples/android-architecture made by Google developers. It provides samples to build Android apps using different architectural concepts and tools. Hope it helps.
A) There is no specific rule about package but a simple rule of thumb is that you should try to minimize package dependency cycling.
That means one package can depend on an other (or multiple other)
package and use their classes but the required package should minimize
the dependency to the first package. so the dependeny calls should
only go into one direction.
The more common packages are usually Activities, Fragments, Services, Receivers, Adapters, Models, Utilities and Helper Classes, Network and Database Packages.
B) Usually it's not a good practice to define inner classes especially for libraries that parse classes Dynamically like GSON. But if you are defining a Class that is Only used by a Specific Class you can encapsulate First class into the Second one for the sake of re-usability.
I am new to android and I started reading the training lessons so I read the term contract classes here and I didn't fully understand what is it used for and how; What I understood is that if you created a class and added in it some public variables to be accessed from other classes that's a contract class, so basically there isn't a pre-created class named Contract it's just a description?!! I don't know if that's true so please if not let me know what is it used for and how, plus they also said:
To prevent someone from accidentally instantiating the contract class, give it an empty constructor.
Why do I need to do that, is it for the hackers not to play with my code or?!!
thanks.