sue spielman [email protected] president/senior consulting engineer 2004 switchback...

35
Sue Spielman [email protected] President/Senior Consulting Engineer 2004 Switchback Software LLC J2ME Tips, Tricks, & Best Practices

Upload: joshua-harvey

Post on 25-Dec-2015

214 views

Category:

Documents


0 download

TRANSCRIPT

Sue [email protected]

President/Senior Consulting Engineer

2004 Switchback Software LLC

J2ME Tips, Tricks, & Best Practices

www.switchbacksoftware.com © 2004

Who is Sue?

President of Switchback Software LLC

18+ years hands-on enterprise and mobile application development experience

Author, technology columnist, magazine contributor, JSP 2.1 EG member

www.switchbacksoftware.com © 2004

Objective

Provide some experience sharing of things that you want to do and things you don’t

want to do when dealing with mobile devices.

Provide some experience sharing of things that you want to do and things you don’t

want to do when dealing with mobile devices.

www.switchbacksoftware.com © 2004

Content

Development tactics

MIDlet programming

Designing UI

XML Parsing

Optimizing

www.switchbacksoftware.com © 2004

Development TacticsDevelopment Tactics

www.switchbacksoftware.com © 2004

J2ME – The Real Questions

Ask yourself these 3 questions each time you write a method:

How can I reduce it?

How can I reuse it?

How can I eliminate it?

www.switchbacksoftware.com © 2004

Main Areas of Size

The code size of the MIDlet for device loading

Runtime size

Runtime behavior – use of processor usage

www.switchbacksoftware.com © 2004

Development Tactics Tips

JAR > 50K might not loadTradeoffs must be made

Don’t over-abstractInterfaces, classes should be scrutinized

Consider cost of fine-grained methodsBe careful when using String

Immutable, causes more garbage collection, slower performance

Pay attention to HeapReuse and pool objects when possible

All I/O is very slowThreading when appropriate

www.switchbacksoftware.com © 2004

MIDlet Programming TipsMIDlet Programming Tips

www.switchbacksoftware.com © 2004

MIDLet Programming Tips

Use Scalar types where ever possible instead of Java Objects

Release resources early: Network Connections, RecordStores, Resource Streams

Be aware of the Garbage Collector Setting unused objects to null

Use Exceptions only when needed, as each Exception throws an Exception object

Lazy Instantiation

www.switchbacksoftware.com © 2004

More Tips

Use Local Variables It is generally faster to access local variable than class members.

Wherever possible, you can assign a class member to a temporary local variable and use it for repeated use.

Avoid String Concatenations. Use StringBuffer instead.

www.switchbacksoftware.com © 2004

MIDLet Suites

Keep MIDlets simple.

If you’re application is complex, delivery it as separate MIDlets in a single suite.

MIDlet to MIDlet communication via the RecordStore vs. large MIDlet using lots of global variables

When loading a single MIDLet, it will only load the classes that it needs vs. loading classes that only used by a portion of a larger MIDlet

www.switchbacksoftware.com © 2004

Designing UIDesigning UI

www.switchbacksoftware.com © 2004

Designing Tips for UI’s

Make it usable on all devicesTry and use Abstraction over Discovery techniques

Keep target in mindAlphabetic input difficult

Use lists or buttons

Small screen

Not all devices have pointing device

Be consistent with key use

Use either Displays or Forms

www.switchbacksoftware.com © 2004

CommandListener Design

In simple applications, the MIDlet can be the CommandListener

However, the object-oriented way is to create a CommandListener for each Displayable

Each If body statement should be as short as possible making a call to a support or utility routine, whenever possible

Utilities routines are shared among all CommandListeners

www.switchbacksoftware.com © 2004

XML ParsingXML Parsing

www.switchbacksoftware.com © 2004

XML Parsing

Different options

Consider doing parsing on the Server instead of client

Use XSLT on server to compress<Choice name="Apples"/> to <C n="Apples/>

Introduce persistence on the server

Reduce message sizes

Supporting multiple clients

www.switchbacksoftware.com © 2004

Message Formatting

Different mechanisms available for doing message formatting

kXML-RPC is very easy to use and fast

kSOAP is another alternative

Let’s look at the difference between XML-RPC vs. SOAP

www.switchbacksoftware.com © 2004

XML-RPC vs. SOAP*

SOAP is asynchronous, XML-RPC is not SOAP supports request routing and pre-processing of requests via SOAP headers XML-RPC is lighter, taking up less bandwidth, and requiring less processing power SOAP is namespace-aware (in fact every element must be namespace-qualified) SOAP has a heavy-weight, robust data typing mechanism based on XML Schemas XML-RPC is easily sent and consumed, and is easily readable by humans SOAP messages have a considerable amount of packaging contained in the envelope, but this allows for flexibility in the messaging paradigm used (publish-subscribe, point-to-point, etc.) *Source: kXML-RPC FAQ*Source: kXML-RPC FAQ

www.switchbacksoftware.com © 2004

When to use kXML-RPC*

Speed is of greater importance than flexibility

Memory usage is a critical factor

Program size must be very small ( < 8kb )

The data being exchanged is simple, or at very least the relationships between the data are simple

You need a neutral, standardized, lightweight mechanism for exchanging data, or remotely invoking some network service

*Source: kXML-RPC FAQ*Source: kXML-RPC FAQ

www.switchbacksoftware.com © 2004

When to use kSOAP*

Flexibility and a robust feature-set are a high priority

Program size and memory usage are less important than advanced networking features

The data being exchanged is complicated, the relationships between the data are complicated, or is it important to define custom data types

If you are uncertain which protocol will be used by potential clients and partners (SOAP is more popular, and thus a better bet in an uncertain situation)

*Source: kXML-RPC FAQ*Source: kXML-RPC FAQ

www.switchbacksoftware.com © 2004

Over the Wire consideration

Don’t poll!

Message formatsHTTP conditional GET to avoid unnecessary traffic

SMS, take advantage of push

SecurityEncryption and using HTTPS comes at a performance price

Support off-line work as much as possible Take advantage of data synchronization, on-device persistent storage (RMS)

Reduce network round-tripping

www.switchbacksoftware.com © 2004

OptimizingOptimizing

www.switchbacksoftware.com © 2004

Battery considerations

Try not to busy-wait.Most devices will go into sleep mode anyway…

Keep aware if there are APIs that are battery intensive (e.g. NMEA, backlighting, etc.)

www.switchbacksoftware.com © 2004

Using Arrays

Arrays are faster and leaner than the Collection Objects

Vector is just a wrapper for Array anyway…

For MIDlets, if you do decide to use Vectors and HashTables, try to size them correctly

Both Vector and HashTable grow as needed

Default is 100, which is usually way more than you need

Vector creates an internal array and copies elements from the old to the new Array

HashTable performs computationally intensive rehashing

www.switchbacksoftware.com © 2004

Data Access Strategies

For every row type, create a utility to encapsulate and isolate the complexity of record management.

Have a single place that reads and a single place that writes

Order and type are critical because the data is stored in a ByteArray

www.switchbacksoftware.com © 2004

Optimizing Resources

Try and reuse Object as much as possible

Reusing existing instances

Avoid allocations when possible

Reduces memory usage

Produces less garbage when the GC runs

Possibly create a cache

Utilize whatever optimization tool you’re working with: Jbuilder OptimizeIt, WTK 2.0 Profiler, Motorola SDK

www.switchbacksoftware.com © 2004

Threading

Whenever doing any task that is longer that X amount of time, execute it in a separate thread

The main thread primary responsibility is to handle hardware interaction and event management

If you lock your main thread up with something slow (like I/O, networking) your application appears to lock up.

Make use of thread priority

www.switchbacksoftware.com © 2004

Optimize Deployment

Make the JAR as small as possible

Eliminate classes that you aren’t usingDon’t do an import com.myclasses.*

Try and partition classes functionally efficient. That way when the class is loaded, everything in it will be used and not waste memory.

www.switchbacksoftware.com © 2004

Use an Obfuscator

Use an Obfuscator to reduce the size of class files

Adds an extra element of security, by making class files hard to de-compile

Include an obfuscator task in the build.xml and try to make use of such tools as Proguard

Some Obfuscators allow for pruning of class which is good for reducing package sizes

Caution: Don’t turn the Obfuscator on right before you are shipping a product! Make sure that you’ve tested with it because there are sometimes unexpected errrors…

www.switchbacksoftware.com © 2004

Benchmarking

Get into the habit of measuring memory usage

Do it as part of the development processUse: Runtime. getRuntime().totalMemory() andRuntime. getRuntime().freeMemory()

Can also measure the speed of the MIDlet usingSystem. currentTimeMillis()

Visit www.jbenchmark.com. This is a cool site for seeing how devices execution speeds compare and you can get an idea of how your MIDlet might run

www.switchbacksoftware.com © 2004

Going Small – Bigger is Not Better

Use shorter names to reduce class file byte code or let the Obfuscator do it

Class/member renaming, prune unused classes & methods

Data caching when using RMS

Conditional compilationsIf (Debug.ON) println(…)

Optimize: estimate size of Hashtables and Vectors upon construction

www.switchbacksoftware.com © 2004

When Things Go Wrong

MIDlet works in emulator, but not on phone. Some things to check for:

Check to make sure the JAR size is correct in the JADSome devices (like Motorola) seem to require a 3 digit version 1.0.0. 1.0 might work in the emulator, but not on the device.

Make sure that emulator settings closely reflect performance metrics on the phone

Possible need to contact phone vendor to get suggestionsFor example, i730 default setting in the SDK are very similar to the actual phone except for intensive GUI renderingPlay with different setting for things like network latency

www.switchbacksoftware.com © 2004

Optimization tools

Provided in the WTK

Memory monitor – for device activity

Profiler – for code coverage

Network monitor – see what is in the packets

Others might be available depending on what your IDE might have.

www.switchbacksoftware.com © 2004

Wrap Up

There are lots of small (no pun intended) details to pay attention too.

Code, tools, and techniques can make a difference between having an app that runs and having one that runs away.