I am in the process of migrating from Android/JNI to Flutter/Dart/FFI to build native apps. Currently in Android I have a Java class (ScanningHelper.java) which is modified during the program lifecycle. During native initialization, I send a jobject type using which in my C/C++ code, I am able to call different member functions or even access variables directly (depending on access).
Is something similar possible with Dart FFI? The closest I have come to is possibly creating a struct in native and then using multiple functions to set/get data from native. I though have a feeling that the amount of code to be written will be high including memory clean up on Dart every time a string/const char* is returned.
Appreciate any direction to accomplish something like below without needing to duplicate implementation across both languages.
// ScanningHelper.java
public class ScanningHelper {
private String _mediaStorageDirectory;
public void setMediaStorageDirectory(String path) { _mediaStorageDirectory = path; }
public String getAppMediaStorageDirectory() { return _mediaStorageDirectory; }
public double latitude;
public double longitude;
...
byte[] image1Bytes;
}
I have some standard methods defined like getStringFromObjectMethod which allows reuse across different classes and return types;
// JNIMethods.cpp
std::string mediaDirectory = JNIMethods::getStringFromObjectMethod(jniEnv,_scanningHelper,"getAppMediaStorageDirectory"));
Related
So, I have a bit of a philosophical question in the realm of C++11 coding best practices.
When creating an application which essentially transforms data from one system to another. Should you define everything in classes, or use structs within a class?
Here is a more concrete example of what I am referring to.
For a typical class object. Should I create it this way:
class Contact {
std::string Name;
std::string Address;
:: :: ::
void Load();
void Save();
std::string OtherFunctions( std::string Name )
}
Or is it better to separate out the data from the class:
struct ContactInfo {
std::string Name;
std::string Address;
:: :: ::
}
class Contact {
ContactInfo data;
void Load();
void Save();
std::string OtherFunctions( std::string Name )
}
Several reason that I am contemplating the Struct over just doing in a class is the ability to transfer data between APIs. For example, the creation of these objects is done at a low level pure C++ application. But, at some point through the process, it is exposed to a managed C++ application and then finally consumed in a .NET application.
Secondly, as information is passed around from function to function, I am passing only the information and not the class object. With modern compilers, perhaps this point is mute, but logically to me, it seems better to pass data only than objects.
Thirdly, it separates class members needed to manage the object data from the data itself. So having a members like ErrorCode, ErrorMessage, etc, don't pollute what is considered data and what is not.
Am I off base here?
Is there a better way that I should be doing this type of activity?
This question is based on an answer I received for another question : https://stackoverflow.com/a/3060233/323357
My understanding is that the use of interfaces to declare return types and parameters types in my services forces the compiler to generate multiple compilation units, which increase my compile time and the size of generated files.
I don't think this is the case, but does the latest versions of gwt compiler (2.4 - 2.5) have a way to detect unnecessary compilation units...
for local variables and parameters?
void someFunction()
{
ArrayList<String> list = new ArrayList<String>();
privateFunction(list); //only use of the private function
}
private void privateFunction(List<String> list)
{
Set<Integer> set = new HashSet<Integer>();
//do stuff without reallocating list or set
}
for final members?
private final Interface member = new InterfaceImpl();
#override
Interface getInterface()
{
return this.member;
}
for return type?
List<String> myFunction()
{
List<String> ret = new ArrayList<String>();
//do stuff and fill the list
return ret;
}
in services?
//Service Interface
List<String> myService();
//Service implementation
List<String> myService()
{
List<String> ret = new ArrayList<String>();
//do stuff and fill the list
return ret;
}
Don't worry about the first 3 of your 4 examples. Usage of interfaces (or classes with many subclasses) on the client side has no cost: Unnecessary classes can be detected easily by analyzing which classes are ever instantiated. If in doubt, examine a compile report.
However, this is impossible in GWT-RPC for server side calls: The client has no way to know, which instances the server will create. Consider that
the same client can continue to work with updated versions of the server (as long as the service definition is unchanged)
the server can use reflection to dynamically generate objects: any subtype of the declared type (and this is by the way a major reason why reflection isn't available on the client side)
The only ways this code size overhead can ever be eliminated, are to either
give up type safety (you can use JSON based approaches!)
or analyze the server side during compilation and forbidding to transfer objects that were generated dynamically (this would require a GWT re-compile whenever object instantiation code on the server side changes)
I'm thinking of introducing some kind of caching mechanism (like HTML5 local storage) to avoid frequent RPC calls whenever possible. I would like to get feedback on how caching can be introduced in the below piece of code without changing much of the architecture (like using gwt-dispatch).
void getData() {
/* Loading indicator code skipped */
/* Below is a gwt-maven plugin generated singleton for SomeServiceAsync */
SomeServiceAsync.Util.getInstance().getDataBySearchCriteria(searchCriteria, new AsyncCallback<List<MyData>>() {
public void onFailure(Throwable caught) {
/* Loading indicator code skipped */
Window.alert("Problem : " + caught.getMessage());
}
public void onSuccess(List<MyData> dataList) {
/* Loading indicator code skipped */
}
});
}
One way I can think of to deal with this is to have a custom MyAsyncCallback class defining onSuccess/onFailure methods and then do something like this -
void getData() {
AsyncCallback<List<MyData>> callback = new MyAsyncCallback<List<MyData>>;
// Check if data is present in cache
if(cacheIsPresent)
callback.onSuccess(dataRetrievedFromCache);
else
// Call RPC and same as above and of course, update cache wherever appropriate
}
Apart from this, I had one more question. What is the maximum size of storage available for LocalStorage for popular browsers and how do the browsers manage the LocalStorage for different applications / URLs? Any pointers will be appreciated.
I suggest to add a delegate class which handles the caching. The delegate class could look like this:
public class Delegate {
private static SomeServiceAsync service = SomeServiceAsync.Util.getInstance();
private List<MyData> data;
public static void getData(Callback callback) {
if (date != null) {
callback.onSuccess(data);
} else {
service.getData(new Callback() {
public onSuccess(List<MyData> result) {
data = result;
callback.onSuccess(result);
});
}
}
}
Of course this is a crude sample, you have to refine the code to make it reliable.
I did take too long to decide on using hash maps to cache results.
My strategy was not to use a singleton hashmap, but a singleton common objects class storing static instances of cache. I did not see the reason to load a single hashmap with excessive levels of hashtree branching.
Reduce the amount of hash resolution
If I know that the objects I am dealing with is Employee, Address, Project, I would create three static hashes
final static private Map<Long, Employee> employeeCache =
new HashMap<Long, Employee>();
final static private Map<Long, Address> addressCache =
new HashMap<Long, Address>();
final static private Map<String name, Project> projectCache =
new HashMap<String name, Project>();
public static void putEmployee(Long id, Employee emp){
employeeCache.put(id, emp);
}
public static Employee getEmployee(Long id){
return employeeCache.get(id);
}
public static void putEmployee(Long id, Address addr){
addressCache.put(id, addr);
}
public static Address getEmployee(Long id){
return addressCache.get(id);
}
public static void putProject(String name, Address addr){
projectCache.put(name, addr);
}
public static Address getProject(String name){
return projectCache.get(name);
}
Putting it all in a single map would be hairy. The principle of efficient access and storage of data is - the more information you have determined about the data, the more you should exploit segregating that data using that information you have. It would reduce the levels of hash resolution required to access the data. Not to mention all the risky and indefinite type casting that would need to be done.
Avoid hashing if you can
If you know that you always have a single value of CurrentEmployee and NextEmployee,
avoid storing them in the hash of Employee. Just create static instances
Employee CurrentEmployee, NextEmployee;
That would avoid needing any hash resolution at all.
Avoid contaminating the global namespace
And if possible, keep them as class instances rather than static instances, to avoid contaminating the global namespace.
Why avoid contaminating the global namespace? Because, more than one class would inadvertently use the same name causing untold number of bugs due to global namespace confusion.
Keep the cache nearest to where it is expected or used
If possible, if the cache is mainly for a certain class, keep the cache as a class instance within that class. And provide an eventbus event for any rare instance that another class would need to get data from that cache.
So that you would have an expectable pattern
ZZZManager.getZZZ(id);
Finalise the cache if possible,
otherwise/and privatise it by providing putters and getters. Do not allow another class to inadvertently re-instantiate the cache, especially if one day your class becomes a general utility library. Also putters and getters have the opportunity to validate the request to avoid a request from wiping out the cache or pushing the app into an Exception by directly presenting the cache with keys or values the cache is unable to handle.
Translating these principles into Javascript local storage
The GWT page says
Judicious use of naming conventions can help with processing storage data. For example, in a web app named MyWebApp, key-value data associated with rows in a UI table named Stock could have key names prefixed with MyWebApp.Stock.
Therefore, supplementing the HashMap in your class, with rather crude code,
public class EmployeePresenter {
Storage empStore = Storage.getLocalStorageIfSupported();
HashMap<Long, Employee> employeeCache;
public EmployeePresenter(){
if (empStore==null) {
employeeCache = new HashMap<Employee>();
}
}
private String getPrefix(){
return this.getClass()+".Employee";
//return this.getClass().getCanonicalName()+".Employee";
}
public Employee putEmployee(Long id, Employee employee)
if (empStore==null) {
stockStore.setItem(getPrefix()+id, jsonEncode(employee));
return;
}
employeeCache.put(id, employee);
}
public Employee getEmployee(Long id)
if (empStore==null) {
return (Employee) jsonDecode(Employee.class, stockStore.getItem(getPrefix()+id));
}
return employeeCache(id);
}
}
Since, the localstore is string based only, I am presuming that you will be writing your own json encoder decoder. On the other hand, why not write the json directly into the store the moment you receive it from the callback?
Memory constraints?
I cannot profess expertise in this question but I predict the answer for hashmaps to be the maximum memory constrained by the OS on the browser. Minus all the memory that is already consumed by the browser, plugins and javascript, etc, etc overhead.
For HTML5 local storage the GWT page says
"LocalStorage: 5MB per app per browser. According to the HTML5 spec, this limit can be increased by the user when needed; however, only a few browsers support this."
"SessionStorage: Limited only by system memory"
Since you are using gwt-dispath an easy solution here is to cache the gwt-dispatch Response objects agains the Request objects as a key in a Map. Its easy to implement and type agnostic. You will need to override Request - equals() method to see if the Request is already in the cache. If yes return Response from cache otherwise hit the server with a call.
IMO - LocalStorage is not a necessity here if all you need is in session cache for performance. Local Storage only a must for offline apps.
You may look into this - http://turbomanage.wordpress.com/2010/07/12/caching-batching-dispatcher-for-gwt-dispatch/
I am writing (with my team) an GWT application, which parses and represent some domain specific language - for example, plays media presentation with text, video and UI controls. So the application has a set of components: ones - for holding model, ones - for control routines (controllers), and of course we have classes for View.
Now we have a problem - make it all plug-able, in the sense of:
should be one core plugin, which make all common stuff. This coer block must be an JavaScript file (one for every permutation)
should be ability to extend core classes, write custom ones - and compile it to separate JS file (one for every permutation)
Every plugin must registers (export it's classes etc) itself to the core platform, so it could be used.
Problems:
How to compile the custom stuff
separately ?
How to load plugins ?
For the second one problem i've found http://code.google.com/p/gwt-exporter/, that exports GWT classes to outer world, so they could be invoked from pure JS.
Also I have an idea to create new module for new plugin, so it will be compiled to separate file (first problem).
Have you an experience of building such architecture, have you some best practices in this case ?
I have experimented with this same question since GWT 1.5 and every time I come up with a more elegant solution they change the linker and break it. The only way that I have come up with that would work independent of linker design is to do exactly what you are talking about and create a new module for ever plug-in. Then use GWT exporter to create an abstract class that plugins must extend that would have an abstract method that would take the root element of the plugin passed to it by the core and populate it. The issue with this method is all plug-in modules must be added to the DOM on the initial load of the page because since 2.0 the iFrame linker relies on a page load event so dynamically added modules wont fully load. So because of this you will want to have the exported population method wrapped in runAsync so that you aren't downloading modules till you use them.
Edit:
Here is a rough example of what I am talking about. Please be aware that I haven't done any GWT in a couple years and there may be a better way of doing this by now.
public final class PluginManager
{
public static final PluginManager INSTANCE = new PluginManager();
private PluginManager()
{
}
private static native void loadPlugin( AbstractPlugin plugin )
/*-{
if (!$wnd.Plugins) {
$wnd.Plugins = {};
}
var name = plugin.#com.example.PluginManager.AbstractPlugin::getName()();
$wnd.Plugins[name] = $entry(plugin.#com.example.PluginManager.AbstractPlugin::load(Ljava/lang/String;));
}-*/;
private static native void unloadPlugin( AbstractPlugin plugin )
/*-{
if ($wnd.Plugins) {
var name = plugin.#com.example.PluginManager.AbstractPlugin::getName()();
delete $wnd.Plugins[name];
}
}-*/;
private static native JsArrayString getPlugins()
/*-{
if ($wnd.Plugins) {
return Object.keys($wnd.Plugins);
}
return undefined;
}-*/;
public static abstract class AbstractPlugin implements EntryPoint
{
#Override
public final void onModuleLoad()
{
PluginManager.INSTANCE.loadPlugin( this );
}
protected final void unload()
{
PluginManager.INSTANCE.unloadPlugin( this );
}
protected abstract String getName();
protected abstract void load( String rootPanelId );
}
}
I saw multiple examples in MSDN that uses to declare the internal fields at the end of the class. What is the point?
I find this a little embarrassing, because each time Visual Studio adds a method it adds it to the end of the class, so there is need every time to move it...
class A
{
public A(){}
// Methods, Properties, etc ...
private string name;
}
class A
{
private string name;
public A(){}
// Methods, Properties, etc ...
}
In C++, it makes sense to put the public interface of the class at the top, so that any user of the class can open up your header file and quickly see what's available. By implication, protected and private members are put at the bottom.
In C# and Java, where interface and implementation are completely intertwined, people would probably not open your class's source code to see what's available. Instead they would rely on code completion or generated documentation. In that case, the ordering of the class members is irrelevant.
If it's obvious the variable has been declared, and the code is by way of an example, then arguably this gets you to the bit being demonstrated quicker - that's all I can think of.
Add-ins like ReSharper will allow you to standardise and automatically apply this layout at the touch of a key combination, by the way, if it is what you want.
Many programmers strive for self-documenting code that helps clients to understand it. In C++ class declaration, they would go from most important (i.e. what is probably most frequently inspected) to least important:
class Class {
public:
// First what interest all clients.
static Class FromFoobar(float foobar); // Named constructors in client code
// often document best
Class(); // "Unnamed" constructors.
/* public methods */
protected:
// This is only of interest to those who specialize
// your class.
private:
// Of interest to your class.
};
Building on that, if you use Qt, the following ordering might be interesting:
class SomeQtClass : public QObject {
public:
signals: // what clients can couple on
public slots: // what clients can couple to
protected:
protected slots:
};
Then the same down for protected and private slots. There is no specific reason why I prefer signals over slots; maybe because signals are always public, but I guess the ordering of them would depend on the situation, anyhow, I keep it consistent.
Another bit I like is to use the access-specifiers to visually seperate behaviour from data (following the importance ordering, behaviour first, data last, because behaviour is the top-interest for the class implementor):
class Class {
private:
void foobar() ;
private:
float frob_;
int glob_;
};
Keeping the last rule helps to prevent visual scattering of class components (we all know how some legacy classes look like over time, when variables and functions are mixed up, not?).
I don't think there is any valid reason for this. If you run Code Analysis on a class declared like this you'll get an error as private fields should be declared on top of classes (and below constants).