问:
Is this method pure?
I have the following extension method:

```<code>    public static IEnumerable<T> Apply<T>(
        [NotNull] this IEnumerable<T> source,
        [NotNull] Action<T> action)
        where T : class
    {
        source.CheckArgumentNull("source");
        action.CheckArgumentNull("action");
        return source.ApplyIterator(action);
    }

    private static IEnumerable<T> ApplyIterator<T>(this IEnumerable<T> source, Action<T> action)
        where T : class
    {
        foreach (var item in source)
        {
            action(item);
            yield return item;
        }
    }
</code>```

It just applies an action to each item of the sequence before returning it.

I was wondering if I should apply the Pure attribute (from Resharper annotations) to this method, and I can see arguments for and against it.

Pros:

strictly speaking, it is pure; just calling it on a sequence doesn't alter the sequence (it returns a new sequence) or make any observable state change

calling it without using the result is clearly a mistake, since it has no effect unless the sequence is enumerated, so I'd like Resharper to warn me if I do that.

Cons:

even though the Apply method itself is pure, enumerating the resulting sequence will make observable state changes (which is the point of the method). For instance, items.Apply(i => i.Count++) will change the values of the items every time it's enumerated. So applying the Pure attribute is probably misleading...

What do you think? Should I apply the attribute or not?

答:
No it is not pure, because it has side effect. Concretely it is calling action on each item. Also, it is not threadsafe.

The major property of pure functions is that it can be called any number of times and it never does anything else than return same value. Which is not your case. Also, being pure means you don't use anything else than the input parameters. This means it can be called from any thread at any time and not cause any unexpected behavior. Again, that is not case of your function.

Also, you might be mistaken on one thing: function purity is not question of pros or cons. Even single doubt, that it can have side effect, is enough to make it not pure.

Eric Lippert raises a good point. I'm going to use http://msdn.microsoft.com/en-us/library/dd264808(v=vs.110).aspx as part of my counter-argument. Especially line

A pure method is allowed to modify objects that have been created after entry into the pure method.

Lets say we create method like this:

```<code>int Count<T>(IEnumerable<T> e)
{
    var enumerator = e.GetEnumerator();
    int count = 0;
    while (enumerator.MoveNext()) count ++;
    return count;
}
</code>```

First, this assumes that GetEnumerator is pure too (I can't really find any source on that). If it is, then according to above rule, we can annotate this method with [Pure], because it only modifies instance that was created within the body itself. After that we can compose this and the ApplyIterator, which should result in pure function, right?

```<code>Count(ApplyIterator(source, action));
</code>```

No. This composition is not pure, even when both Count and ApplyIterator are pure. But I might be building this argument on wrong premise. I think that the idea that instances created within the method are exempt from the purity rule is either wrong or at least not specific enough.

Title: Is this method pure?

Body:
No it is not pure, because it has side effect. Concretely it is calling action on each item. Also, it is not threadsafe.

The major property of pure functions is that it can be called any number of times and it never does anything else than return same value. Which is not your case. Also, being pure means you don't use anything else than the input parameters. This means it can be called from any thread at any time and not cause any unexpected behavior. Again, that is not case of your function.

Also, you might be mistaken on one thing: function purity is not question of pros or cons. Even single doubt, that it can have side effect, is enough to make it not pure.

Eric Lippert raises a good point. I'm going to use http://msdn.microsoft.com/en-us/library/dd264808(v=vs.110).aspx as part of my counter-argument. Especially line

A pure method is allowed to modify objects that have been created after entry into the pure method.

Lets say we create method like this:

int Count<T>(IEnumerable<T> e)
{
    var enumerator = e.GetEnumerator();
    int count = 0;
    while (enumerator.MoveNext()) count ++;
    return count;
}

First, this assumes that GetEnumerator is pure too (I can't really find any source on that). If it is, then according to above rule, we can annotate this method with [Pure], because it only modifies instance that was created within the body itself. After that we can compose this and the ApplyIterator, which should result in pure function, right?

Count(ApplyIterator(source, action));

No. This composition is not pure, even when both Count and ApplyIterator are pure. But I might be building this argument on wrong premise. I think that the idea that instances created within the method are exempt from the purity rule is either wrong or at least not specific enough.


答:
It's not a pure function, so applying the Pure attribute is misleading.

Pure functions do not modify the original collection, and it doesn't matter whether you're passing an action that has no effect or not; it's still an impure function because its intent is to cause side effects.

If you want to make the function pure, copy the collection to a new collection, apply the changes that the Action takes to the new collection, and return the new collection, leaving the original collection unchanged.

ContentLicense: CC BY-SA 3.0

Title: Is this method pure?

Body:
I have the following extension method:

```<code>    public static IEnumerable<T> Apply<T>(
        [NotNull] this IEnumerable<T> source,
        [NotNull] Action<T> action)
        where T : class
    {
        source.CheckArgumentNull("source");
        action.CheckArgumentNull("action");
        return source.ApplyIterator(action);
    }

    private static IEnumerable<T> ApplyIterator<T>(this IEnumerable<T> source, Action<T> action)
        where T : class
    {
        foreach (var item in source)
        {
            action(item);
            yield return item;
        }
    }
</code>```

It just applies an action to each item of the sequence before returning it.

I was wondering if I should apply the Pure attribute (from Resharper annotations) to this method, and I can see arguments for and against it.

Pros:

strictly speaking, it is pure; just calling it on a sequence doesn't alter the sequence (it returns a new sequence) or make any observable state change

calling it without using the result is clearly a mistake, since it has no effect unless the sequence is enumerated, so I'd like Resharper to warn me if I do that.

Cons:

even though the Apply method itself is pure, enumerating the resulting sequence will make observable state changes (which is the point of the method). For instance, items.Apply(i => i.Count++) will change the values of the items every time it's enumerated. So applying the Pure attribute is probably misleading...

What do you think? Should I apply the attribute or not?


问:
Understanding UML composition better
The difference between Composition and Aggregation in UML (and sometimes in programming too) is that with Composition, the lifetime of the objects composing the composite (e.g. an engine and a steering wheel in a car) is dependent on the composite object. While with Aggregation, the lifetime of the objects making up the composite is independent of the composite.

However I'm not sure about something related to composition in UML.

Say ClassA is composed of an object of ClassB:

```<code>class ClassA{
    ClassB bInstance;
    public ClassA(){
        bInstance = new ClassB();
    }
}
</code>```

This is an example of composition, because bInstance is dependent on the lifetime of it's enclosing object.

However, regarding UML notation - I'm not sure if I would notate the relationship between ClassA and ClassB with a filled diamond (composition) or a white diamond (aggregation).

This is because while the lifetime of some ClassB instances is dependent of ClassA instances - there could be ClassB instances anywhere else in the program - not only within ClassA instances.

The question is: if some ClassB objects are composed with ClassA objects (and thus are dependent on the lifetime of the ClassA objects), but some are not - would the relationship between the two classes in UML be an aggregation or a composition relationship??

答:
Short answer: UML doesn't care about inner classes. Inner classes is a feature in Java and a few other languages, but not all support them. In fact, Inner classes are usually an implementation detail which is very often not shown in UML diagrams.

Now, If the sample code is Java (but it could be anything else) I would say that it could(1) be  aggregation, or neither... or maybe composition

As an example of aggregation, you could have a collection class, where each item is stored in an inner class. An example of this would be the HashMap.Entry class in Java, but it's static and package protected, as it's used from other classes in java.util.

And as an example of neither would be if you want to have a helper class, but don't want to create a top level class or a anonymous inner class. For example if you want to instantiate a custom Comparator.

Last but not least, it could be an example of bad composition.

(1) I say it could be, because there are plenty of really bad examples or composition and aggregation in most of the codebases I've worked on.

Title: Understanding UML composition better


问:
Question about casting a class in Java with generics
In Java 6

```<code>Class<? extends ArrayList<?>> a = ArrayList.class;
</code>```

gives and error, but

```<code>Class<? extends ArrayList<?>> b = (Class<? extends ArrayList<?>>)ArrayList.class;
</code>```

gives a warning.

Why is (a) an error?  What is it, that Java needs to do in the assignment, if not the cast shown in (b)?

And why isn't ArrayList compatible with ArrayList<?>  I know one is "raw" and the other is "generic", but what is it you can do with an ArrayList<?> and not with an ArrayList, or the other way around?

答:
While it's true that Java's type erasure means that generics are compiled into raw classes, they still mean something at compilation. The whole point of generics is to apply consistent casting at compile time, so it should be no wonder that you can't implicitly cast from Class<ArrayList> to Class<? extends ArrayList<?>> even though they are exactly the same type at runtime.

In other words - you get a compilation error because the whole point of generics in Java is to provide safe implicit "casting" in such cases, and raise a compilation error when there is a generic type mismatch.


问:
What is the most appropriate testing method in this scenario?
I'm writing some Objective-C apps (for OS X/iOS) and I'm currently implementing a service to be shared across them. The service is intended to be fairly self-contained.

For the current functionality I'm envisioning there will be only one method that clients will call to do a fairly complicated series of steps both using private methods on the class, and passing data through a bunch of "data mangling classes" to arrive at an end result.

The gist of the code is to fetch a log of changes, stored in a service-internal data store, that has occurred since a particular time, simplify the log to only include the last applicable change for each object, attach the serialized values for the affected objects and return this all to the client.

My question then is, how do I unit-test this entry point method? Obviously, each class would have thorough unit tests to ensure that their functionality works as expected, but the entry point seems harder to "disconnect" from the rest of the world. I would rather not send in each of these internal classes IoC-style, because they're small and are only made classes to satisfy the single-responsibility principle.

I see a couple possibilities:

Create a "private" interface header for the tests with methods that call the internal classes and test each of these methods separately. Then, to test the entry point, make a partial mock of the service class with these private methods mocked out and just test that the methods are called with the right arguments.

Write a series of fatter tests for the entry point without mocking out anything, testing the entire functionality in one go. This looks, to me, more like "integration testing" and seems brittle, but it does satisfy the "only test via the public interface" principle.

Write a factory that returns these internal services and take that in the initializer, then write a factory that returns mocked versions of them to use in tests. This has the downside of making the construction of the service annoying, and leaks internal details to the client.

Write a "private" initializer that take these services as extra parameters, use that to provide mocked services, and have the public initializer back-end to this one. This would ensure that the client code still sees the easy/pretty initializer and no internals are leaked.

I'm sure there's more ways to solve this problem that I haven't thought of yet, but my question is: what's the most appropriate approach according to unit testing best practices? Especially considering I would prefer to write this test-first, meaning I should preferably only create these services as the code indicates a need for them.

答:
Is there any important logic in your "entry point" method? It sounds like its only job is to instantiate some other classes and wire them together. If that's right then I'd say this is trivial code, it's not business critical, you'd notice immediately if it was broken (generally if you get this sort of 'composition' code wrong it won't even compile), so - I know this seems blasphemous - it doesn't need unit tests. "The best code is no code" also applies to tests: if a test isn't testing something important, difficult, or liable to break without detection, then that test is not worth the effort of writing or maintaining.

If the main method is more than just trivial code (try...catch blocks are common in this sort of method, as are if statements for configuration) then you should probably consider extracting some logic. For example, if you have lots of if statements in your app maybe you could extract a Configuration class which handles arbitrary configurations and can easily be unit tested or extended.


问:
Use unnamed object to invoke method or not?
If I have a class with only only public method. When I use this class, is it good to use unnamed object to invoke its method?

normal:

```<code>TaxFileParser tax_parser(tax_file_name);
auto content = tax_parser.get_content();
</code>```

or unnamed object version:

```<code>auto content = TaxFileParser(tax_file_name).get_content();
</code>```

Because I've told that we should avoid temporary as possible. If tax_parser object is used only once, can I call it a temporary and try to eliminate it?

Any suggestion will be helpful.

答:
Temporary variables are even worse than temporary unnamed values. To use a temporary variable, you have to come up with a name for it and everybody reading the code has to read that name, remember what it means and check it's extent.

There are good reasons to implement functionality by a class. But if it only has one method that is only called once on an instance, the class is an implementation detail. The public API should be a function like:

```<code>whatever_t parse_tax(string const &tax_file_name) {
    return TaxFileParser(tax_file_name).get_content();
}
</code>```

C++ is multi-paradigmatic langue. It does not require everything to be in a class. So only put things in them if it has actual meaning.

Body:
Temporary variables are even worse than temporary unnamed values. To use a temporary variable, you have to come up with a name for it and everybody reading the code has to read that name, remember what it means and check it's extent.

There are good reasons to implement functionality by a class. But if it only has one method that is only called once on an instance, the class is an implementation detail. The public API should be a function like:

whatever_t parse_tax(string const &tax_file_name) {
    return TaxFileParser(tax_file_name).get_content();
}

C++ is multi-paradigmatic langue. It does not require everything to be in a class. So only put things in them if it has actual meaning.


问:
Why should main() be short?
I've been programming for over 9 years, and according to the advice of my first programming teacher, I always keep my main() function extremely short.

At first I had no idea why. I just obeyed without understanding, much to the delight of my professors.

After gaining experience, I realized that if I designed my code correctly, having a short main() function just sortof happened. Writing modularized code and following the single responsibility principle allowed my code to be designed in "bunches", and main() served as nothing more than a catalyst to get the program running.

Fast forward to a few weeks ago, I was looking at Python's souce code, and I found the main() function:

```<code>/* Minimal main program -- everything is loaded from the library */

...

int
main(int argc, char **argv)
{
    ...
    return Py_Main(argc, argv);
}
</code>```

Yay python. Short main() function == Good code.

Programming teachers were right.

Wanting to look deeper, I took a look at Py_Main. In its entirety, it is defined as follows:

```<code>/* Main program */

int
Py_Main(int argc, char **argv)
{
    int c;
    int sts;
    char *command = NULL;
    char *filename = NULL;
    char *module = NULL;
    FILE *fp = stdin;
    char *p;
    int unbuffered = 0;
    int skipfirstline = 0;
    int stdin_is_interactive = 0;
    int help = 0;
    int version = 0;
    int saw_unbuffered_flag = 0;
    PyCompilerFlags cf;

    cf.cf_flags = 0;

    orig_argc = argc;           /* For Py_GetArgcArgv() */
    orig_argv = argv;

#ifdef RISCOS
    Py_RISCOSWimpFlag = 0;
#endif

    PySys_ResetWarnOptions();

    while ((c = _PyOS_GetOpt(argc, argv, PROGRAM_OPTS)) != EOF) {
        if (c == 'c') {
            /* -c is the last option; following arguments
               that look like options are left for the
               command to interpret. */
            command = (char *)malloc(strlen(_PyOS_optarg) + 2);
            if (command == NULL)
                Py_FatalError(
                   "not enough memory to copy -c argument");
            strcpy(command, _PyOS_optarg);
            strcat(command, "\n");
            break;
        }

        if (c == 'm') {
            /* -m is the last option; following arguments
               that look like options are left for the
               module to interpret. */
            module = (char *)malloc(strlen(_PyOS_optarg) + 2);
            if (module == NULL)
                Py_FatalError(
                   "not enough memory to copy -m argument");
            strcpy(module, _PyOS_optarg);
            break;
        }

        switch (c) {
        case 'b':
            Py_BytesWarningFlag++;
            break;

        case 'd':
            Py_DebugFlag++;
            break;

        case '3':
            Py_Py3kWarningFlag++;
            if (!Py_DivisionWarningFlag)
                Py_DivisionWarningFlag = 1;
            break;

        case 'Q':
            if (strcmp(_PyOS_optarg, "old") == 0) {
                Py_DivisionWarningFlag = 0;
                break;
            }
            if (strcmp(_PyOS_optarg, "warn") == 0) {
                Py_DivisionWarningFlag = 1;
                break;
            }
            if (strcmp(_PyOS_optarg, "warnall") == 0) {
                Py_DivisionWarningFlag = 2;
                break;
            }
            if (strcmp(_PyOS_optarg, "new") == 0) {
                /* This only affects __main__ */
                cf.cf_flags |= CO_FUTURE_DIVISION;
                /* And this tells the eval loop to treat
                   BINARY_DIVIDE as BINARY_TRUE_DIVIDE */
                _Py_QnewFlag = 1;
                break;
            }
            fprintf(stderr,
                "-Q option should be `-Qold', "
                "`-Qwarn', `-Qwarnall', or `-Qnew' only\n");
            return usage(2, argv[0]);
            /* NOTREACHED */

        case 'i':
            Py_InspectFlag++;
            Py_InteractiveFlag++;
            break;

        /* case 'J': reserved for Jython */

        case 'O':
            Py_OptimizeFlag++;
            break;

        case 'B':
            Py_DontWriteBytecodeFlag++;
            break;

        case 's':
            Py_NoUserSiteDirectory++;
            break;

        case 'S':
            Py_NoSiteFlag++;
            break;

        case 'E':
            Py_IgnoreEnvironmentFlag++;
            break;

        case 't':
            Py_TabcheckFlag++;
            break;

        case 'u':
            unbuffered++;
            saw_unbuffered_flag = 1;
            break;

        case 'v':
            Py_VerboseFlag++;
            break;

#ifdef RISCOS
        case 'w':
            Py_RISCOSWimpFlag = 1;
            break;
#endif

        case 'x':
            skipfirstline = 1;
            break;

        /* case 'X': reserved for implementation-specific arguments */

        case 'U':
            Py_UnicodeFlag++;
            break;
        case 'h':
        case '?':
            help++;
            break;
        case 'V':
            version++;
            break;

        case 'W':
            PySys_AddWarnOption(_PyOS_optarg);
            break;

        /* This space reserved for other options */

        default:
            return usage(2, argv[0]);
            /*NOTREACHED*/

        }
    }

    if (help)
        return usage(0, argv[0]);

    if (version) {
        fprintf(stderr, "Python %s\n", PY_VERSION);
        return 0;
    }

    if (Py_Py3kWarningFlag && !Py_TabcheckFlag)
        /* -3 implies -t (but not -tt) */
        Py_TabcheckFlag = 1;

    if (!Py_InspectFlag &&
        (p = Py_GETENV("PYTHONINSPECT")) && *p != '\0')
        Py_InspectFlag = 1;
    if (!saw_unbuffered_flag &&
        (p = Py_GETENV("PYTHONUNBUFFERED")) && *p != '\0')
        unbuffered = 1;

    if (!Py_NoUserSiteDirectory &&
        (p = Py_GETENV("PYTHONNOUSERSITE")) && *p != '\0')
        Py_NoUserSiteDirectory = 1;

    if ((p = Py_GETENV("PYTHONWARNINGS")) && *p != '\0') {
        char *buf, *warning;

        buf = (char *)malloc(strlen(p) + 1);
        if (buf == NULL)
            Py_FatalError(
               "not enough memory to copy PYTHONWARNINGS");
        strcpy(buf, p);
        for (warning = strtok(buf, ",");
             warning != NULL;
             warning = strtok(NULL, ","))
            PySys_AddWarnOption(warning);
        free(buf);
    }

    if (command == NULL && module == NULL && _PyOS_optind < argc &&
        strcmp(argv[_PyOS_optind], "-") != 0)
    {
#ifdef __VMS
        filename = decc$translate_vms(argv[_PyOS_optind]);
        if (filename == (char *)0 || filename == (char *)-1)
            filename = argv[_PyOS_optind];

#else
        filename = argv[_PyOS_optind];
#endif
    }

    stdin_is_interactive = Py_FdIsInteractive(stdin, (char *)0);

    if (unbuffered) {
#if defined(MS_WINDOWS) || defined(__CYGWIN__)
        _setmode(fileno(stdin), O_BINARY);
        _setmode(fileno(stdout), O_BINARY);
#endif
#ifdef HAVE_SETVBUF
        setvbuf(stdin,  (char *)NULL, _IONBF, BUFSIZ);
        setvbuf(stdout, (char *)NULL, _IONBF, BUFSIZ);
        setvbuf(stderr, (char *)NULL, _IONBF, BUFSIZ);
#else /* !HAVE_SETVBUF */
        setbuf(stdin,  (char *)NULL);
        setbuf(stdout, (char *)NULL);
        setbuf(stderr, (char *)NULL);
#endif /* !HAVE_SETVBUF */
    }
    else if (Py_InteractiveFlag) {
#ifdef MS_WINDOWS
        /* Doesn't have to have line-buffered -- use unbuffered */
        /* Any set[v]buf(stdin, ...) screws up Tkinter :-( */
        setvbuf(stdout, (char *)NULL, _IONBF, BUFSIZ);
#else /* !MS_WINDOWS */
#ifdef HAVE_SETVBUF
        setvbuf(stdin,  (char *)NULL, _IOLBF, BUFSIZ);
        setvbuf(stdout, (char *)NULL, _IOLBF, BUFSIZ);
#endif /* HAVE_SETVBUF */
#endif /* !MS_WINDOWS */
        /* Leave stderr alone - it should be unbuffered anyway. */
    }
#ifdef __VMS
    else {
        setvbuf (stdout, (char *)NULL, _IOLBF, BUFSIZ);
    }
#endif /* __VMS */

#ifdef __APPLE__
    /* On MacOS X, when the Python interpreter is embedded in an
       application bundle, it gets executed by a bootstrapping script
       that does os.execve() with an argv[0] that's different from the
       actual Python executable. This is needed to keep the Finder happy,
       or rather, to work around Apple's overly strict requirements of
       the process name. However, we still need a usable sys.executable,
       so the actual executable path is passed in an environment variable.
       See Lib/plat-mac/bundlebuiler.py for details about the bootstrap
       script. */
    if ((p = Py_GETENV("PYTHONEXECUTABLE")) && *p != '\0')
        Py_SetProgramName(p);
    else
        Py_SetProgramName(argv[0]);
#else
    Py_SetProgramName(argv[0]);
#endif
    Py_Initialize();

    if (Py_VerboseFlag ||
        (command == NULL && filename == NULL && module == NULL && stdin_is_interactive)) {
        fprintf(stderr, "Python %s on %s\n",
            Py_GetVersion(), Py_GetPlatform());
        if (!Py_NoSiteFlag)
            fprintf(stderr, "%s\n", COPYRIGHT);
    }

    if (command != NULL) {
        /* Backup _PyOS_optind and force sys.argv[0] = '-c' */
        _PyOS_optind--;
        argv[_PyOS_optind] = "-c";
    }

    if (module != NULL) {
        /* Backup _PyOS_optind and force sys.argv[0] = '-c'
           so that PySys_SetArgv correctly sets sys.path[0] to ''
           rather than looking for a file called "-m". See
           tracker issue #8202 for details. */
        _PyOS_optind--;
        argv[_PyOS_optind] = "-c";
    }

    PySys_SetArgv(argc-_PyOS_optind, argv+_PyOS_optind);

    if ((Py_InspectFlag || (command == NULL && filename == NULL && module == NULL)) &&
        isatty(fileno(stdin))) {
        PyObject *v;
        v = PyImport_ImportModule("readline");
        if (v == NULL)
            PyErr_Clear();
        else
            Py_DECREF(v);
    }

    if (command) {
        sts = PyRun_SimpleStringFlags(command, &cf) != 0;
        free(command);
    } else if (module) {
        sts = RunModule(module, 1);
        free(module);
    }
    else {

        if (filename == NULL && stdin_is_interactive) {
            Py_InspectFlag = 0; /* do exit on SystemExit */
            RunStartupFile(&cf);
        }
        /* XXX */

        sts = -1;               /* keep track of whether we've already run __main__ */

        if (filename != NULL) {
            sts = RunMainFromImporter(filename);
        }

        if (sts==-1 && filename!=NULL) {
            if ((fp = fopen(filename, "r")) == NULL) {
                fprintf(stderr, "%s: can't open file '%s': [Errno %d] %s\n",
                    argv[0], filename, errno, strerror(errno));

                return 2;
            }
            else if (skipfirstline) {
                int ch;
                /* Push back first newline so line numbers
                   remain the same */
                while ((ch = getc(fp)) != EOF) {
                    if (ch == '\n') {
                        (void)ungetc(ch, fp);
                        break;
                    }
                }
            }
            {
                /* XXX: does this work on Win/Win64? (see posix_fstat) */
                struct stat sb;
                if (fstat(fileno(fp), &sb) == 0 &&
                    S_ISDIR(sb.st_mode)) {
                    fprintf(stderr, "%s: '%s' is a directory, cannot continue\n", argv[0], filename);
                    fclose(fp);
                    return 1;
                }
            }
        }

        if (sts==-1) {
            /* call pending calls like signal handlers (SIGINT) */
            if (Py_MakePendingCalls() == -1) {
                PyErr_Print();
                sts = 1;
            } else {
                sts = PyRun_AnyFileExFlags(
                    fp,
                    filename == NULL ? "<stdin>" : filename,
                    filename != NULL, &cf) != 0;
            }
        }

    }

    /* Check this environment variable at the end, to give programs the
     * opportunity to set it from Python.
     */
    if (!Py_InspectFlag &&
        (p = Py_GETENV("PYTHONINSPECT")) && *p != '\0')
    {
        Py_InspectFlag = 1;
    }

    if (Py_InspectFlag && stdin_is_interactive &&
        (filename != NULL || command != NULL || module != NULL)) {
        Py_InspectFlag = 0;
        /* XXX */
        sts = PyRun_AnyFileFlags(stdin, "<stdin>", &cf) != 0;
    }

    Py_Finalize();
#ifdef RISCOS
    if (Py_RISCOSWimpFlag)
        fprintf(stderr, "\x0cq\x0c"); /* make frontend quit */
#endif

#ifdef __INSURE__
    /* Insure++ is a memory analysis tool that aids in discovering
     * memory leaks and other memory problems.  On Python exit, the
     * interned string dictionary is flagged as being in use at exit
     * (which it is).  Under normal circumstances, this is fine because
     * the memory will be automatically reclaimed by the system.  Under
     * memory debugging, it's a huge source of useless noise, so we
     * trade off slower shutdown for less distraction in the memory
     * reports.  -baw
     */
    _Py_ReleaseInternedStrings();
#endif /* __INSURE__ */

    return sts;
}
</code>```

Good God Almighty...it is big enough to sink the Titanic.

It seems as though Python did the "Intro to Programming 101" trick and just moved all of main()'s code to a different function called it something very similar to "main".

Here's my question: Is this code terribly written, or are there other reasons to have a short main function?

As it stands right now, I see absolutely no difference between doing this and just moving the code in Py_Main() back into main(). Am I wrong in thinking this?

答:
Do not assume that just because a bit of software is good all of the code behind that software is good. Good software and good code are not the same thing and even where good software is backed by good code, it is inevitable that in a large project there will be places where standards slip.

It is good practice to have a shortmainfunction, but that is really just a special case of the general rule that it is better to have short functions. Short functions are easier to understand and easier to debug as well as being better at sticking to the kind of 'single purpose' design that makes programs more expressive. main is, perhaps, a more important place to stick to the rule since anyone who wants to understand the program must understand main while more obscure corners of the codebase may be visited less often.

But, the Python codebase isn't pushing the code out toPy_Mainin order to game this rule but because you cannot exportmainfrom a library nor call it as a function.

Title: Why should main() be short?


答:
I believe you answered your question when you said "the lifetime of the objects composing the composite (e.g. an engine and a steering wheel in a car) is dependent on the composite object." In your code example, Object B would cease to exist when Object A is gone.
On the other hand,

```<code>class ClassA{
   ClassB bInstance;
  public ClassA(ClassB classB){
    bInstance = classB;
  }
}
</code>```

would become an aggregate in your UML since object B can exist independently from object A.

EDIT (after your update )
I tried to imagine an instance where Class B would depend on Class A and here's what I come up with:

```<code>class ClassA{
   bool bDependsOnA = // true or false based on some logic
   ClassB bInstance;
   public ClassA(){
     if(bDependsOnA){
        bInstance = new ClassB(this);
      }else{
        bInstance = new ClassB();
    }
  }
}

class ClassB{
   ClassA aInstance;
  public ClassB()
  {
     aInstance = null;
  }
  public ClassB(ClassA classA ){
    aInstance = classA;
  }
}
</code>```

Class B is a composite of class A, ClassB has a weak association with Class A. An interesting article I found, while thinking about your question (http://aviadezra.blogspot.ca/2009/05/uml-association-aggregation-composition.html)

By the way, as great as UML is, it's not perfect. Aggregation vs composition been going on for a long time. Sometimes, it's not clear what is what. Personally, I've found that when I'm stuck trying to decide which is which, it means my design is way too complex and could be simplified :)

Title: Understanding UML composition better

Body:
The difference between Composition and Aggregation in UML (and sometimes in programming too) is that with Composition, the lifetime of the objects composing the composite (e.g. an engine and a steering wheel in a car) is dependent on the composite object. While with Aggregation, the lifetime of the objects making up the composite is independent of the composite.

However I'm not sure about something related to composition in UML.

Say ClassA is composed of an object of ClassB:

```<code>class ClassA{
    ClassB bInstance;
    public ClassA(){
        bInstance = new ClassB();
    }
}
</code>```

This is an example of composition, because bInstance is dependent on the lifetime of it's enclosing object.

However, regarding UML notation - I'm not sure if I would notate the relationship between ClassA and ClassB with a filled diamond (composition) or a white diamond (aggregation).

This is because while the lifetime of some ClassB instances is dependent of ClassA instances - there could be ClassB instances anywhere else in the program - not only within ClassA instances.

The question is: if some ClassB objects are composed with ClassA objects (and thus are dependent on the lifetime of the ClassA objects), but some are not - would the relationship between the two classes in UML be an aggregation or a composition relationship??

Body:
I believe you answered your question when you said "the lifetime of the objects composing the composite (e.g. an engine and a steering wheel in a car) is dependent on the composite object." In your code example, Object B would cease to exist when Object A is gone.
On the other hand,

class ClassA{
   ClassB bInstance;
  public ClassA(ClassB classB){
    bInstance = classB;
  }
}

would become an aggregate in your UML since object B can exist independently from object A.

EDIT (after your update )
I tried to imagine an instance where Class B would depend on Class A and here's what I come up with:

class ClassA{
   bool bDependsOnA = // true or false based on some logic
   ClassB bInstance;
   public ClassA(){
     if(bDependsOnA){
        bInstance = new ClassB(this);
      }else{
        bInstance = new ClassB();
    }
  }
}

class ClassB{
   ClassA aInstance;
  public ClassB()
  {
     aInstance = null;
  }
  public ClassB(ClassA classA ){
    aInstance = classA;
  }
}

Class B is a composite of class A, ClassB has a weak association with Class A. An interesting article I found, while thinking about your question (http://aviadezra.blogspot.ca/2009/05/uml-association-aggregation-composition.html)

By the way, as great as UML is, it's not perfect. Aggregation vs composition been going on for a long time. Sometimes, it's not clear what is what. Personally, I've found that when I'm stuck trying to decide which is which, it means my design is way too complex and could be simplified :)


问:
Algorithm for detecting windows in a room

I am dealing with the following problem and i was looking to write a Pseudo-code for developing an algorithm that can be generic for such a problem.

Here is what i have come up with thus far.

STEP 1

In this step i try to get the robot where it maybe placed to the top left corner.

```<code>Turn Left -> If no window or Wall detected keep going forward 1 unit..

if window or wall detected ->Turn right --> if no window or Wall detected keep going forward..

if window or wall detected then top left corner is reached.
</code>```

STEP 2 (We start counting windows after we get to this stage to avoid miscounting)

I would like to declare a variable called turns as it will help me keep track if robot has gone around entire room.

```<code>Turns = 4;
</code>```

Now we are facing north and placed on top left corner.

```<code>while(turns>0){

If window or wall detected (if window count++)

Turn Right

Turn--;

While(detection!=wall || detection!=window){

move 1 unit forward

Turn left (if window count++)

Turn right

}

}
</code>```

I believe in doing so the robot will go around the entire room and count windows and it will stop once it has gone around the entire room as the turns get decremented. I don't feel this is the best solution and would appreciate suggestions on how i can improve my Pseudo-code. I am not looking for any code just a algorithm on solving such a problem and that is why i have not posted this in stack overflow. I apologize if my Pseudo-code is poorly written please make suggestions if i can improve that as i am new to this. Thanks.

答:
You need to find the top left corner. Instead, move forward (no matter the current orientation of the robot) until you hit the wall, then turn right. Those are the steps 1 and 2 in the illustration below. At the step 2, the robot turns right, orienting itself to the top.

The second phase is to move forward, constantly turning left to see whether you're near a wall or a window. For example, at step 6, the robot will turn to be oriented to the left, see that it's a wall, and turn back to be able to move to the top. At step 7, the robot turns left, sees that it's near a wall, and can now turn right twice, since it knows that there is also a wall at the top of it. It performs a similar operation at step 16, 23 and 32.

At step 9, it records that it's near a window. At step 10, he knows that it previously had a window at the top of it, so there is no need to count a different window.

The approach supposes that:

The room is rectangular. Having a non-rectangular room would require a slightly more complicated approach.

There is no walls or windows inside the room itself, i.e. in the middle of the room. Having walls or windows inside a room would require an overly-complex approach where the robot should scan nearly the whole surface.

The robot knows that it has already visited a given cell. If it doesn't know that, it should be at least able to know the size of the room.

The algorithm may further be improved, for example by handling the case where the robot touches the wall in its initial position, but I suppose such optimizations are outside the scope of the exercise.


问:
Is it normal needing time to understand code I wrote recently
By recently I mean some weeks ago. I am trying to continue a project I left 2 weeks ago and I need time to understand some functions I wrote (not copied from somewhere) and it takes me time. Normally I don't need to because my functions, methods etc. are black boxes but when I need to change something it's really hard. Does this mean I write bad code? I am still in school and I am the only who writes/uses the code so I don't have feedback, but I am afraid that if it is difficult for me to understand it, it would be 10 times more difficult for someone else. What should I do? I write a lot of comments but most of the time are useless when reviewing.

Do you have any suggestions?

答:
It's "normal" for some definition of normal, but it's also something you should seek to improve.

I define my progress as a good programmer in terms of exactly that: how easily I understand my code when I look at it later ... and to some extent, how much I apologize in comments to my future self because I know it will be hard to understand (legacy code is sad).

Usually I write very few comments in code I write, since I believe that the code should be fairly obvious. The few comments I do write are to help the understanding of myself or anyone else who looks at the codebase (though that latter is not nearly as important as the first; anyone new will need a long time to become as intimate with the codebase as you are).

As an immediate path forward, I suggest that you delete all comments in that codebase, and then add comments until you understand, then look at how your new comments compare to your old ones.


答:
Working on thing without other developer feedback can be really hard.  Feedback helps us learn and grow much quicker.  I work for a very small company, there are two of us, typically working on separate segments of projects, UI vs. back-end calculation logic.  The internet provides lots of information, but this has to be broken down into applied knowledge, and the transition can be tough.  Hence, sites like this are great for you and I.

The complexity of the code you write can be reduced.  There are several ways to do this.  One is by trying to break complex functions down into smaller functions.  Try to use method names that describe clearly what the method is doing.  For example, instead of a method named CalcMatDen, name it CalculateMaterialDensity.  If you do this, one large function will suddenly become a series of calls to smaller more focused functions.  Now when reading the code you can easily see what a large function does, and you can go directly to the level of complexity you care about...

Another thing you can do is write a method that returns a bool to replace complex if statements.

Instead of:

```<code> if (depth > wellSurveyDepth &&
      depth > wellGeometryDepth &&
      depth > wellTemperatures)
</code>```

Try writing a method so you can do something like this:

```<code>if (DepthExceedsWellDepths(depth))
</code>```

If you have access to Pluralsight there is a great course called Clean Code: Writing Code for Humans by Corey House.   Also the book Clean Code by Robert C. Martin may help.  On a side note, writing Unit Tests can be very helpful when working toward writing more maintainable code.

Title: Is it normal needing time to understand code I wrote recently

Body:
By recently I mean some weeks ago. I am trying to continue a project I left 2 weeks ago and I need time to understand some functions I wrote (not copied from somewhere) and it takes me time. Normally I don't need to because my functions, methods etc. are black boxes but when I need to change something it's really hard. Does this mean I write bad code? I am still in school and I am the only who writes/uses the code so I don't have feedback, but I am afraid that if it is difficult for me to understand it, it would be 10 times more difficult for someone else. What should I do? I write a lot of comments but most of the time are useless when reviewing.

Do you have any suggestions?

Body:
Working on thing without other developer feedback can be really hard.  Feedback helps us learn and grow much quicker.  I work for a very small company, there are two of us, typically working on separate segments of projects, UI vs. back-end calculation logic.  The internet provides lots of information, but this has to be broken down into applied knowledge, and the transition can be tough.  Hence, sites like this are great for you and I.

The complexity of the code you write can be reduced.  There are several ways to do this.  One is by trying to break complex functions down into smaller functions.  Try to use method names that describe clearly what the method is doing.  For example, instead of a method named CalcMatDen, name it CalculateMaterialDensity.  If you do this, one large function will suddenly become a series of calls to smaller more focused functions.  Now when reading the code you can easily see what a large function does, and you can go directly to the level of complexity you care about...

Another thing you can do is write a method that returns a bool to replace complex if statements.

Instead of:

 if (depth > wellSurveyDepth &&
      depth > wellGeometryDepth &&
      depth > wellTemperatures)

Try writing a method so you can do something like this:

if (DepthExceedsWellDepths(depth))

If you have access to Pluralsight there is a great course called Clean Code: Writing Code for Humans by Corey House.   Also the book Clean Code by Robert C. Martin may help.  On a side note, writing Unit Tests can be very helpful when working toward writing more maintainable code.


答:
It is normal, but there are proven counter-measures.

Train yourself to document all your non-throwaway code as if
you were publishing it for other skilled programmers (but not for dummies).
Do it as you write the code, part of the process; review it as you change
the code. You will be pretty much another programmer when you've left it alone
for, say, your summer holiday.

When you form a habit of this, it doesn't feel like a drag.

Documenting your code is a key weapon of design, problem-solving
and bug-detecting. When you can't code it right, stop trying and
document it first. If the code smells, document it and you will probably see
where the smell comes from.

Then progress to documenting it first anyway.

Write code that is sufficiently well designed and modularized that the documentation
of the interfaces is almost all the documentation you need to write:
functions, templates, classes, methods; parameters and return values;
pre-conditions and post-conditions; exceptions.

You want the implementation of an interface to be surveyable in one "eyeful" and "obvious" to
skilled programmers. If you find the need to explain an implemention
by a running commentary of comments, then the design and/or the implementation
is bad. Smart-ass implementations always need explanation and are rarely worthwhile.

If you have some code you have written that you struggle to understand every time you need
to maintain it, consider that a bug that needs fixed, and fix it at least by the
Fixes Before Features principle.


答:
Sometimes it is unavoidable but readability is one of the most important factors in the maintainability of a code base.  You can get away with code that only you understand on tiny projects with tiny teams, but that doesn't scale well at all.  Think high level, what does the code need to achieve? It needs to work and it needs to be maintainable(except for some rare cases).

Some things to consider...

If you have trouble reading your code a few days later, how are other team members going to be able to read it?

When someone has to make changes to that code 6 months later will the original author's intent be clear? If not, how can one be sure that any changes won't have unintended consequences that cascade throughout the whole system?(tests help mitigate this)

Well written code should prioritize readability(and resulting maintainability) over finding that neat one-line ultra-concise solution to a problem, which no-one except yourself will understand.

The vast majority of the code shouldn't need comments.  The code IS the comments.  Developers read/write code, so they shouldn't need them IF the code was written well (except for areas where complexity is unavoidable)

We as developers have limited resources in terms of our focus and brain power.  Comments frequently serve as noise and can be problematic due to the ambiguous nature of many technical terms and how people understand them.

Leverage peer review.  Before you check that code in, have another developer give it a once-over and see if they understand it.  In practice it takes a lot of discipline to do this all the time, so often its best to adopt this as a team policy.

Now most of this may not appear to be applicable since you are still in school and all too often developing code for a course in no way resembles how things work in the real world; but you can still apply many of these concepts... e.g. use your professor to do peer review(his opinion is the only thing that matters in the end anyway right?)


问:
Should I always encapsulate an internal data structure entirely?
Please consider this class:

```<code>class ClassA{

    private Thing[] things; // stores data

    // stuff omitted

    public Thing[] getThings(){
        return things;
    }

}
</code>```

This class exposes the array it uses to store data, to any client code interested.

I did this in an app I'm working on. I had a ChordProgression class that stores a sequence of Chords (and does some other things). It had a Chord[] getChords() method that returned the array of chords. When the data structure had to change (from an array to an ArrayList), all client code broke.

This made me think - maybe the following approach is better:

```<code>class ClassA{

    private Thing[] things; // stores data

    // stuff omitted

    public Thing[] getThing(int index){
        return things[index];
    }

    public int getDataSize(){
        return things.length;
    }

    public void setThing(int index, Thing thing){
        things[index] = thing;
    }

}
</code>```

Instead of exposing the data structure itself, all of the operations offered by the data structure are now offered directly by the class enclosing it, using public methods that delegate to the data structure.

When the data structure changes, only these methods have to change - but after they do, all client code still works.

Note that collections more complex than arrays might require the enclosing class to implement even more than three methods just to access the internal data structure.

Is this approach common? What do you think of this? What downsides does it have other? Is it reasonable to have the enclosing class implement at least three public methods just to delegate to the inner data structure?

答:
Code like:

```<code>   public Thing[] getThings(){
        return things;
    }
</code>```

Doesn't make much sense, since your access method is doing nothing but directly returning the internal data structure. You might as well just declare Thing[] things to be public. The idea behind an access method is to create an interface that insulates clients from internal changes and precludes them from manipulating the actual data structure except in discreet ways as allowed by the interface. As you discovered when all your client code broke, your access method didn't do that - it's just wasted code. I think a lot of programmers tend to write code like that because they learned somewhere that everything needs to be encapsulated with access methods - but that's for the reasons I explained. Doing it just to "follow form" when the access method isn't serving any purpose is just noise.

I would definitely recommend your proposed solution, which accomplishes some of the most important goals of encapsulation: Giving clients a robust, discreet interface that insulates them from the internal implementation details of your class, and doesn't allow them to touch the internal data structure expect in the ways that you decide are appropriate - "the law of least necessary privilege". If you look at the big popular OOP frameworks, such as the CLR, the STL, the VCL, the pattern you've proposed is widespread, for exactly that reason.

Should you always do that? Not necessarily. For example, if you have helper or friend classes that are essentially a component of your main worker class and are not "front facing", it's not necessary -  it's an overkill that's going to add a lot of unnecessary code. And in that case, I wouldn't use an access method at all - it's senseless, as explained. Just declare the data structure in a way that's scoped only to the main class that uses it - most languages support ways of doing that - friend, or declaring it in the same file as the main worker class, etc.

The only downside I can see in your proposal it that it's more work to code (and now you're going to have to re-code your consumer classes - but you have/had to do that anyway.) But that's not really a downside - you need to do it right, and sometimes that takes more work.

One of the things that makes a good programmer good is that they know when the extra work is worth it, and when it isn't. In the long run putting in the extra now will pay off with big dividends in the future - if not on this project, then on others. Learn to code the right way and use your head about it, not just robotically follow prescribed forms.

Note that collections more complex than arrays might require the
  enclosing class to implement even more than three methods just to
  access the internal data structure.

If you're exposing an entire data structure through a containing class, IMO you need to think about why that class is encapsulated at all, if it's not simply to provide a safer interface - a "wrapper class". You're saying the containing class does not exist for that purpose - so perhaps there's something not right about your design. Consider breaking up your classes into more discreet modules and layering them.

A class should have one clear and discreet purpose, and provide an interface to support that functionality - no more. You may be trying to bundle things together that don't belong together. When you do that, things will be breaking every time you have to implement a change. The smaller and more discreet your classes are, the easier it is to change things around: Think LEGO.

Body:
Code like:

   public Thing[] getThings(){
        return things;
    }

Doesn't make much sense, since your access method is doing nothing but directly returning the internal data structure. You might as well just declare Thing[] things to be public. The idea behind an access method is to create an interface that insulates clients from internal changes and precludes them from manipulating the actual data structure except in discreet ways as allowed by the interface. As you discovered when all your client code broke, your access method didn't do that - it's just wasted code. I think a lot of programmers tend to write code like that because they learned somewhere that everything needs to be encapsulated with access methods - but that's for the reasons I explained. Doing it just to "follow form" when the access method isn't serving any purpose is just noise.

I would definitely recommend your proposed solution, which accomplishes some of the most important goals of encapsulation: Giving clients a robust, discreet interface that insulates them from the internal implementation details of your class, and doesn't allow them to touch the internal data structure expect in the ways that you decide are appropriate - "the law of least necessary privilege". If you look at the big popular OOP frameworks, such as the CLR, the STL, the VCL, the pattern you've proposed is widespread, for exactly that reason.

Should you always do that? Not necessarily. For example, if you have helper or friend classes that are essentially a component of your main worker class and are not "front facing", it's not necessary -  it's an overkill that's going to add a lot of unnecessary code. And in that case, I wouldn't use an access method at all - it's senseless, as explained. Just declare the data structure in a way that's scoped only to the main class that uses it - most languages support ways of doing that - friend, or declaring it in the same file as the main worker class, etc.

The only downside I can see in your proposal it that it's more work to code (and now you're going to have to re-code your consumer classes - but you have/had to do that anyway.) But that's not really a downside - you need to do it right, and sometimes that takes more work.

One of the things that makes a good programmer good is that they know when the extra work is worth it, and when it isn't. In the long run putting in the extra now will pay off with big dividends in the future - if not on this project, then on others. Learn to code the right way and use your head about it, not just robotically follow prescribed forms.

Note that collections more complex than arrays might require the
  enclosing class to implement even more than three methods just to
  access the internal data structure.

If you're exposing an entire data structure through a containing class, IMO you need to think about why that class is encapsulated at all, if it's not simply to provide a safer interface - a "wrapper class". You're saying the containing class does not exist for that purpose - so perhaps there's something not right about your design. Consider breaking up your classes into more discreet modules and layering them.

A class should have one clear and discreet purpose, and provide an interface to support that functionality - no more. You may be trying to bundle things together that don't belong together. When you do that, things will be breaking every time you have to implement a change. The smaller and more discreet your classes are, the easier it is to change things around: Think LEGO.


答:
You should use interfaces for those things. Wouldn't help in your case, since Java's array don't implement those interfaces, but you should do it from now on:

```<code>class ClassA{

    public ClassA(){
        things = new ArrayList<Thing>();
    }

    private List<Thing> things; // stores data

    // stuff omitted

    public List<Thing> getThings(){
        return things;
    }

}
</code>```

That way you can change ArrayList to LinkedList or anything else, and you won't break any code since all Java collections(beside arrays) that have (pseudo?) random access will probably implement List.

You can also use Collection, that offer less methods than List but can support collections without random access, or Iterable that can even support streams but doesn't offer much in term of access methods...

Title: Should I always encapsulate an internal data structure entirely?

Body:
Please consider this class:

```<code>class ClassA{

    private Thing[] things; // stores data

    // stuff omitted

    public Thing[] getThings(){
        return things;
    }

}
</code>```

This class exposes the array it uses to store data, to any client code interested.

I did this in an app I'm working on. I had a ChordProgression class that stores a sequence of Chords (and does some other things). It had a Chord[] getChords() method that returned the array of chords. When the data structure had to change (from an array to an ArrayList), all client code broke.

This made me think - maybe the following approach is better:

```<code>class ClassA{

    private Thing[] things; // stores data

    // stuff omitted

    public Thing[] getThing(int index){
        return things[index];
    }

    public int getDataSize(){
        return things.length;
    }

    public void setThing(int index, Thing thing){
        things[index] = thing;
    }

}
</code>```

Instead of exposing the data structure itself, all of the operations offered by the data structure are now offered directly by the class enclosing it, using public methods that delegate to the data structure.

When the data structure changes, only these methods have to change - but after they do, all client code still works.

Note that collections more complex than arrays might require the enclosing class to implement even more than three methods just to access the internal data structure.

Is this approach common? What do you think of this? What downsides does it have other? Is it reasonable to have the enclosing class implement at least three public methods just to delegate to the inner data structure?

Body:
You should use interfaces for those things. Wouldn't help in your case, since Java's array don't implement those interfaces, but you should do it from now on:

class ClassA{

    public ClassA(){
        things = new ArrayList<Thing>();
    }

    private List<Thing> things; // stores data

    // stuff omitted

    public List<Thing> getThings(){
        return things;
    }

}

That way you can change ArrayList to LinkedList or anything else, and you won't break any code since all Java collections(beside arrays) that have (pseudo?) random access will probably implement List.

You can also use Collection, that offer less methods than List but can support collections without random access, or Iterable that can even support streams but doesn't offer much in term of access methods...


答:
Instead of returning the raw data directly, try something like this

```<code>class ClassA {
  private Things[] things;
  ...
  public Things[] asArray() { return things; }
  public List<Thing> asList() { ... }
  ...
}
</code>```

So, you are essentially providing a custom collection that presents whatever face to the world is desired. In your new implementation then,

```<code>class ClassA {
  private List<Thing> things;
  ...
  public Things[] asArray() { return things.asArray(); }
  public List<Thing> asList() { return things; }
  ...
}
</code>```

Now you have the proper encapsulation, hide the implementation details, and provide backwards compatibility (at a cost).

Body:
Instead of returning the raw data directly, try something like this

class ClassA {
  private Things[] things;
  ...
  public Things[] asArray() { return things; }
  public List<Thing> asList() { ... }
  ...
}

So, you are essentially providing a custom collection that presents whatever face to the world is desired. In your new implementation then,

class ClassA {
  private List<Thing> things;
  ...
  public Things[] asArray() { return things.asArray(); }
  public List<Thing> asList() { return things; }
  ...
}

Now you have the proper encapsulation, hide the implementation details, and provide backwards compatibility (at a cost).


问:
Test Data in a Distributed System
A question that has been vexing me lately has been about how to effectively test (end-to-end) features in a distributed system.  Particuarly, how to effectively manage (through time) test data for feature testing.

The system in question is a typical SOA setup.  The composition is done in JavaScript when call to several REST APIs. Each service is built as an independent block.  Each service has some kind of persistent storage (SQL Server in most cases).

The main issue at the moment is how to approach test data when testing end-to-end features.  Functional end-to-end testing occurs through the UI, and it is therefore necessary for test data to be set up before the test run (this could be manual or automated testing).  As is typical in a distributed system, identifiers from one service are used as a link in another service.  So, some level of synchronization needs to be present in the data to effectively test.

What is the best way to manage and set up this data after a successful deployment to a test environment?

For example, is it better to manage this test data inside each service?  Or package it together with the testing suite?  Does that testing suite exist as a separate project?

I'm interested in design guidance about how to store and manage this test data as the application features evolve.

答:
Trying to provision for a widely distributed system is a hard thing to do.

Assumption 1: You don't have control over the databases at the level where you can reset them readily. Institutional test databases tend to be used, often heavily, by a number of separate development/maintenance groups. Hence, you cannot wipe/restore all of the databases without extensive coordination.

Assumption 2: You have support from the data stewards of each repository for necessary testing; hence, you can call on data managers to work with you on data sets. The data manager might allocate a range of test ZIP codes, or usernames, or similar.

Assumption 3: You are able to manage the data sets you are working with in each repository domain. For instance, in a contact database, you might be able to add an address of "1234 Testers Lane", or, perhaps "Suite CamoTester1, 1234 Birch Street" when ZIP code checking is being done.

Assumption 4: You are able to establish clear mappings between systems that exchange data. While not completely necessary, it will leave holes in your testing if you can't arrange this.

Set up provisioning sheets (MS Excel is your friend) with worksheets for each repository. You may end up with hundreds of data cases for each repository. Nobody said it would be easy! Now you have to come up with a way for your data not to explode combinatorially on you -- see assumption 4. Take data from sheet 1 for repository 1, determine if it is a source or sink for repository 2, whether it needs to coordinate with repository 2. Continue on down the line.

I have experience setting up testing for the connection between two ERP systems. Likely, the size of the problem was similar to what you are facing, although yours is more complex.

Title: Test Data in a Distributed System


问:
How important is XML for a developer?
Is it must that every developer should know XML? How important is XML for a developer? Any suggestion...</p>

答: XML is a tool, and like any tool it works better for some purposes than others. There is some debate about whether XML is the best tool for the purposes it's good at. My personal opinion is that JSON and s-expressions are both better alternatives for data interchange. In any case, knowing about XML as an option is a good thing.</p>

ContentLicense: CC BY-SA 2.5

Title: How important is XML for a developer?


问:
What is a good way to share internal helpers?
All my projects share the same base library that I have build up over quite some time. It contains utilities and static helper classes to assist them where .NET doesn't exactly offer what I want. Originally all the helpers were written mainly to serve an internal purpose and it has to stay that way, but sometimes they prove very useful to other assemblies. Now making them public in a reliable way is more complicated than most would think, for example all methods that assume nullable types must now contain argument checking while not charging internal utilities with the price of doing so. The price might be negligible, but it is far from right.

While refactoring, I have revised this case multiple times and I've come up with the following solutions so far:

Have an internal and public class for each helper

The internal class contains the actual code while the public class serves as an access point which does argument checking.

Cons:

The internal class requires a prefix to avoid ambiguity (the best presentation should be reserved for public types)

It isn't possible to discriminate methods that don't need argument checking

Have one class that contains both internal and public members (as conventionally implemented in .NET framework).

At first, this might sound like the best possible solution, but it has the same first unpleasant con as solution 1.

Cons:

Internal methods require a prefix to avoid ambiguity

Have an internal class which is implemented by the public class that overrides any members that require argument checking.

Cons:

Is non-static, atleast one instantiation is required. This doesn't really fit into the helper class idea, since it generally consists of independent fragments of code, it should not require instantiation.

Non-static methods are also slower by a negligible degree, which doesn't really justify this option either.

There is one general and unavoidable consequence, alot of maintenance is necessary because every internal member will require a public counterpart.

A note on solution 1:
The first consequence can be avoided by putting both classes in different namespaces, for example you can have the real helper in the root namespace and the public helper in a namespace called "Helpers".

答:
No, this doesn't answer your question directly, but mostly because I believe your problem is rooted elsewhere.

Personally I tend to stay away from "helper classes" and libraries. Such code tends to be a dumping ground for code that doesn't have a home, and leads to poor design. From what I've gathered your suggesting to have an assembly attached to each of your 'real' projects so that it can share some common code. And what I see happening is a bunch of code that gets loaded into the app domain, and maybe 10% of it actually used by any given segment of your domain. Which may end up costing you more than a few checks on public members.

I would suggest analyzing what parts of your domain will actually need specific code shared, and design the reusable code around that. Personally I prefer the usage of extension methods; You can tie specific reusable code to a specific type (avoid extending string, int or the like) giving it a nice comfortable home, and easy to understand code.

When all else fails remember: "Performance is not a problem until it is a problem. Your time is more valuable than a few CPU cycles"


答:
Here's another way to look at it:

As @rommik pointed out with his example, you could also pass the B object as a constructor argument, thus decoupling its lifecycle from A. Now forget about the corresponding UML diagram and think about your classes first. You have (at least these) two options:

class A { ... public A(B bInstance) { ...} }

or

class A { B bInstance = new B(); ... }

There are good reasons for either of these to be used, depending on the circumstances, and they naturally fit the aggregation and composition semantics of UML, respectively.

On the other hand, your edit proposes that class A has some instances, where the B object's lifetime depends on the A instance, and some other instances, where it doesn't.

Leave out UML and look at this simply from a general design point of view. Your class A suddenly got a lot more complicated. Of course, it is no wonder that you are having problems finding out how to depict it in a UML diagram. Heck, you'd even have problems to explain someone else what A does: "It gets B objects and does this and that with them.. oh except when it creates its own B objects..". Contrast this to explaining either of the two clear variants above.

In summary, the fact that you have two semantically different ways to model your design in UML is neither a problem of UML itself, nor your understanding of it. It is merely a pointer to remind you that your class design itself is ambiguous regarding its semantics.

Title: Understanding UML composition better


问:
With AMD style modules in JavaScript is there any benefit to namespaces?
Coming from C++ originally and seeing lots of Java programmers doing the same we brought namespaces to JavaScript. See Google's closure library as an example where they have a main namespace, goog and under that many more namespaces like goog.async, goog.graphics

But now, having learned the AMD style of requiring modules it seems like namespaces are kind of pointless in JavaScript. Not only pointless but even arguably an anti-pattern.

What is AMD? It's a way of defining and including modules that removes all direct dependencies. Effectively you do this

```<code>// some/module.js
define([
    'name/of/needed/module',
    'name/of/someother/needed/module',
  ], function(
     RefToNeededModule,
     RefToSomeOtherNeededModule) {

  ...code...

  return object or function
});
</code>```

This format lets the AMD support code know that this module needs name/of/needed/module.js and name/of/someother/needed/module.js loaded. The AMD code can load all the modules and then, assuming no circular dependencies, call the define function on each module in the correct order, record the object/function returned by the module as it calls them, and then call any other modules' define function with references to those modules.

This seems to remove any need for namespaces. In your own code you can call the reference to any other module anything you want. For example if you had 2 string libraries, even if they define similar functions, as long as they follow the AMD pattern you can easily use both in the same module. No need for namespaces to solve that.

It also means there's no hard coded dependencies. For example in Google's closure any module could directly reference another module with something like var value = goog.math.someMathFunc(otherValue) and if you're unlucky it will magically work where as with AMD style you'd have to explicitly include the math library otherwise the module wouldn't have a reference to it since there are no globals with AMD.

On top of that dependency injection for testing becomes easy. None of the code in the AMD module references things by namespace so there is no hardcoded namespace paths, you can easily mock classes at testing time.

Is there any other point to namespaces or is that something that C++ / Java programmers are bringing to JavaScript that arguably doesn't really belong?

答:
Executive summary below.

I should actually start a blog instead of writing it here, but hey.
live with it ;) this is also a opinion, everything in this 'answer' is
how I program, and what I think is best. Don't aggree? feel free to
send and email to /dev/null or comment :)

I personally believe that JavaScript and namespaces should not be used together. JavaScript is a JIT language. And that gives us a lot of good  stuff to work with.

The biggest speed-pain websites have are extra HTTP requests that get extra resources from the server. Everthing inside the  and  slows down the loading speed.
Webdevelopers then tend to only load critical libraries in the head (modernizr,...) and load al the other JS at the bottom of the  tag.

This works in modern browsers since they start rendering once they read the first line of the document. The page however hasn't finished loading untill all JS file shave been loaded. So visualy users will have a better responsetime, but this is simply because we defered the loading.

So we added Asynchronous loading techniques. Instead of add a  tag we add a small script that writes a  tag to the DOM. The small script that creates the  tag is loaded fired synchronous, but the loading of the  itself happens asynchronous and does not slow down page-loadtime (i.e. the domready event doesn't wait for this  to load). But then there is the problem of dependencies. We have no control over the order that these scripts load now. (A good example of this is the GA asynchronous script).

In comes AMD. Instead of loading all JS files that we might need somewhere in the application (one could add some optimization in the views/CMS but that just feels wrong) we load nothing (just the AMD loader) and defer the loading of everything else for later.

Then, often on a domready event or similar (bottom  tag) we start our application. e.g.:

```<code>var myFancyStartUpModule = require('my/fancy/boot/module');
myFancyStartUpModule.init();
</code>```

Now, lets say for some reason, we need a second instance of our fancy boot module. So one would do:

```<code>var mySecondFancyStartUpModule = new FancyStartUpModule();
</code>```

This ofcourse errors. So we try this:

```<code>var mySecondFancyStartUpModule = new my\Fancy\boot\Module();
</code>```

Again, syntax error. Ofcourse, forgot. Namespaces don't actually exist. What does exist is an object my, that has the object fancy,... So lets use it.

```<code>var mySecondFancyStartUpModule = new my.fancy.boot.Module();
</code>```

So we are using object to namespace (ieuk) and this will still error because my.fancy.boot.Module doesnt exist in the window scope. And that is the good stuff about javascript.

Because everything of my fancy module is defined inside that define function it doesn't exist in the window scope. Meaning that everything that wants to use that piece of code, has to use the require() (or set dependencie in define()). This gives you the sweet pieces of javascript like on the fly object creation, binding of this, prototyping but the robustness of a IOC-like style of programming.

I always tend to use a Adapter-pattern like style of programming in my AMD scripts. Instead of writing

```<code>require('vendor/fancy/module/for/pdf');
</code>```

I have a pdf adapter:

```<code>require('app/adapter/pdf');
</code>```

Now, i find this really sweet pdf library not written by fancy met by ultraFancy. I simply change one line of code in my adapter, and suddenly everything in my application uses the new ultraFancy pdf library.

Executive summary:

To answer your question. Namespaces in JS feel really stupid. Because namespaces don't exist in JS. However, we doe have objects with public arguments. And these arguments can be objects as well. And we can add stuff to objects on the fly (really nice). But writing new namespaced.module.inside.an.object(); just doesnt feel right imo.
Simply because we not only have molested those nice objects, there is also an unused object in the window object. All code is accessible, and oh boy, I don't trust my self with that much power. A I'll just do a quick fix for now turns into I'll just add this code to the previous fix codebase and quickly becomes require('app/fixes/all.min').

So, don't use namespaces in JS, you don't need them. Think of all those molested objects :(

Body:
Executive summary below.

I should actually start a blog instead of writing it here, but hey.
live with it ;) this is also a opinion, everything in this 'answer' is
how I program, and what I think is best. Don't aggree? feel free to
send and email to /dev/null or comment :)

I personally believe that JavaScript and namespaces should not be used together. JavaScript is a JIT language. And that gives us a lot of good  stuff to work with.

The biggest speed-pain websites have are extra HTTP requests that get extra resources from the server. Everthing inside the  and  slows down the loading speed.
Webdevelopers then tend to only load critical libraries in the head (modernizr,...) and load al the other JS at the bottom of the  tag.

This works in modern browsers since they start rendering once they read the first line of the document. The page however hasn't finished loading untill all JS file shave been loaded. So visualy users will have a better responsetime, but this is simply because we defered the loading.

So we added Asynchronous loading techniques. Instead of add a  tag we add a small script that writes a  tag to the DOM. The small script that creates the  tag is loaded fired synchronous, but the loading of the  itself happens asynchronous and does not slow down page-loadtime (i.e. the domready event doesn't wait for this  to load). But then there is the problem of dependencies. We have no control over the order that these scripts load now. (A good example of this is the GA asynchronous script).

In comes AMD. Instead of loading all JS files that we might need somewhere in the application (one could add some optimization in the views/CMS but that just feels wrong) we load nothing (just the AMD loader) and defer the loading of everything else for later.

Then, often on a domready event or similar (bottom  tag) we start our application. e.g.:

var myFancyStartUpModule = require('my/fancy/boot/module');
myFancyStartUpModule.init();

Now, lets say for some reason, we need a second instance of our fancy boot module. So one would do:

var mySecondFancyStartUpModule = new FancyStartUpModule();

This ofcourse errors. So we try this:

var mySecondFancyStartUpModule = new my\Fancy\boot\Module();

Again, syntax error. Ofcourse, forgot. Namespaces don't actually exist. What does exist is an object my, that has the object fancy,... So lets use it.

var mySecondFancyStartUpModule = new my.fancy.boot.Module();

So we are using object to namespace (ieuk) and this will still error because my.fancy.boot.Module doesnt exist in the window scope. And that is the good stuff about javascript.

Because everything of my fancy module is defined inside that define function it doesn't exist in the window scope. Meaning that everything that wants to use that piece of code, has to use the require() (or set dependencie in define()). This gives you the sweet pieces of javascript like on the fly object creation, binding of this, prototyping but the robustness of a IOC-like style of programming.

I always tend to use a Adapter-pattern like style of programming in my AMD scripts. Instead of writing

require('vendor/fancy/module/for/pdf');

I have a pdf adapter:

require('app/adapter/pdf');

Now, i find this really sweet pdf library not written by fancy met by ultraFancy. I simply change one line of code in my adapter, and suddenly everything in my application uses the new ultraFancy pdf library.

Executive summary:

To answer your question. Namespaces in JS feel really stupid. Because namespaces don't exist in JS. However, we doe have objects with public arguments. And these arguments can be objects as well. And we can add stuff to objects on the fly (really nice). But writing new namespaced.module.inside.an.object(); just doesnt feel right imo.
Simply because we not only have molested those nice objects, there is also an unused object in the window object. All code is accessible, and oh boy, I don't trust my self with that much power. A I'll just do a quick fix for now turns into I'll just add this code to the previous fix codebase and quickly becomes require('app/fixes/all.min').

So, don't use namespaces in JS, you don't need them. Think of all those molested objects :(


问:
Javascript Event in Innerhtml Resulting from PHP Server Script
I'm (very slowly) making a website, and I'm creating a search engine for the database, which is essential to organize the dependencies during data entry.

Anyway, what I would like is to type a few keywords into a box, have a menu pop up with various search results, and have the box fill with the ID number of the selected entry when it's clicked.

Currently, I have a document called search.php which fills a div called search-output using xmlhttp.open() and the innerhtml property. Everything is working perfectly except for filling the original search box with the ID number when clicking.

My first attempt was to add an onclick event to each entry in the output from search.php. Unfortunately, I found that javascript inserted into innerhtml is not run for security reasons. I've been Googling for hours but haven't been able to find a solution.

How can I get the original search text box to fill with the correct ID when I click it? Is what I'm doing a good setup for the results I desire, or is there a better way to integrate search features into data entry?

答:
Assuming I got what you mean correctly, The solution would be to have a single event handler on the div which is getting populated with the results, and use the Event object passed to the event handler to determine exactly which object was hit:

```<code><input type="text" id="search" name="search">
<div id="search-popup"></div> <!-- This will be populated with partial results -->
</code>```

And in the JavaScript, this JavaScript is not inserted into the page, but is part of it:

```<code>var searchPopup = document.getElementById("search-popup");
searchPopup.onclick = function(event) {
    var actualClickedElement = event.target; //Magic is here
    //Handle your event, probably by changing searchInput.value
};
</code>```

Now you can handle things with actualClickedElement inside the handler function. This also provides a nice performance boost when things get larger, since you only ever have one handler.

Read up on event delegation @ MDN.

Body:
Assuming I got what you mean correctly, The solution would be to have a single event handler on the div which is getting populated with the results, and use the Event object passed to the event handler to determine exactly which object was hit:

<input type="text" id="search" name="search">
<div id="search-popup"></div> <!-- This will be populated with partial results -->

And in the JavaScript, this JavaScript is not inserted into the page, but is part of it:

var searchPopup = document.getElementById("search-popup");
searchPopup.onclick = function(event) {
    var actualClickedElement = event.target; //Magic is here
    //Handle your event, probably by changing searchInput.value
};

Now you can handle things with actualClickedElement inside the handler function. This also provides a nice performance boost when things get larger, since you only ever have one handler.

Read up on event delegation @ MDN.


问:
Inheritance vs containment while extending a large legacy project
I have got a legacy Java project with a lot of code. The code uses MVC pattern and is well structured and well written. It also has a lot of unit tests and it is still actively maintained (bug fixing, minor features adding). Therefore I want to preserve the original structure and code style as much as possible.

I aim to inject a new behavior into an existing class. Like a Duck that was trained to jump. Then I ask all my Ducks to jump. Those who can - jump. Those who cannot do nothing which is perfectly OK with me.

The new feature I am going to add is a conceptual one, so I have to make my changes all over the code. In order to minimize changes I decided not to extend existing classes but to use containment:

```<code>class ExistingClass
{
   // .... existing code

   //  my code adding new functionality
   private ExistingClassExtension extension = new ExistingClassExtension();
   public ExistingClassExtension getExtension() {return extension;}
}

...
// somewhere in code
ExistingClass instance = new ExistingClass();

...
// when I need a new functionality
instance.getExtension().newMethod1();
</code>```

All functionality that I am adding is inside a new ExistingClassExtension class.
Actually I am adding only these 2 lines to each class that needs to be extended.

By doing so I also do not need to instantiate new, extended classes all over the code and I may use existing tests to make sure there is no regression.

However my colleagues argue that in this situation doing so isn't a proper OOP approach, and I need to inherit from ExistingClass in order to add a new functionality.

What do you think? I am aware of numerous inheritance/containment questions here, but I think my question is different.

EDIT:
Most of people replying to my question presume that a containment relationship looks like that:

```<code>class NewClass
{
   OldClass instanceOfOldClass;
   void oldFunctionality() { instanceOfOldClass.oldFunctionality();}

   void newFunctionality() { // new code here }
}
</code>```

But isn't this a kind of a containment relationship too?

```<code>class OldClass
{
   void OldFunctionality();
   NewClass instanceOfNewClass;

   void NewFunctionality {instanceOfNewClass.NewFunctionality();}
}
</code>```

答:
You are misunderstanding the composition vs inheritance argument here. The idea is that rather than inherit the different behaviors of your class/module/component, you inject it and contain it, like so:

```<code>class Duck {
    private ICanFly flyAbility;
    private ICanSpeak soundAbility;
    private ICanSwim swimAbility;

    public Duck(ICanFly wings, ICanSpeak beak, ICanSwim fins) { ... }
}
</code>```

So then the wings can be replaced with a JetPack, the beak with a VoiceCard and the fins with the UnderwaterPropeller, awesome Duck huh?

The idea is that your different objects can be broken down further by their behaviors, and that you can have Duck which is a bird that swims, Bat which is a mammal that flies, and Platypus which is a mammal that swims and lays eggs.

In your case, continuing with the existing structure and extending it (the structure, not necessarily the objects!) would be the best move. The question is how things are built nowadays. Don't break convention.

Body:
You are misunderstanding the composition vs inheritance argument here. The idea is that rather than inherit the different behaviors of your class/module/component, you inject it and contain it, like so:

class Duck {
    private ICanFly flyAbility;
    private ICanSpeak soundAbility;
    private ICanSwim swimAbility;

    public Duck(ICanFly wings, ICanSpeak beak, ICanSwim fins) { ... }
}

So then the wings can be replaced with a JetPack, the beak with a VoiceCard and the fins with the UnderwaterPropeller, awesome Duck huh?

The idea is that your different objects can be broken down further by their behaviors, and that you can have Duck which is a bird that swims, Bat which is a mammal that flies, and Platypus which is a mammal that swims and lays eggs.

In your case, continuing with the existing structure and extending it (the structure, not necessarily the objects!) would be the best move. The question is how things are built nowadays. Don't break convention.


问:
Which language features are considered harmful?
Please, explain why and list which languages have the (mis)feature implemented As far you know.

Post what you consider a harmful feature, not what you dislike.

答: The ability to turn counterclockwise in LOGO.  Wtf, lets just turn clockwise 360 - x degrees.


问:
Can an object call a method on its immediate descendant?
I have an inheritance hierarchy three deep : an abstract base class, from which I derive another abstract class, call it the intermediate class, from which will derive possibly a large variety of derived classes.

At one point, the base class calls a this.GenerateXml() method, implemented in the derived class, that returns nothing, but writes xml to a public property. At this point, I would like the intermediate class to do some stuff, without the base class or the derived class having to call a specific method on the intermediate class.

Is this possible in OO languages? Constructors call each other up the chain of inheritance. Can methods? Can an object call a method on its immediate descendant? The language in this case is C#

The obvious solution is to call a method, perhaps a same named method, from the derived class, using "base". This is less than ideal, because every derived class has to remember to make the call.

答:
I think, what you're looking for is the Template method pattern. You define in one abstract class the general outline of what needs to be done by calling smaller, more fine-grained methods. One (or more) of these methods is abstract and must thus be implemented by inheriting classes.

```<code>abstract class Vehicle {
    public void drive() {
        startEngine();
        goForward();
        stopEngine();
    }

    protected abstract void goForward();

    private void startEngine() {
        ...
    }

    private void stopEngine() {
        ...
    }
}
</code>```

All inheriting classes implement the goForward() method while only drive() is publicly visible. Vehicle thus defines how driving in general works while a Car or Truck implements the actual movement.

Your request seems to be a little more complex by using another inheritance layer. But, in general, I don't see a problem with another intermediate abstract class that passes the abstract method even further down, or even implements it using itself the template method pattern all over again.

Body:
I think, what you're looking for is the Template method pattern. You define in one abstract class the general outline of what needs to be done by calling smaller, more fine-grained methods. One (or more) of these methods is abstract and must thus be implemented by inheriting classes.

abstract class Vehicle {
    public void drive() {
        startEngine();
        goForward();
        stopEngine();
    }

    protected abstract void goForward();

    private void startEngine() {
        ...
    }

    private void stopEngine() {
        ...
    }
}

All inheriting classes implement the goForward() method while only drive() is publicly visible. Vehicle thus defines how driving in general works while a Car or Truck implements the actual movement.

Your request seems to be a little more complex by using another inheritance layer. But, in general, I don't see a problem with another intermediate abstract class that passes the abstract method even further down, or even implements it using itself the template method pattern all over again.