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.
Related
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.
I am new to android. If my question is wrong please forgive me,
My Question is:
Can I write a method in android which can be accessed from anywhere inside my application?
I've studied VB for all these years and now I am trying to program in android, I couldn't stop comparing them when I write code.
In VB we can create modules and access it from anywhere. Is there anything I can do in Android...??
Answers and advises are needed!
You have to create a class with a static method:
public class MyClass {
public static void myMethod() {
// Your code here...
}
}
And you can call it like this: MyClass.myMethod();
You can try extending Application and put your common functions there.
In all activities you can access this via context.
For reference follow this:
http://www.devahead.com/blog/2011/06/extending-the-android-application-class-and-dealing-with-singleton/
It is a long topic to discuss , but as you have simply ask whether method is accessible or not , then answer is yes but with some respect of java rules.
Android is again like java coding, You can do same thing what we can do with java.
Same Data type
Method Format
Class structure
Inheritance, Public , private , protected, etc.
So while you write your code you should care for that all things and these all thing you know because you are working in VB.
VB module equivalent is not there in java(android),
but some how you can mock them to some extend by using final classes with static methods.
Anyway you need to import the package containing these type of classes wherever you use it.
I have created an application which uses a lot of custom objects I've created to manage parts of the application.
for example:
FacebookManager class - responsible for connecting to facebook
DatabaseManager class - responsible for application's database connection
etc...
these classes must be reachable for all application's classes.
i've extend the Application class and i'm sharing the Application instance between class so every class will be able to reach the global objects (and some more methods).
i'm wondering if this is the correct way of doing what i want, or should i create a class with static methods for the same propose.
I've read a lot about it and understood that from the memory point of view - non of these ways are best.
is there a way to save an object to the SharedPereferences and get it from another class ?
or any other idea ?
If your classes contain no states but only utility methods - you can arrange them as Utils classes, with no constructors and static methods. Otherwise, take a look at the Singleton design pattern, which is used to create a global access point for an object of class and ensures there's only one object of that class in the whole system. Hope this helps.
Recently I have started development in Java for Android.
My idea is to create one static class which will load ton of stuff on the beginning and store results for a lifetime of application.
I have been reading lot of how to share object between activities and I think the best will be to create one static class. What do you think? Should I use another approach? I am asking because I have read lot of counter opinions over the internet.
Thank you.
I'm assuming that you were referring to static fields of a class, as opposed to static class which, as Wyzard pointed out, is something completely different. As a general rule of thumb, holding information in static fields is not a good idea in Java. The reason for this is that it prevents the ability to instantiate multiple instances of whatever it is you store in the class.
In the specific case of an Android application, the best way to deal with the issue of having data stored associated with the application itself is to subclass the android.app.Application class and use it to handle application-global data:
class FooApplication extends Application
{
private String privData;
public String getPrivData() {
return privData;
}
}
You then need to declare that this class is your main application class (instead of the default Application). In the application entry in AndroidManifest.xml add the following:
<application android:name="com.example.application.FooApplication"
...>
...
</application>
You can then look up the application instance from anywhere inside your application using the method Context.getApplicationContext() which will be an instance of your Application subclass:
FooApplication app = (FooApplication)Context.getApplicationContext();
String privData = app.getPrivData();
Depending on from where you are trying to look for subclass of "Application", you may have to invoke the "getApplicationContext()" without "Context":
FooApplication app = (FooApplication)getApplicationContext();
String privData = app.getPrivData();
The problem with your solution is that you're basically creating a huge stack of globals. It's sometimes unavoidable, but it has the same type of problems globals always have- you quickly end up with hard to read code that doesn't really have a good OO breakdown. You can use this, but use it sparingly- only with important data structures that are really going to be shared between many activities.
Android provides a class called Application, which is will not be gc'ed as long as your Application isn't killed. Use this class for initialization, static classes as containers are somewhat ugly, but i can't pinpoint why that is.
I only use them as containers for constants such as bitmasks which can't be expressed as EnumSets.
As the other posts mention SharedPreferences: I think the preferences exist to store values, but not to load your structures that you need for you application. These structures should be loaded from a construct that represent or make up a model for your data's semantics.
There are many questions and answers on how to implement a global variable in Android/Java.
So it seems one can either implement a singleton or use a data class itself with static variables.
I am about to start a larger project and would like to start on the right foot.
I am just not sure which one to use.
Pro singleton/con Data Class
supposedly "cleaner" way (but I really don't know why)
ensures that there is really always just one representation
creates a new instance should the old one be "cleaned away" (whenever this may happen?)
Con singleton/pro Data Class
not recommendet by some (but did not find convincng reasons)
ensures that there is only one representation by design
very easy to access just by writing MyDataClass.x (vs accessing singleton requires getting access to it first somehow)
no need to pass it as a parameter
So in summary I tend to use DataClass but I am unsure because I read that this is supposedly not good programming style.
I like to add
the data this global object has to hold is quite big, more than 30k strings/keys. And this should not be cleaned at any stage so that when the app return it may crash because of that - as I read in other places eg Singletons vs. Application Context in Android? (the 3rd answer)
it's not a web application, I use only one classloader
it is multithread but only one thread is actually accessing this data
one may certainly also use this approach How to declare global variables in Android?, but isn't an ObjectClass just easier to use and access in this case?
And checking this http://developer.android.com/resources/faq/framework.html, esp under "Persistent Objects", implies that there is no real advantage for on or the other in those cases anyway.
Many thanks
Best way to implement singleton is to use enum.
public enum Singleton
{
INSTANCE;
public void someMethod()
{
// your code here
}
}
For more details you can read Effective Java (2nd Edition)
First of all: There's not much difference between a class with public static member variables and a singleton class. A lot of developers prefer the singleton pattern because the code looks more natural and more Java. E.g. Singleton.Data looks like a constant access and Singleton.getData() looks like you're accessing some kind of static data.
Personally I use the static Application pattern: See Accessing resources without an Activity or Context reference
You can use onCreate to setup any kind of static data or even other singletons. E.g. I prefer to setup a singleton SQLite database like that and access it then via App.getDb(). You can use this pattern to access the application context or resources.
While using static data you should think about memory leeks. I would recommend to take a look at this article then.