Monday, February 12, 2024

Bridging the Gap: Connecting Your Web App's Front-End and Back-End




The magic of a web application lies in the seamless dance between its front-end (FE) and back-end (BE). But how do these two distinct worlds converse and collaborate? Today, we'll delve into the various methods that connect FE and BE, exploring their strengths and weaknesses to help you choose the best fit for your web project.


The Communication Channels:


REST API: The classic act of sending HTTP requests for CRUD operations - create, read, update, delete - remains a popular choice. This familiar protocol is well-supported by libraries like Axios, making data exchange efficient and predictable. However, fetching multiple related resources can lead to numerous requests, impacting performance.


GraphQL: This query language emerges as a game-changer, allowing the FE to request only the specific data it needs. This granular approach minimizes unnecessary data transfer and boosts performance, especially for complex data structures.


WebSockets: Real-time is the name of the game here! WebSockets establish persistent connections, enabling efficient, bi-directional communication for live updates, chat applications, and more. The downside? Browser and server support can vary, and managing multiple connections adds complexity.


Server-Sent Events (SSE): For one-way real-time updates, SSE shines. The server pushes data to the client without the need for constant requests, ideal for live feeds and notifications. However, SSE doesn't support bi-directional communication, limiting its versatility.


Message Queues: Asynchronous communication gets a major boost with message queues. This decoupled approach allows the FE and BE to exchange messages without waiting for each other, improving scalability and resilience. Yet, setting up and managing message systems can add complexity.


RPC (Remote Procedure Call): Treat a remote function like a local one! RPC offers a familiar syntax for invoking procedures on the server, simplifying development. However, security concerns and potential performance bottlenecks demand careful consideration.


Beyond the Basics:

While Axios simplifies REST API communication, remember the server-side perspective. Utilizing template engines within backend frameworks like Django or Ruby on Rails can streamline dynamic HTML generation, improving maintainability and separation of concerns. However, be mindful of potential performance implications, especially as modern front-end frameworks often handle rendering themselves.

Using a template engine within a backend framework can be beneficial for rendering dynamic HTML on the server side. It allows for the separation of concerns by keeping the presentation logic in the templates, making it easier to maintain and modify the UI. Additionally, template engines often support features like template inheritance, partials, and helpers, which can streamline the development process.

However, it's important to consider the performance implications of using a template engine, as rendering templates on the server side can impact response times. Additionally, modern front-end frameworks and libraries often handle rendering on the client side, so the use of a template engine in the backend may depend on the specific requirements of the project.



Choosing the Right Path:

The optimal connection method hinges on your application's specific needs. Consider factors like data complexity, real-time requirements, scalability, and development complexity. Experiment, explore, and find the perfect bridge to connect your FE and BE, creating a harmonious web experience for all.


Here are some additional points that should be considered:

Caching
- Implement caching strategies like CDNs and redis to optimize performance


Authentication/Authorization
- Use JSON Web Tokens (JWT) or sessions to manage user access and permissions


Error Handling
- Handle errors gracefully and provide user-friendly messages


Logging
- Log requests, responses, and errors on both front-end and back-end to debug issues


Testing
- Write unit and integration tests to ensure different components work together as expected


Build Tools
- Use build tools like Webpack to optimize assets and deploy both front-end and back-end


Environments
- Set up dev, test, staging, and production environments to match workflows


Documentation
- Document integration points, data models, APIs, etc. to align teams


Monitoring
- Monitor performance metrics, logs, errors, and user journeys across the stack


Modular Design
- Build self-contained, reusable components that are easy to maintain and extend


Happy Coding!

Thursday, February 23, 2017

Optimize Android Studio speed

Go to/create file: /Users/aselims/Library/Preferences/AndroidStudio2.2/studio.vmoptions

Configure those options according to your RAM limits:

-Xms512m
-Xmx4096m
-XX:MetaspaceSize=512m
-XX:MaxPermSize=1024m
-XX:ReservedCodeCacheSize=512m
-XX:+UseCompressedOops

Thursday, February 9, 2017

Animations for the app

I would like to have general animations (transitions) between my activities. There are many possibilities. Use TransitionManager, use Activity#overridePendingTransition(), use ActivityOptions, FragmentTransaction#setCusotmAnimation()...

One general solution would be:

<style name="ActivityAnimations" parent="@android:style/Animation.Activity">
<item name="android:activityOpenEnterAnimation">@anim/slide_up_in</item>
<item name="android:activityOpenExitAnimation">@null</item>
<item name="android:activityCloseEnterAnimation">@null</item>
<item name="android:activityCloseExitAnimation">@anim/slide_out_right</item>
</style>


and apply in the base theme:
<item name="android:windowAnimationStyle">@style/ActivityAnimations</item>


To understand what those means, here is an excerpt from here
intactivityCloseEnterAnimationWhen closing the current activity, this is the animation
 that is run on the next activity (which is entering the screen).
intactivityCloseExitAnimationWhen closing the current activity,
this is the animation that is run on the current activity (which is exiting the screen).
intactivityOpenEnterAnimationWhen opening a new activity,
this is the animation that is run on the next activity (which is entering the screen).
intactivityOpenExitAnimationWhen opening a new activity,
this is the animation that is run on the previous activity (which is exiting the screen).


<!-- In case we need to generalize for the fragments
<item name="fragmentOpenEnterAnimation">@animator/fragment_open_enter</item>
<item name="fragmentOpenExitAnimation">@animator/fragment_open_exit</item>
<item name="fragmentCloseEnterAnimation">@animator/fragment_close_enter</item>
<item name="fragmentCloseExitAnimation">@animator/fragment_close_exit</item>-->

Monday, January 30, 2017

Keep Gradle uptodate

One of the downsides of Gradle is it takes a lot of time to build for big projects. Gradle team works on this problem with continuos efforts. So that means when you update Gradle, this means it could get better with increasing the speed of the build.

How?
- Check the latest Gradle distribution at: https://services.gradle.org/distributions/
-- At the time of this post, It is : gradle-3.4-rc-1-all.zip
-- Invoke with CmdLine: ./gradlew -wrapper -gradle-version=3.4-rc-1
-- Check the config file in <project>/gradle/wrapper/gradlewrapper.properties 
is changed to 
"distributionUrl=https\://services.gradle.org/distributions/gradle-3.4-rc-1-all.zip"

Happy build times! :)

Thursday, October 6, 2016

Save objects in Shared Preferences


private SharedPreferences preferences;
private SharedPreferences.Editor editor;

//Save objects
preferences = context.getSharedPreferences(namePreferences, mode);
editor = preferences.edit();
editor.putString(key, GSON.toJson(object));
editor.commit();

//Retrieve objects
String gson = preferences.getString(key, null);
Object o = GSON.fromJson(gson, a);

Tuesday, May 24, 2016

Calculate battery drain in your app

Interesting slide
 for each API call, it consumes 1/3 mAh
so if you just make API call a minute, you will drain the battery by 1/3 a day!


https://www.youtube.com/watch?v=QR3PIg0RDnk
#io16

Location, save battery and still have a great user experience!

Through patching data from Sensors (e.g. GPS, WiFi, Cell, Gyro, Magno, Acce) via FLP (Fused Location Provider) this leads to more battery saving as it sends those batched data at specific intervals which you can define according to your use case.
But if the user wants to know the exact location right now, they can immediately check it through Flushing callback which provides a seamless user experience.

Changes in Hardware (Lowest level of abstraction) makes User Experience much better (Highest level of abstraction)




Sources:
https://www.youtube.com/watch?v=OEvycEMoLUg
https://developers.google.com/awareness-location/

Thursday, March 17, 2016

Google Tag Manager and Analytics Integration

Firstly, we can say that you can send events from your app to GA directly. However, you can send events to GTM and then GTM will send those to analytics. Many reasons can be said why to use GTM over GA such as in here. But it always a Design/Need decision!

Anyhow, For Android, A draft implementation is at https://developers.google.com/tag-manager/android/v4/#getting-started

Check it, you may have some questions, you would find the answers in here I hope. So those are some of the lessons I learnt:
- Event Names and keys at Android code should match the corresponding ones at GTM.
dataLayer.pushEvent("openScreen",      DataLayer.mapOf("screenName", screenName));
- If you send Events from GTM to GA, the "value" field should be always Integer . if not, it will not be sent
public static void pushEvent(Context context, String event,String category, String label, Integer labelValue) {
        DataLayer dataLayer = TagManager.getInstance(context).getDataLayer();
        dataLayer.pushEvent(event, DataLayer.mapOf("eventCategory", category,"eventLabel", label, "eventValue", labelValue);
    }

- Configure GTM with Variables, Triggers, and Tags. as described here: https://developers.google.com/tag-manager/android/v4/ua#create-transaction-tag

- Use pushEvent rather than push. It is easier!

Thursday, March 10, 2016

Wednesday, March 9, 2016

Android font and caligraphy



So if you want to set an external font to a text view, you have different options:

- A common step: Get the font and put it under assets/fonts folder (create it if it not already created)

1 - Use this Gist:
Typeface typeface = Typeface.createFromAsset(getAssets(),"Roboto-Regular.ttf");
TextView textview = (TextView) findViewById(R.id.textview);
textview.setTypeface(typeface); 
2 - Use DataBinding Lib as described in here: fontbinding
3- Use XML attributes through custom widget: this is a good blog covering it all Custom fonts

Sunday, February 21, 2016

Some questions and answers "About me!"

I got those questions from a recruiter and I thought it is Ok to share them as a kind of about me!:
  1. What position are you looking for? Android Pervasive Engineer with great capacity of Technology Evangelism 
  2. Do you have any experience working in a Scrum environment?
    1. If yes, what was your role? Developer among Development Team
    2. What did you like about the process? Adapting to changes responsively and actively. Continous communication with frequent updates.
  3. What is your opinion on CI? Continous Integration is an essential building block in Software Development. Whenever you develop a feature, you are pretty sure that it will work seamlessly with other parts of software. if used properly, gives confidence about the product and its quality.
  4. What is QA for you and who is responsible for it? Quality Assurance is a proactive approach to tell this app would not crash. Every one working on the app is responsible for the quality of the app besides the QA team.
  5. What does Software Architecture mean to you? How do you ensure you have a maintainable and extensible code base? Building blocks interacting with each other and if you want to scale, you need architecture.  By following Best Practices, Design Patterns, Separating Concerns, Readable Naming Convention and surely Unit Testing.
     
  6. How big were the teams you worked in? And what is the ideal team size you feel comfortable with? as Android mobile development team 2-4 people. And it depends on the context 2 to 4 is nice with capacity of Pair Programming. 
  7. What is your experience in terms of mobile? I started with the early version of Android 1.1. I keep on track with latest trends in Android development as I am still eager to learn. I conduct presentations, workshops and participate in hackathons whenever possible besides I consider myself as a Mobile Computing Evangelist. 

Thursday, December 17, 2015

Configure Android Studio for UnitTesting with legacy structure

So you want to to use unit testing with Android Studio and you have an old code base that does not follow the standard folder structure of Android Studio.

- You need to create test/java folders in the module you want to test.
-- Tip: use external file explorer (e.g. Mac Finder) to do so outside Android.
- Add this to you module dependencies at build.gradle:
-- compile 'junit:junit:4.12'
-- Add Junit to the classPath
-- Start Testing!

Tuesday, December 8, 2015

Working with Legacy Code

As I am trying to find my way to a better quality well structured code, I am in my journey reading "Working Effectively with Legacy Code" by Michael Feathers.

I found the following strategy interesting:
"The general legacy management strategy is:
1. Identify change points
2. Find an inflection point
3. Cover the inflection point
 a. Break external dependencies
 b. Break internal dependencies
 c. Write tests
4. Make changes
5. Refactor the covered code."

Thursday, December 3, 2015

Dependencies Report in Android

So I learnt a nice feature through the Android Summit, How to generate dependencies report for certain module in your app:

-Gradle plugin -> your module -> help -> dependecies
- It will suffer saying no configurations
- Go to  Edit configurations -> tasks -> put your module you need to analyze e.g. ":app:dependencies"
- Build and run again, you would get sth like that:
+--- com.android.support:multidex:1.0.1
+--- project :volley
+--- com.squareup.picasso:picasso:2.5.2
+--- com.beaconinside:beaconinside-sdk-basic-1.2.2:
+--- com.android.support:support-v4:21.0.0 -> 23.0.1
|    \--- com.android.support:support-annotations:23.0.1
+--- com.android.support:appcompat-v7:21.0.0
|    \--- com.android.support:support-v4:21.0.0 -> 23.0.1 (*)
+--- com.google.android.gms:play-services-analytics:7.5.0
|    \--- com.google.android.gms:play-services-base:7.5.0
|         \--- com.android.support:support-v4:22.0.0 -> 23.0.1 (*)
+--- com.google.android.gms:play-services-gcm:7.5.0
|    \--- com.google.android.gms:play-services-base:7.5.0 (*)
+--- com.amazonaws:aws-android-sdk-core:2.+ -> 2.2.9
|    \--- com.google.code.gson:gson:2.2.4 -> 2.3.1
+--- com.amazonaws:aws-android-sdk-sns:2.+ -> 2.2.9
|    +--- com.amazonaws:aws-android-sdk-core:2.2.9 (*)
|    \--- com.amazonaws:aws-android-sdk-sqs:2.2.9
|         \--- com.amazonaws:aws-android-sdk-core:2.2.9 (*)
+--- com.readystatesoftware.systembartint:systembartint:1.0.3
+--- com.sensorberg.sdk:android-sdk-bootstrapper:2.0.0
|    \--- com.sensorberg.sdk:android-sdk:1.0.0 -> 1.0.4
|         +--- com.sensorberg.android:okvolley:1.1.4
|         |    +--- com.squareup.okhttp:okhttp-urlconnection:2.2.0
|         |    |    \--- com.squareup.okhttp:okhttp:2.2.0
|         |    |         \--- com.squareup.okio:okio:1.2.0
|         |    +--- com.google.code.gson:gson:2.3.1
|         |    +--- com.squareup.okhttp:okhttp:2.2.0 (*)
|         |    \--- com.sensorberg.android:volley:1.2.4
|         +--- io.realm:realm-android:0.79.1
|         +--- net.danlew:android.joda:2.7.2
|         |    \--- joda-time:joda-time:2.7
|         +--- com.sensorberg.android:networkstate:1.0.0
|         \--- com.sensorberg.android:volley:1.2.4
+--- com.sensorberg.sdk:android-sdk:1.0.4 (*)
+--- org.igniterealtime.smack:smack-bosh:4.1.5
|    +--- org.igniterealtime.smack:smack-core:4.1.5

Happy analyzing! :)

Sunday, November 22, 2015

Reactive Programming

- Why Rx:
abstracting away concerns about things like low-level threading, synchronization, thread-safety, concurrent data structures, and non-blocking I/O. Which makes your code more readable and bug-prone.


The key is stream... Everything is stream of events "Variables, User inputs, Data structures,...".
- A stream can be an input for another stream
- A stream can be filtered, combined or mapped to other values...
- A stream is immutable.
- Subscribe to a stream and get the value from onNext; finish at onCompleted; handle error at onError.
- A stream is called observable.


It is all about Feedback: Incremental Iterative Development

The following excerpt from "Growing object-oriented software guided by tests" is inspiring in how to Software Projects should work...

"The sooner we can get feedback about any aspect of the project, the better. Many teams in large organizations can release every few weeks. Some teams re- lease every few days, or even hours, which gives them an order of magnitude increase in opportunities to receive and respond to feedback from real users.
Incremental and Iterative Development
In a project organized as a set of nested feedback loops, development is incremental and iterative.
Incremental development builds a system feature by feature, instead of building all the layers and components and integrating them at the end. Each feature is implemented as an end-to-end “slice” through all the relevant parts of the system. The system is always integrated and ready for deployment.
Iterative development progressively refines the implementation of features in response to feedback until they are good enough."

Friday, October 9, 2015

Effective Permissions

I conducted a presentation about how to use Android Permissions effectively before and after M release at GDG Android Meetup: GDG Android Meetup

Here is the link for slides: here

The simple guide to contribute to open source


- Clone the repo you would like to contribute:
git clone https://github.com/aselims/frab.git

- Create a branch for the feature/issue you want to add/fix:
git checkout -b events_to_session

- Do your changes in the repo

- Commit & add
git commit -am "change event to session"

- Push your branch "with the changes"
git push origin events_to_session

- Go the github page and create a pull request and describe your change.

- Wait for merging :)

One Good Article: https://guides.github.com/activities/forking/

Tuesday, July 21, 2015

Retrieve a file that is mistakenly deleted with Git

Firstly, check the commits:

As-MacBook-Pro:Events aselims$ git log
commit dd2f0f7c2b3024ec29c2337be2f0a768a743a9a1
Author: aselims <selim.2k@gmail.com>
Date:   Tue Jul 14 20:22:15 2015 +0200

    time format.

commit 43032e348bf0015759836c4e5e035d66c62d05f1
Author: aselims <selim.2k@gmail.com>
Date:   Tue Jul 14 19:37:09 2015 +0200

    webFragment for support.
...

Then checkout the file you need from a specific revision
git checkout <revision> -- <path_to_file>

git checkout 43032e348bf0015759836c4e5e035d66c62d05f1 -- ./app/src/main/java/co/rahala/selim/events/util/WebFragment.java

The file is already now at its original place.