Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsWhite Papers
Discussion GroupsFirst AidDatabasesJavaBeansGUIJava 3DVirtual MachineCORBASecurityToolsGeneral
Java DirectoryOpen Source ProjectsSample Book ChaptersUser GroupsWeb Resources
Related Topics
Databases.NETMore Topics ...

Java Forum / General / March 2007

Tip: Looking for answers? Try searching our database.

"pointing" to functions to execute for scaleable code

Thread view: 
metaperl - 03 Mar 2007 13:29 GMT
I've been a programmer for many years and am just learning Java. In
the code below, I think that the for loop from
j=0 to j=3 is poor code. Instead there should be an array of
"pointers" to each getInstance function and one should iterate through
that "dereferencing" each function pointer.

Pseudo code -

FunctionPointer fplist[] = { getInstance, getIntegerInstance,
getCurrencyInstance, getPercentInstance } ;

for (fp : fplist) {
 fp->(locales[i])
}

import java.text.DecimalFormat;
import java.text.NumberFormat;

import java.text.ParseException;

import java.util.Locale;

class nf {
   public static void main(String[] arg) {

    // Print out a number using the localized number, integer, currency,
    // and percent format for each locale
    Locale[] locales = NumberFormat.getAvailableLocales();
    double myNumber = -1234.56;
    NumberFormat form;
    for (int j=0; j<4; ++j) {
       System.out.println("FORMAT");
       for (int i = 0; i < locales.length; ++i) {
        if (locales[i].getCountry().length() == 0) {
           continue; // Skip language-only locales
        }
        System.out.print(locales[i].getDisplayName());
        switch (j) {
        case 0:
           form = NumberFormat.getInstance(locales[i]); break;
        case 1:
           form = NumberFormat.getIntegerInstance(locales[i]); break;
        case 2:
           form = NumberFormat.getCurrencyInstance(locales[i]); break;
        default:
           form = NumberFormat.getPercentInstance(locales[i]); break;
        }
        if (form instanceof DecimalFormat) {
           System.out.print(": " + ((DecimalFormat) form).toPattern());
        }
        System.out.print(" -> " + form.format(myNumber));
        try {
           System.out.println(" -> " + form.parse(form.format(myNumber)));
        } catch (ParseException e) {}
       }
    }
   }
}
Eric Sosman - 03 Mar 2007 13:51 GMT
> I've been a programmer for many years and am just learning Java. In
> the code below, I think that the for loop from
> j=0 to j=3 is poor code. Instead there should be an array of
> "pointers" to each getInstance function and one should iterate through
> that "dereferencing" each function pointer.
> [code snipped]

    Are you just stating an opinion, or do you have a question?

Signature

Eric Sosman
esosman@acm-dot-org.invalid

Tom Hawtin - 03 Mar 2007 13:55 GMT
> I've been a programmer for many years and am just learning Java. In
> the code below, I think that the for loop from
> j=0 to j=3 is poor code. Instead there should be an array of
> "pointers" to each getInstance function and one should iterate through
> that "dereferencing" each function pointer.

Being firmly in the object camp, Java does not have function pointers.
If you want something it should be an object. That object may be of a
strategy type that just adds one method and no state (other than
implementation class, identity and monitor).

The usual way of doing it is with an (anonymous) inner class. Since 1.5,
there has been an easy way to define a closed family, using enum.

enum NumberFormatType {
    GENERAL() {
        public NumberFormat get(Locale locale) {
            return NumberFormat.getInstance(locale);
        }
    },
    INTEGER() {
        public NumberFormat get(Locale locale) {
            return NumberFormat.getIntegerInstance(locale);
        }
    },
    CURRENCY() {
        public NumberFormat get(Locale locale) {
            return NumberFormat.getCurrencyInstance(locale);
        }
    },
    PERCENT() {
        public NumberFormat get(Locale locale) {
            return NumberFormat.getPercentInstance(locale);
        }
    };
    public abstract NumberFormat get(Locale locale);
}
...
    private final List<NumberFormatType> formatTypes = Arrays.asList(
        NumberFormatType.GENERAL,
        NumberFormatType.INTEGER,
        NumberFormatType.CURRENCY,
        NumberFormatType.PERCENT
    );
    ...
        for (NumberFormatType formatType : formatTypes) {
            System.out.println("FORMAT");
            for (Locale locale : locales) {
                if ("".equals(locale.getCountry())) {
                    continue; // Skip language-only locales
                }
                System.out.print(locale.getDisplayName());
                NumberFormat format = formatType.get(locale);
                ...

Tom Hawtin
Lew - 03 Mar 2007 14:57 GMT
>> I've been a programmer for many years and am just learning Java. In
>> the code below, I think that the for loop from
[quoted text clipped - 9 lines]
> The usual way of doing it is with an (anonymous) inner class. Since 1.5,
> there has been an easy way to define a closed family, using enum.

Not always an inner class. It is also common to use an interface, e.g.,
Runnable, and pass around different instances of implementations that may or
may not be inner classes.

A related term is "polymorphism", whereby a subclass object performs an action
declared by the superclass, but in its own way.

-- Lew
Chris Uppal - 03 Mar 2007 18:30 GMT
>      private final List<NumberFormatType> formatTypes = Arrays.asList(
>          NumberFormatType.GENERAL,
[quoted text clipped - 4 lines]
>      ...
>          for (NumberFormatType formatType : formatTypes) {

You could replace the above code with:

        for (NumberFormatType formatType : NumberFormatType.values()) {

Seems simpler to me, though it might have made the meaning more obscure for the
OP.

I like this way of using enums, but I'd guess that most Java programmers would
see anonymous inner classes as more idiomatic for this example.  More flexible
too, although that is not needed here.

   -- chris


Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.