问:
Generalized VS Specialized technical solution; what to take into account?
We recently had a discussion in the office because of conflicting views between developers. One side (side S) argued technical solutions -generally- need to be a specific as possible, while the other side (side G) argued generalized solutions are preferred.

I'll try to keep it short; we deal with file transfers and we need to start saving three files (log.txt, details.txt, receipt.pdf) for each transfer. We already have a files table that we'll use but we all agree that we need a different table to create a one-to-many relationship between transfers and files.

Side G proposed creating general resource_attachments table that can attach files to any type of resource it would look something like this;

resource_attachments

- id : int

- entityId : int

- entityType : string

- fileId : int

- kind : string

Side S disagreed and proposed creating a specialized transfer_attachments table, something like this;

transfer_attachments

- id : int

- transferId : int

- fileId : int

- kind : string

One argument of side S is that any resource should be as specific as possible so its role and its attributes and their possible values are clear, so any new developer will have no trouble understanding it.

An argument of side G was that a more generalized approach would provide a broader range of functionality; you can attach files to any resource, whatever their role will be.

Though the practical differences are very small, there is some fundamental stuff going on here (this is where it gets philosophical); one person in the room sharply observed that the generalizer is the ruby expert, while the specializer is the java expert. Ruby is an interpreted language with dynamic typing while java is a compiled language with static typing.

I found the matter wildly interesting and was wondering which approach is preferred; specialized or generalized solution, and what matters should be taken into account?

Note that we're only talking about a the technical part of the solution, this has nothing to do with the end-user experience.

答:
As usual, the answer is: it depends. There are lots of issues to consider, including:

first and foremost, what the customer wants and is willing to pay for

the difference in implementation and maintenance cost and risks between the alternative solutions

the expected lifetime of the product

the expected scope of future changes (i.e. is it reasonably expected that the more general solution will actually be used in the foreseeable future?)

If the more general solution is easy to implement, with minimal additional cost and zero risk, it may be a good idea to do it, even if there is no known need for it. OTOH if the general solution is significantly costlier, you need a strong enough justification (= added value for the customer) for it, otherwise you end up with speculative generality.

You should always keep in mind that a more general solution usually (although not always!) means more complex code, which is thus harder to understand and modify in the long run. So the implementation cost is not the only factor to take into account. Maintenance costs for a product with a long lifecycle exceed development costs manifold. OTOH for a product meant to be used only once or for a short time, obviously making it more general may be pointless. (Although we should be aware that the actual lifetime of software is often significantly longer than originally planned.)

And the "not always" case mentioned above also includes cases when careful analysis of the problem reveals that it is a subcase or a different view of some more general, well known problem for which known solutions exist, or the solution is significantly easier to implement. In these cases, the extra analysis and design effort more than pays off in simpler and cleaner code, which may even be faster and/or less resource hungry. These cases are the exception, rather than the rule, but still they are worth mentioning.

Update

One extra aspect I forgot to mention is the potential cost of making the solution more general in the future. Often it is not significantly costlier to refactor the code later than to make it general now - which suggests deferring the decision to as late as possible. The economy of such decisions is saving 100 dollars now, with the risk that in the worst case, you will need to pay 110 dollars some years later (but you have invested that 100 dollars and it may have since earned you more than that), but in the best case you pay nothing.

However, there is (at least) one area where refactoring later is significantly costlier, riskier and more difficult than designing a general solution from the start: databases. Changing your table structure and migrating huge amounts of business critical data into a new structure is far from trivial even in simpler cases, and can be downright impossible sometimes. So when designing a DB schema, it makes sense to go for the more general solution, which can include a greater range of potential future extensions.


问:
Program/library to match string patterns
I've city names, like Newyork. Somebody may misspell it and write it as Newyoork. I want an algorithm or library which can match such patterns with some confidence level.

Any idea how to do it or if any pattern recognition library is present?

It is same as when we type something in Google with spelling mistake in it but instead it automatically corrects the mistake.

答:
You already quoted in your own question one service to use: Google itself. Looking at Google Maps API may be helpful too, I believe, but I don't remember if there was an auto-correction feature in their geolocation API.

Another possibility is to use a spell checker (on Windows where you have Microsoft Office, you can use the API provided by Microsoft Office; on other platforms, analog products are available). Get all the suggestions for a word from a spell checker, and compare them to the list of cities, to be sure that the suggestion is a geographic location, not a word from a dictionary.

ContentLicense: CC BY-SA 3.0


答:
Comparing two strings A and B :-

Levenshtein comparison counts the number of steps (adding, replacing or removing a single character at a time) to change A into B.

Ratcliff comparison gives a match score (100 for two equal strings) based on the longest common sequence between A and B, with recurrence to compare the remaining sub-strings after each iteration.

Here are my C# implementations as string extender functions

```<code>public static class StringExtender
{
    public static int CompareLevenshtein(this string A, string B)
    { return A.CompareLevenshtein(B, false); }

    public static int CompareLevenshtein(this string A, string B, bool CaseSensitive)
    {
        int LA = A.Length;
        int LB = B.Length;
        if (LA == 0)
            return LB;
        else if (LB == 0)
            return LA;
        else
        {
            string A1 = CaseSensitive ? A : A.ToUpperInvariant();
            string B1 = CaseSensitive ? B : B.ToUpperInvariant();
            int[,] D = new int[LA + 1, LB + 1];
            for (int i = 0; i <= LA; i++)
                D[i, 0] = i;
            for (int i = 0; i <= LB; i++)
                D[0, i] = i;
            for (int i = 1; i <= LA; i++)
            {
                char AI = A1[i - 1];
                for (int j = 1; j <= LB; j++)
                {
                    char BJ = B1[j - 1];
                    int cost = (AI == BJ ? 0 : 1);
                    D[i, j] = MimumumOf3(D[i - 1, j] + 1,
                                         D[i, j - 1] + 1,
                                         D[i - 1, j - 1] + cost);
                }
            }
            return D[LA, LB];
        }
    }

    private static int MimumumOf3(int i, int j, int k)
    { return Math.Min(Math.Min(i, j), k); }

    public static float CompareStringsRatcliff(this string A, string B)
    { return CompareStringsRatcliff(A, B, false); }

    public static float CompareStringsRatcliff(this string A, string B, bool CaseSensitive)
    {
        int LA = A.Length;
        int LB = B.Length;

        if ((LA == 0) || (LB == 0))
            return 0.0f;
        else
        {
            string A1 = (CaseSensitive ? A : A.ToUpperInvariant());
            string B1 = (CaseSensitive ? B : B.ToUpperInvariant());
            if (A1.Equals(B1))
                return 100.0f;
            else
                return CompareStringsRatcliffInternal(A1, 0, LA - 1, B1, 0, LB - 1) * 200.0f / (LA + LB);
        }
    }

    private static int CompareStringsRatcliffInternal(string A, int StartIndexA, int EndIndexA, string B, int StartIndexB, int EndIndexB)
    {
        if ((StartIndexA > EndIndexA) || (StartIndexB > EndIndexB))
            return 0;
        else
        {
            int NewStartIndexA = 0;
            int NewStartIndexB = 0;
            int BestMatches = 0;
            for (int Ai = StartIndexA; Ai <= EndIndexA; Ai++)
                for (int Bi = StartIndexB; Bi <= EndIndexB; Bi++)
                {
                    int i = 0;
                    int Matches = 0;
                    while ((Ai + i <= EndIndexA) && (Bi + i <= EndIndexB) && (A[Ai + i] == B[Bi + i]))
                    {
                        Matches++;

                        if (Matches > BestMatches)
                        {
                            NewStartIndexA = Ai;
                            NewStartIndexB = Bi;
                            BestMatches = Matches;
                        }
                        i++;
                    }
                }

            if (BestMatches > 0)
            {
                BestMatches += CompareStringsRatcliffInternal(A, NewStartIndexA + BestMatches, EndIndexA, B, NewStartIndexB + BestMatches, EndIndexB);
                BestMatches += CompareStringsRatcliffInternal(A, StartIndexA, NewStartIndexA - 1, B, StartIndexB, NewStartIndexB - 1);
            }

            return BestMatches;
        }
    }
}
</code>```

Title: Program/library to match string patterns

Body:
I've city names, like Newyork. Somebody may misspell it and write it as Newyoork. I want an algorithm or library which can match such patterns with some confidence level.

Any idea how to do it or if any pattern recognition library is present?

It is same as when we type something in Google with spelling mistake in it but instead it automatically corrects the mistake.

Body:
Comparing two strings A and B :-

Levenshtein comparison counts the number of steps (adding, replacing or removing a single character at a time) to change A into B.

Ratcliff comparison gives a match score (100 for two equal strings) based on the longest common sequence between A and B, with recurrence to compare the remaining sub-strings after each iteration.

Here are my C# implementations as string extender functions

public static class StringExtender
{
    public static int CompareLevenshtein(this string A, string B)
    { return A.CompareLevenshtein(B, false); }

    public static int CompareLevenshtein(this string A, string B, bool CaseSensitive)
    {
        int LA = A.Length;
        int LB = B.Length;
        if (LA == 0)
            return LB;
        else if (LB == 0)
            return LA;
        else
        {
            string A1 = CaseSensitive ? A : A.ToUpperInvariant();
            string B1 = CaseSensitive ? B : B.ToUpperInvariant();
            int[,] D = new int[LA + 1, LB + 1];
            for (int i = 0; i <= LA; i++)
                D[i, 0] = i;
            for (int i = 0; i <= LB; i++)
                D[0, i] = i;
            for (int i = 1; i <= LA; i++)
            {
                char AI = A1[i - 1];
                for (int j = 1; j <= LB; j++)
                {
                    char BJ = B1[j - 1];
                    int cost = (AI == BJ ? 0 : 1);
                    D[i, j] = MimumumOf3(D[i - 1, j] + 1,
                                         D[i, j - 1] + 1,
                                         D[i - 1, j - 1] + cost);
                }
            }
            return D[LA, LB];
        }
    }

    private static int MimumumOf3(int i, int j, int k)
    { return Math.Min(Math.Min(i, j), k); }

    public static float CompareStringsRatcliff(this string A, string B)
    { return CompareStringsRatcliff(A, B, false); }

    public static float CompareStringsRatcliff(this string A, string B, bool CaseSensitive)
    {
        int LA = A.Length;
        int LB = B.Length;

        if ((LA == 0) || (LB == 0))
            return 0.0f;
        else
        {
            string A1 = (CaseSensitive ? A : A.ToUpperInvariant());
            string B1 = (CaseSensitive ? B : B.ToUpperInvariant());
            if (A1.Equals(B1))
                return 100.0f;
            else
                return CompareStringsRatcliffInternal(A1, 0, LA - 1, B1, 0, LB - 1) * 200.0f / (LA + LB);
        }
    }

    private static int CompareStringsRatcliffInternal(string A, int StartIndexA, int EndIndexA, string B, int StartIndexB, int EndIndexB)
    {
        if ((StartIndexA > EndIndexA) || (StartIndexB > EndIndexB))
            return 0;
        else
        {
            int NewStartIndexA = 0;
            int NewStartIndexB = 0;
            int BestMatches = 0;
            for (int Ai = StartIndexA; Ai <= EndIndexA; Ai++)
                for (int Bi = StartIndexB; Bi <= EndIndexB; Bi++)
                {
                    int i = 0;
                    int Matches = 0;
                    while ((Ai + i <= EndIndexA) && (Bi + i <= EndIndexB) && (A[Ai + i] == B[Bi + i]))
                    {
                        Matches++;

                        if (Matches > BestMatches)
                        {
                            NewStartIndexA = Ai;
                            NewStartIndexB = Bi;
                            BestMatches = Matches;
                        }
                        i++;
                    }
                }

            if (BestMatches > 0)
            {
                BestMatches += CompareStringsRatcliffInternal(A, NewStartIndexA + BestMatches, EndIndexA, B, NewStartIndexB + BestMatches, EndIndexB);
                BestMatches += CompareStringsRatcliffInternal(A, StartIndexA, NewStartIndexA - 1, B, StartIndexB, NewStartIndexB - 1);
            }

            return BestMatches;
        }
    }
}


答:
You want Soundex, which is intended to do exactly this: recognize proper names that people have misspelt in various ways.

a phonetic algorithm for indexing names by sound, as pronounced in English. The goal is for homophones to be encoded to the same representation so that they can be matched despite minor differences in spelling. The algorithm mainly encodes consonants; a vowel will not be encoded unless it is the first letter. Soundex is the most widely known of all phonetic algorithms (in part because it is a standard feature of popular database software such as PostgreSQL, MySQL, MS SQL Server and Oracle)...


问:
Why are several popular programming languages influenced by C?
The Top 10 programming languages, according to the TIOBE index seem to be heavily influenced by C:

1. Java

The language derives much of its syntax from C and C++ but has a simpler object model and fewer low-level facilities. - wikipedia.org

2. C

C is one of the most widely used programming languages of all time and there are very few computer architectures for which a C compiler does not exist. - wikipedia.org

3. C#

During the development of the .NET Framework, the class libraries were originally written using a managed code compiler system called Simple Managed C (SMC). In January 1999, Anders Hejlsberg formed a team to build a new language at the time called Cool, which stood for "C-like Object Oriented Language". - wikipedia.org

4. C++

It was developed by Bjarne Stroustrup starting in 1979 at Bell Labs as an enhancement to the C language. - wikipedia.org

5. Objective-C

Objective-C is a reflective, object-oriented programming language that adds Smalltalk-style messaging to the C programming language. - wikipedia.org

6. PHP

He rewrote these scripts as C programming language Common Gateway Interface (CGI) binaries, extending them to add the ability to work with Web forms and to communicate with databases and called this implementation "Personal Home Page/Forms Interpreter" or PHP/FI. - wikipedia.org

8. Python

Python was conceived in the late 1980s and its implementation was started in December 1989 by Guido van Rossum at CWI in the Netherlands as a successor to the ABC programming language (itself inspired by SETL) capable of exception handling and interfacing with the Amoeba operating system. - wikipedia.org

ABC (programming language)
Its designers claim that ABC programs are typically around a quarter the size of the equivalent Pascal or C programs, and more readable. - wikipedia.org

9. Perl

Perl borrows features from other programming languages including C, shell scripting (sh), AWK, and sed. - wikipedia.org

10. JavaScript

JavaScript uses syntax influenced by that of C. - wikipedia.org

It appears that most of them borrow their syntax from C and / or are heavily influenced in several other ways, at least in their beginnings. Why?

答:
Programming languages evolve over time just like natural languages, with some older languages influencing that evolution in a stronger way than others, while others fade into obscurity and their influence is harder to trace on the surface level, that is, syntax.

C's influence comes from many sources - it's low level, widespread, had backing in both Unix and Microsoft circles. It's also survival of the fittest issue - it's easy to see terse C-like syntax had more appeal than the verbose Algol-derived syntax of Pascal and other competitors of C in the 1970s and 1980s. Hence it was widely adopted by languages that came after it.

With present growth of importance of multithreaded programming and functional languages being particularly well-suited to it, I'd say we'll see their influence grow in the future. Case in point: Python, which even made that list in the question post.

A nice timeline view of language history to ponder upon


答:
With the rise of UNIX in the 1970's, its standard systems programming language C quickly became the lingua franca of the programming world. For quite a while, C was practically mandatory for every programmer. As such, the fact that C has influenced almost every programming language that came after it in one way or another is hardly surprising, for two reasons:

When designing a new language, it makes sense to base its syntax, where possible, on a popular existing language that can be assumed common knowledge.

A new language is more likely to succeed if the learning curve is shallow, and a syntax that resembles an already known language is generally easier to learn (unless it behaves radically different despite the apparent similarities). So languages that borrow syntax from C generally gain traction more quickly than ones that don't.

But other languages existed, and they still do, some of them even predating C - there's the LISP family (CL, Clojure and Scheme being the most popular modern dialects), the ML family (with several modern dialects), there's a whole army of BASIC dialects (VB.NET and VBA are modern implementations), there's Pascal and its relatives (Delphi being the best known one) and many 'oddball' languages that took influences from many other languages and invented a few things themselves; examples include Go, Python, Lua, Haskell (and its predecessor, Miranda), Prolog, and Erlang. While none of these languages (except Python) is in your top 10, many of them have a stable user base and an active community; they're certainly not going away.

Also, it should be noted that the amount of C influence in these languages differs wildly, ranging from the almost 100% C compatible languages C++ and Objective-C, up to Python (which deliberately abandons many of C's syntax features). And that's only the syntax: in terms of semantics, most of the languages on that list don't have much in common with C. The overwhelming majority has memory management built into the language, and consequently, copy semantics, argument passing, etc., are very different. JavaScript, for example, has strong semantic influences from Scheme, while its syntax was designed to resemble Java (which, in turn bases its bits-and-pieces syntax on C, but not its semantics). Other differences (with the exception of C++ and Objective-C, which are mostly backwards-compatible with C) include error handling, scope rules, standard libraries, external code inclusion (#include), and the fact that many of these languages are 'virtualized', that is, they run on an interpreter, JIT compiler, or a virtual machine.

Python, by the way, does have some C influence, but it is certainly not "based on" C. Both syntax and semantics differ quite radically from C, and this is by design. Python only borrows features from C where other alternatives are equally "good" (as per the "Zen of Python" - type import this in a python interpreter).

As for the future of programming; predictions vary. The influence of C is not going away, but recent developments in hardware (multi-core machines becoming commonplace, powerful GPU's, the CPU ceasing to be the typical performance bottleneck, fast reliable network connections, etc.) call for radically different approaches to programming in general. Anyone who has ever written a multithreaded distributed application in an imperative language can tell that it's incredibly hard, while languages like Haskell have features that remove most of the typical problems and offer a more abstract and more structured approach to distributed, concurrent, and parallel processing (purity being an important concept in this context). Newer programming languages (e.g. C# or D) already include many features to support such an idiom. In any case, neither the strong impact C has made on programming, nor the existence of non-C-like languages is going away.

Title: Why are several popular programming languages influenced by C?

Body:
The Top 10 programming languages, according to the TIOBE index seem to be heavily influenced by C:

1. Java

The language derives much of its syntax from C and C++ but has a simpler object model and fewer low-level facilities. - wikipedia.org

2. C

C is one of the most widely used programming languages of all time and there are very few computer architectures for which a C compiler does not exist. - wikipedia.org

3. C#

During the development of the .NET Framework, the class libraries were originally written using a managed code compiler system called Simple Managed C (SMC). In January 1999, Anders Hejlsberg formed a team to build a new language at the time called Cool, which stood for "C-like Object Oriented Language". - wikipedia.org

4. C++

It was developed by Bjarne Stroustrup starting in 1979 at Bell Labs as an enhancement to the C language. - wikipedia.org

5. Objective-C

Objective-C is a reflective, object-oriented programming language that adds Smalltalk-style messaging to the C programming language. - wikipedia.org

6. PHP

He rewrote these scripts as C programming language Common Gateway Interface (CGI) binaries, extending them to add the ability to work with Web forms and to communicate with databases and called this implementation "Personal Home Page/Forms Interpreter" or PHP/FI. - wikipedia.org

8. Python

Python was conceived in the late 1980s and its implementation was started in December 1989 by Guido van Rossum at CWI in the Netherlands as a successor to the ABC programming language (itself inspired by SETL) capable of exception handling and interfacing with the Amoeba operating system. - wikipedia.org

ABC (programming language)
Its designers claim that ABC programs are typically around a quarter the size of the equivalent Pascal or C programs, and more readable. - wikipedia.org

9. Perl

Perl borrows features from other programming languages including C, shell scripting (sh), AWK, and sed. - wikipedia.org

10. JavaScript

JavaScript uses syntax influenced by that of C. - wikipedia.org

It appears that most of them borrow their syntax from C and / or are heavily influenced in several other ways, at least in their beginnings. Why?


问:
php + web service
Can someone confirm good performance using PHP + Java webservice (for heavy duty tasks) running on NGINX (or Apache) because PHP is slow in completing some heavy tasks and I want to make a web service in java to communicate with PHP via SOAP or REAT or JSON.

The fact I'm asking this question is that I already know PHP at a very good level (and Java and I don't want to start learning ASP or Ruby) and HTML5, CSS3 and I want to develop a big portal that will have increased number of requests (1000 / 2000 request/sec) and I don't want to code the whole application in Java (cause PHP has more sense), I only need the heavy work to be done by a webservice.

For my project PHP is slow in doing some Math computation and I/O file access every second. It consume a lot of memory and a lot of CPU. At the rate of 1000 req/s it almost crushes.

Is this a good practice? Is there another solution?

答:
If you need better performance out of your PHP code, these are the steps you should be taking, in order:

Identify the bottlenecks. Add some simple profiling to see where your code spends most of its time. Focus on that part.

Check your algorithmic complexity ("big-O"). If you can reduce an O(n^3) algorithm to O(n^2), do it.

For everything you do, check if there is a PHP library function that can do the same thing. Many of those are implemented in C, and they run much faster than equivalent PHP code.

Balance CPU vs. RAM usage. For most problems, you can trade one for the other: if you're using too much RAM, you can generate some of your data procedurally when needed (you trade CPU cycles for RAM), if you're CPU bound, you can often precalculate results and reuse them (using more RAM to save CPU cycles).

Use caching. Lots of it. If you aren't using memcached already, do so, and use it to cache final results, intermediate results, or anything you are going to need a lot. You may even want to cache at several levels, e.g., cache database query results, intermediate values, final values, and raw responses.

Write faster PHP. PHP and its interpreter have a few quirks, so it's not always obvious if and why a certain code variation runs faster, so you really need to profile in order to know.

If you have to, implement the most performance-critical part of your code in C, and call the C code from PHP. There are several ways of achieving this - you can write a PHP extension, you can simply shell out to the C program, you can run the C program as a CGI binary, or you can design the C part as a daemon and communicate over named pipes or local sockets. If in doubt, the shellout is probably the easiest option to implement.

Throw more hardware at it - that is, buy a faster server.

Distribute the load over several servers. This usually requires drastic changes to your architecture, so you should investigate thoroughly if this is both necessary and feasible. Also note that there are several strategies to this.

Title: php + web service


问:
Are dynamic languages always interpreted?
Looking at most (if not all) dynamic languages (e.g. Python, PHP, Perl and Ruby), they are all interpreted. Correct me if I'm wrong. Is there any example of dynamic language that goes through compilation phase? Is dynamic language identical with interpreted language? </p>

答:
No - it's certainly possible to compile dynamic languages.

There are even some dynamic languages that are always compiled by design (e.g. Clojure).

The question however touches on an important related point: although dynamic languages can be compiled, it is often the case that dynamic langauges cannot be compiled down to code that is as efficient as a statically typed language. This is because there are some inherent features in dynamic languages that require runtime checks that would be unnecessary in a statically compiled langauge.

An example of this: languages that allow runtime patching of objects (e.g. Ruby) often require the object to be inspected (with a hashtable lookup or similar) whenever you invoke a method on the object. Even if this is compiled, the compiler will have to generate code to do the method lookup at runtime. To some extent this method lookup is not dissimilar to what an interpreter would have to do.

This adds a significant overhead when compared to a method call in a language like Java, where the correct method can be statically determined by the compiler from the class definition and reduced to a simple function call in native code.

I believe it is this effect more than anything else that results in dynamic languages having slower performance on average than their statically compiled counterparts. As you can see from the flawed benchmarks, it's the statically typed languages (C, Java, Fortran etc.) that tend to be fastest with the dynamic languages (Perl, Python, Ruby, PHP etc.) at the bottom of the ranking.

ContentLicense: CC BY-SA 4.0


问:
Is there a viable alternative to the agile development methodology?
The two predominant software-development methodologies are waterfall and agile.  When discussing these two, there is often much focus on the particular practices that distinguish them (pair programming, TDD, etc. vs. functional spec, big up-front design, etc.)

But the real differences are far deeper, in that these practices come from a philosophy.

Waterfall says:  Change is costly, so it should be minimized.

Agile says:  Change is inevitable, so make change cheap.

My question is, regardless of what you think of TDD or functional specs, is the waterfall development methodology really viable?

Does anyone really think that minimizing change in software is a viable option for those that desire to deliver valuable software?  Or is the question really about what sort of practices work best in our situations to manage the inevitable change?

答:
The Waterfall method most certainly is viable and is as philosophically sound as any other approach. Remember that Waterfall has been around much longer than Agile, but note that this isn't an argument to state whether one methodology is better than another.

You use the Waterfall method when have a very clear understanding about the entire problem domain and what the customer wants to achieve in a software package. You've probably quoted a fixed price when taking on the contract, and your customer understands that they cannot deviate from any agreed requirements. Your process is strictly one that flows through a series of sign-offs between the various stages of development, and it is often the case that each stage is completed by a different team - sometimes even a different company - each of which may not necessarily in contact with the others. You often see Waterfall applied to good effect in military and government projects when they are tendered to outside contractors. Where Waterfall and other similar approaches get a bad reputation is when developers run into problems, such as poor estimation, schedules planned without contingency time, or a poor or incomplete understanding of the problem domain. The issue is never truly a fault of the methodology, but in the application of it.

The comparison between Agile and any methodology is a false one.  Agile isn't a methodology, it's a philosophy, or perhaps it would be better to say that it is an umbrella term that represents a different way to look at how you go about developing software. A methodology is merely a tool, and as such its value will always be less than the individuals and interactions that are at the heart of what it means to be Agile.

Does anyone really think that minimizing change in software is a viable option for those that desire to deliver valuable software?

Every opportunity to minimize change is valuable to both the developer and the customer. Changes can cause a schedule to slip, or features to be left out in order to meet a schedule. It's how you manage the effects of change that impacts on the value of your projects.

Or is the question really about what sort of practices work best in our situations to manage the inevitable change?

Your practices may aid in the management of change, or they may ignore change completely. What matters is the combination of your development practices, and the management of your relationship with your customers, and whether these things work together effectively for all of the parties involved.

Those of us who are for all intents and purposes Agile understand that you choose a method that works for you. If you like particular approach, follow it. If it doesn't quite fit your needs, change it. How you go about crafting software really comes down to trying to make the best use of the resources you have at hand, and minimizing those practices that can lead your project towards failure, and you often find that you need to change your method to suit the particular project at hand.

It really is one thing to say "Ok, so now we are Agile", and totally another to actually live and work by the philosophy that Agile is. Whether you use Waterfall, Incremental, Spiral, SCRUM, XP, FDD, or any other method, you are basically Agile where you value:

Individuals and interactions over processes and tools

Working software over comprehensive documentation

Customer collaboration over contract negotiation

Responding to change over following a plan

and where you bring your tools, method, and your experience all together in order to apply these values successfully.


问:
GUI architecture and class naming advice
Problem:

I'm working on coding a few light-weight touch-tablet games and often get stuck with difficulties naming my user interaction/interface classes and their relationships with each other (architecture?). I'm rarely satisfied with any of my solutions, thus doubt and change them several times on down the line. For example, I have a board game with these components (among others):

"HUD" - the HUD frames the view of the game world thus enabling user interaction

"boardOverlay" - this is invisible and lies on top of the viewed game world. It  receives and interprets touches, consequently calling methods in "thinger".

"board" - maintains all elements on the board.

"thinger" - the class that gets things done, changes game state. I call it thinger since I dont know what it should be called. Better to have a non-descript name than one that will be misinterpreted.

Searching for enlightenment:

Now I would like to have general/abstract names/architecture for these components which will likely be used in many other games/apps. But I have difficulty coming up with satisfying ones. I have searched the net many a time for guidelines/advice but I find that all of the sources are language/technology/API specific and seldom like their approach.

I don't know the name of this discipline/practice to search for for enlightenment. I have tried "event driven framework", "event driven naming conventions", "GUI architecture", "+oop +GUI +taxonomy"...   on and on .... ....   with no luck.

Question1:

Can anyone provide a resource to enlighten me? A technology independent resource that philosophizes about this type of naming and architecture.

Extra credit question:

It would also be great with a reliable/concise resource discussing practices/disciplines of this context? There are too many different and overlapping usages/interpretations out there. Example: GUI framework, GUI architecture, GUI structure, GUI design - what should the proper usage of these terms be?

答:
Have you heard about the Model View Controller (MVC) Architectural Pattern? Maybe it would help you to name things clearer if you apply this pattern to your software architecture/design.

If i would apply this pattern to your components i would do it like that:

HUD = Hud View

boardOverlay = Board Controller

board = Board View if it's main task is rendering, Model otherwise

thinger = Game Controller

Hope this helps.


问:
Interface and Inheritance: Best of both worlds?
I 'discovered' interfaces and I started to love them. The beauty of an interface is that it is a contract, and any object that fulfills that contract can be used wherever that interface is required.

The problem with an interface is that it can't have a default implementation, which is a pain for mundane properties and defeats DRY. This is also good, because it keeps the implementation and the the system decoupled. Inheritance, on the hand, maintains a tighter coupling, and has the potential of breaking encapsulation.

Case 1 ( Inheritance with private members, good encapsulation, tightly coupled)

```<code>class Employee
{
int money_earned;
string name;

public:
 void do_work(){money_earned++;};
 string get_name(return name;);
};

class Nurse : public Employee:
{
   public:
   void do_work(/*do work. Oops, can't update money_earned. Unaware I have to call superclass' do_work()*/);

};

void HireNurse(Nurse *n)
{
   nurse->do_work();
)
</code>```

Case 2 (just an interface)

```<code>class IEmployee
{
     virtual void do_work()=0;
     virtual string get_name()=0;
};

//class Nurse implements IEmployee.
//But now, for each employee, must repeat the get_name() implementation,
//and add a name member string, which breaks DRY.
</code>```

Case 3: (best of both worlds?)

Similar to Case 1. However, imagine that (hypothetically) C++ did not allow overriding methods except those methods that are pure virtual.

So, in Case 1, overriding do_work() would cause a compile-time error. To fix this, we set do_work() as pure virtual, and add a separate method increment_money_earned(). As an example:

```<code>class Employee
{
int money_earned;
string name;

public:
 virtual void do_work()=0;
 void increment_money_earned(money_earned++;);
 string get_name(return name;);
};

class Nurse : public Employee:
{
   public:
   void do_work(/*do work*/ increment_money_earned(); ); .
};
</code>```

But even this has problems. What if 3 months from now, Joe Coder creates a Doctor Employee, but he forgets to call increment_money_earned() in do_work()?

The question:

Is Case 3 superior to Case 1? Is it because it of 'better encapsulation' or 'more loosely coupled', or some other reason?

Is Case 3 superior to Case 2 because it conforms with DRY?

答: Using interfaces only breaks DRY if each implementation is a duplicate of every other.  You can resolve this dilemma by applying both interface and inheritance, yet there are some cases where you may wish to implement the same interface on a number of classes, but vary the behavior in each of the classes, and this will still keep to the principle of DRY. Whether you choose to use any of the 3 approaches you've described comes down to the choices you need to make to apply the best technique to match a given situation. On the other hand, you'll probably find that over time, you use Interfaces more, and apply inheritance only where you wish to remove repetition.  That's not to say that this is the only reason for inheritance, but that it's better to minimize the use of inheritance to allow you to keep your options open if you find your design needs to change later on, and if you wish to minimize the impact on descendant classes from the effects that a change would introduce in a parent class.


答:
This is a lot like asking why English is the dominant language in the US.  Why not Spanish or French? They controlled more of the US territory than the English colonies.  Why not Dutch?  The first US capital was in a former Dutch colony.  I'm not sure there can possibly be an "answer" to this.

However, the "Computer Languages History" timeline (http://www.levenez.com/lang/) provides all the answer there can possibly be.


答: Most of the languages you list have virtually nothing to do with C apart from irrelevant syntactic similarities. The only two actual C derivatives are Objective-C and C++.</p>


问:
Is Spring + Hibernate prefered instead of EJB 3?
It is my perception that whenever new JEE projects start (where these technologies would be applicable), people prefer to use a combination of Spring + Hibernate instead of EJB 3.

It seems junior programmers are even advised to go for that instead of EJB.

Is this personal preference or are there pertinent reasons for it? (e.g. personal scars created by earlier EJB versions which caused mistrust in EJB or technology bloat versus performance reasons or learning curve)?

答:
The EJB 3+ frameworks are actually pretty good as they came along with JPA as an answer for annotation configured Persistence frameworks, as well as CDI which allows for annotation configured dependency injection.  You also add on top of that Weld.  Spring on the other hand is just now catching up in the game with configuration through annotation.

With that being said the historical backlack against EJB1 and 2 should not be discounted.  They didn't just fail to solve the problems with writing enterprise applications, they spectacularly failed.  It was a complete failure on the part of the designers to get a pulse on the true problems facing enterprise and web application developers and in turn deliver solutions that they actually needed.

Add on top of that the mistrust that there are some serious shakeups and instabilities with the current direction of Java at this time and lack of faith in the current stewards and owners of old Sun JVM, in Oracle.  Many people do not have faith that Oracle will improve upon Java and lead the direction and there is also fear that the Apache Software Foundation may just throw in the towel.  More and more people are looking to OpenJDK for the future of Java but it just isn't where it needs to be for Enterprise adoption.

Some see all of this as the smell of death as enterprise applications are the leading reasons why Java has historically been the #1 programming language in the world for as long as it has.  This is why Microsoft has been gaining so much ground against Java with .NET technologies.

The non enterprise based Java application developers are turning more and more towards OpenJDK and other open source frameworks to help build their solutions and some are never looking back.  One could say it is a case of too little too late on getting JEE back in the forefront of legitimacy, even though technically JEE can and does stand toe to toe with your comparable Spring application.


答:
For a good start to reading see this wikipedia list. Ideally, you are looking at separation of concerns. While a more general solution has advantages for reuse between projects, there is a problem.

The database is concerned with storing the data, and so it is the job of the database to know what the data is. You don't want a table that can store anything with one field holding the data and one holding the description.

I would follow the rule of representation. The data needs to say what it is, or else it is useless. Only if the data is actually general should it be treated as general.

Finally, worse is better. You aren't going to know everything about generalizing the solution when you first build it. You don't know what is actually required, so building a solution that attempts to do so is far more work for only a marginal gain.

Title: Generalized VS Specialized technical solution; what to take into account?

Body:
We recently had a discussion in the office because of conflicting views between developers. One side (side S) argued technical solutions -generally- need to be a specific as possible, while the other side (side G) argued generalized solutions are preferred.

I'll try to keep it short; we deal with file transfers and we need to start saving three files (log.txt, details.txt, receipt.pdf) for each transfer. We already have a files table that we'll use but we all agree that we need a different table to create a one-to-many relationship between transfers and files.

Side G proposed creating general resource_attachments table that can attach files to any type of resource it would look something like this;

resource_attachments

- id : int

- entityId : int

- entityType : string

- fileId : int

- kind : string

Side S disagreed and proposed creating a specialized transfer_attachments table, something like this;

transfer_attachments

- id : int

- transferId : int

- fileId : int

- kind : string

One argument of side S is that any resource should be as specific as possible so its role and its attributes and their possible values are clear, so any new developer will have no trouble understanding it.

An argument of side G was that a more generalized approach would provide a broader range of functionality; you can attach files to any resource, whatever their role will be.

Though the practical differences are very small, there is some fundamental stuff going on here (this is where it gets philosophical); one person in the room sharply observed that the generalizer is the ruby expert, while the specializer is the java expert. Ruby is an interpreted language with dynamic typing while java is a compiled language with static typing.

I found the matter wildly interesting and was wondering which approach is preferred; specialized or generalized solution, and what matters should be taken into account?

Note that we're only talking about a the technical part of the solution, this has nothing to do with the end-user experience.


答:
My answer ultimately is similar to Péter Török's in that I believe it depends on the additional effort and complexity of implementing the Generalized solution.

Framing this as a implementaiton argument though is a mistake, and labeling the two opposing sides by programming language and defining that in the way they think is dangerously close to creating the stereotype of the logical, forward thinking Ruby developer versus the trollish, stubborn and foolish Java developer.

This shouldn't be a technical discussion in how to fulfill the needs of the client with the added anticipation that clients almost never really know what they want and change their minds frequently, and also expect that when they change their minds it won't result in a major refactoring effort.  This problem isn't so much about seperation of concerns (which is important on its own merits) in my mind, but one of realistic interpretation of reality.

If I am modeling a strict interpretation of the Mayan Calendar and designing and implementing it strictly then I am probably right to be specific in my design.  I am virtually guaranteed that the Mayan calendar will not change, especially seeing as how the Mayan people no longer exist on this Earth.  On the other hand if I am designing a document management system and I am told the only documents they want to store are JPEG files, then I am probably being smart to not design my tables around the specificities of images, because when I demo it, they will probably realize they want to store PDF's as well.  I just created a heck of a lot more work for myself there.

This has nothing to do with language and everything to do with the reality in software development of rapidly changing business requirements and depressingly unreliable clients.


问:
How to write Requirements for a specific module
I am familiar with writing Software Requirements Specification, but not quite sure how to write the requirements for a specific module.

Let's say I need to develop a Reservation System and  there will be a module to perform validation. Now, an SRS is already available for the entire system, but prior to designing(API Specification and Class Diagrams) the Validation module, what would be the format of writing Requirements for this module.

答: A specific model shouldn't require more requirements, a module should complete or be part of the solution to a subset of overall requirements for the project. If you find that a module doesn't work towards fulfilling project requirements, then it,s either unnecessary or your requirements are lacking. Creating modules is part of the design process, requirements should already have been set, if you are trying to make specific requirements for a specific module then you are doing it wrong.</p>


答: Like Ryathal said in his answer, specific components shouldn't have their own requirements. However, it might be a good idea to provide traceability from the system architecture, the component's detailed design, and the implementation details back to the requirement(s) that drove that decision. All the design decisions and functionality implemented should be derived from some requirement of the system.</p>

Title: How to write Requirements for a specific module

Body:
I am familiar with writing Software Requirements Specification, but not quite sure how to write the requirements for a specific module.

Let's say I need to develop a Reservation System and  there will be a module to perform validation. Now, an SRS is already available for the entire system, but prior to designing(API Specification and Class Diagrams) the Validation module, what would be the format of writing Requirements for this module.


答:
EJB has a lot of baggage. Part of that baggage comes from the fact that it was targeted at the wrong audience. The other part was that the first two versions were utter crap.

If you look at the original EJB versions, the design was that an EJB developer could create a packaged solution that could be used within any EJB compliant container. For an in house shop, this level of abstraction was unnecessary. It was a perfect solution to make a thriving market for third party EJB component vendors. However, the Container vendors were overzealous in their marketing and were making tons selling their product as a viable solution for every day development. This would be the equivalent of building all of your application code as COM+ components.

For more of the background on the original J2EE spec, most of the vendors involved had CORBA servers and wanted to leverage those products going forward. The EJB spec was built over the IIOP protocol (actually Java RMI which was a thin layer over IIOP). CORBA had already been rejected because of its complexity, and EJB was just CORBA in disguise so it brought with it many of the problems that CORBA had. Actually, the abstractions of EJB made it more difficult to work with than a pure CORBA implementation would have been.

Once the rubber hit the pavement, people realized that performance with EJB was atrocious. With every call being a remote call and the difficulty of even getting the application up and running correctly to begin with, people quickly looked for alternatives. Hibernate and Spring running in a JSP container became the solution.

EJB 3 "adopted" this approach. But it's still a generic compromise that doesn't provide much benefit. There is still no 3rd party EJB component market so there's really no point in using an EJB container to build your solution.

Long story short. While EJB 3 is a vast improvement over the first two iterations, it still doesn't provide enough benefits to outweigh the costs.

Title: Is Spring + Hibernate prefered instead of EJB 3?

Body:
It is my perception that whenever new JEE projects start (where these technologies would be applicable), people prefer to use a combination of Spring + Hibernate instead of EJB 3.

It seems junior programmers are even advised to go for that instead of EJB.

Is this personal preference or are there pertinent reasons for it? (e.g. personal scars created by earlier EJB versions which caused mistrust in EJB or technology bloat versus performance reasons or learning curve)?


问:
Why is it evil to run selects from a prod server?
I'm basically looking for arguments to persuade the internal "consultants" at work as the following are not working:

What happens if you do a Cartesian join and crash the server?

You don't need to do selects from that server. You have other servers for that.

It's not for you it's for the clients.

We're going to be implementing DB wide triggers to stop casual logging on during work hours but with a fail safe so that devs / DBAs can fix issues if they come up but need some more arguments to forstall the screaming that's probably going to happen.

EDIT
To clarify; there are no actual problems. The database will be locked down better no matter what.

I'm not looking for technical reasons to do things or advice on how to manage a DB. I'm hoping that some other technical people on here have some advice on how to explain to non-technical people the, possibly only perceived, importance of this particular issue.

答:
Do they have somewhere else to test their queries, such as a duplicate of prod, with the same data, but in an isolated test region where they can do whatever they want? They might want to test their code/queries on prod because there's no suitable substitute. And if there's a suitable substitute, can you change the passwords to lock them out? NO one should have prod access except for prod support staff.

I guess the simplest reason is: "The production server is a PRODUCTION server, not a test server, so stop testing your development work on PROD!"

I think your point about testing queries that could have negative impacts on performance of production is a good one. If they don't respect that (and if you can't lock them out), then this more a workplace authority issue, and it might be worth keeping that in mind when it's time for contract renewal.


问:
Need help with clarifying the design of an Android game
I'm going to develop a Kakuro (Cross-Sums) game for Android, and have got the algorithm right.

But I can't seem to get the user-interaction part right- i.e. The puzzle is very large. So only a portion is shown at a time to a user depending on their device (eg: HVGA smartphone vs XGA tablet). It should be scrollable.

To make it more clear, see the images below:

So what I'm asking for: Do you know a suitable method to approach this? I mean, like a design or a structure that will achieve this kind of behavior?

Please note that I'm completely new to game programming and do not know anything about canvases, etc (but have got experience in application development). So any help really appreciated.

答:
In order to solve your problem, you need to think about your game in terms of different "spaces".

First, lets talk about "worldspace". If you pretend that you have an suitably wide and tall device upon which you can do your rendering, you can render the entire grid of cells.

For a more concrete example, if your grid is 100x100 cells, and each cell is 16x16 pixels, you'd need a screen that is 1600x1600 pixels.

If you had such a device, you could easily render the whole thing.

You don't, which is why you are here. The device is only a particular number of pixels wide and tall.  This is your "devicespace".  A smartphone screen will have a different devicespace than a tablet.

If you are ONLY dealing with scrolling, then you need only keep track of a single point that maps one corner (typically the upper left corner) of devicespace into worldspace.  This is an anchor point.

If using something like OpenGL, you can accomplish this quite easily with matrices, but knowing how to do in using just 2d algebra doesn't hurt either.

When you are scrolling around the worldspace, you simply change the anchor point, and re-render the area covered by devicespace, not the whole world (that would be wasteful). Fortunately, with a square grid, it is pretty easy to determine which grid cells need to be rendered, since you take the anchor point, divide by the cell height and widths, and start rendering there, stopping at the opposite corner.

The anchor point has some definite bounds. If it is (0,0) and the upper left corner is being used, the lower right corner is at (devicewidth,deviceheight).

When scrolling, the anchor point needs not go further than (worldwidth-devicewidth,worldheight-deviceheight), and so as a result, this and (0,0) are the bounds for a different type of space called "anchorspace".

To add zooming, there is slightly more to it, but it builds off of the basics here, there is simply one more intermediate space, but for now I'll leave you with the basic of scrolling.

Good luck.


问:
exclamation points in error messages
What do you think about using exclamation points in error messages?  i.e. "The address is not valid!".

Personally, I think it adds nothing, insults the user, and makes the product look like it was written in TRS-80 BASIC by a 12-year-old.

答: They are almost as bad as the word "please" in dialogs. Dump em!</p>

ContentLicense: CC BY-SA 2.5

Title: exclamation points in error messages


问:
Is a JSON-based AJAX checkout safe?
For a mobile e-commerce site, that follows the client-server model, where all the views are json-ajax calls to return data from a secure service, is it safe to also pass the "checkout" process through an ajax call?

The entire site is presented by making json-formatted ajax calls to the service (which is controlled). But because it's using ajax, the calls are easily read in Javascript (or through a http proxy for the transaction). SSL certificate will be installed.

If the service only responds to the site (i.e. lockdown on the IP range) would that make it secure? Are there other considerations? Are there specific security holes to protect against in this setup?

答: Ajax/JSON/XHP/XHR/$insert_stupid_neologism_here is as safe as vanilla HTTP (because it is vanilla HTTP) if and only if the site is secured with SSL and you use a token system to prevent cross site request forgeries.

Title: Is a JSON-based AJAX checkout safe?


问:
When to favor ASP.NET WebForms over MVC
I know that Microsoft has said

ASP.NET MVC is not a replacement for WebForms.

And some developers say WebForms is faster to develop on than MVC.  But I believe speed of coding comes down to comfort level with the technology so I don't want any answers in that vein.

Given that ASP.NET MVC gives a developer more control over their application, why isn't WebForms considered obsolete?  Alternatively, when should I favor WebForms over MVC for new development?

答:
I prefer webforms because my background is windows development.

Speed of developmnt is a key issue, and I can easily pass a problem to someone in india to fix overnight with forms, also, if I have a speed issue on a page, a really good book about asp.net speed is handy (  Rick Kiessig is the man ).

webforms is for ex windows people
mvc is for web people

but, in the modern world, where Rick has written an awesome book, with servers increasing in speed daily and cheap coders in India, well, webforms has the edge

Title: When to favor ASP.NET WebForms over MVC


答:
If not by MVC, maybe you can separate them logical layers and name them as such? GUI, Middleware, DataAccess, Security, etc.

Personally, I would try and follow an architectural pattern or see if your implementation fits any existing pattern. From there you can use their naming structure and go from there.

Title: GUI architecture and class naming advice

Body:
Problem:

I'm working on coding a few light-weight touch-tablet games and often get stuck with difficulties naming my user interaction/interface classes and their relationships with each other (architecture?). I'm rarely satisfied with any of my solutions, thus doubt and change them several times on down the line. For example, I have a board game with these components (among others):

"HUD" - the HUD frames the view of the game world thus enabling user interaction

"boardOverlay" - this is invisible and lies on top of the viewed game world. It  receives and interprets touches, consequently calling methods in "thinger".

"board" - maintains all elements on the board.

"thinger" - the class that gets things done, changes game state. I call it thinger since I dont know what it should be called. Better to have a non-descript name than one that will be misinterpreted.

Searching for enlightenment:

Now I would like to have general/abstract names/architecture for these components which will likely be used in many other games/apps. But I have difficulty coming up with satisfying ones. I have searched the net many a time for guidelines/advice but I find that all of the sources are language/technology/API specific and seldom like their approach.

I don't know the name of this discipline/practice to search for for enlightenment. I have tried "event driven framework", "event driven naming conventions", "GUI architecture", "+oop +GUI +taxonomy"...   on and on .... ....   with no luck.

Question1:

Can anyone provide a resource to enlighten me? A technology independent resource that philosophizes about this type of naming and architecture.

Extra credit question:

It would also be great with a reliable/concise resource discussing practices/disciplines of this context? There are too many different and overlapping usages/interpretations out there. Example: GUI framework, GUI architecture, GUI structure, GUI design - what should the proper usage of these terms be?


答:
If these are external consultants, you shouldn't have to persuade them.

Lock them out.

If, as another poster asked, there is no other "test" database they can use, then arrange to have one setup for them, with data anonymised if necessary.

If you really need a reason for a non-technical person, tell them you do not want a non-technical person potentially writing inefficient queries that may compromise the performance of your DB and surrounding application(s).

Title: Why is it evil to run selects from a prod server?

Body:
I'm basically looking for arguments to persuade the internal "consultants" at work as the following are not working:

What happens if you do a Cartesian join and crash the server?

You don't need to do selects from that server. You have other servers for that.

It's not for you it's for the clients.

We're going to be implementing DB wide triggers to stop casual logging on during work hours but with a fail safe so that devs / DBAs can fix issues if they come up but need some more arguments to forstall the screaming that's probably going to happen.

EDIT
To clarify; there are no actual problems. The database will be locked down better no matter what.

I'm not looking for technical reasons to do things or advice on how to manage a DB. I'm hoping that some other technical people on here have some advice on how to explain to non-technical people the, possibly only perceived, importance of this particular issue.


问:
Not-for-profit universities that offer computer science undergraduate degree online?
There are many masters degree programs in computer science online offered by reputable organizations. However, I've found very few bachelors only degree programs offered by non for-profit institutions.

I am looking for a degree in computer science and also any programs for entrepreneurship/management or algorithmic trading.

I've found only 2 programs so far that fit:

http://www.regis.edu/regis.asp?sctn=cpcis&p1=ap&p2=cs&p3=ol

http://depaul.edu

Requirements:

100% online undergraduate non-profit

Options: Bachelor of Science Bachelor of Arts

Bonuses: accelerated recognized ABET cost effective

Update:
I've answered my question with a list. If anyone knows an online program that combines skills in entrepreneurship (getting capital, starting a business) or algorithmic trading with a computer program that would be ideal.. maybe too much to ask though

答:
The University of South Africa offer both undergraduate and postgraduate degrees in mathematics, computer science, information technology, and all the rest.

There's also the Open University.


问:
Why would a company develop an atmosphere which discourage code comments?
I was taught in university to write comments for our programs. As I write comments, I feel like I have a better organization and understand the programs better.

However, I am in a company where most of the code I encounter doesn't have comments. Why would a programmer not write comments? Are there are any objective reasons? Do you think comments are annoying when you read others' code? I don't write comments either, and I can think of some reasons why not:

Because I can already easily understand the program.

My boss won't care how my program gets the job done.

Nobody is likely to pick up my program after I am gone.

The purpose of comments is usually to include explanations for the program, however, I found that in my company, comments are used to cover obsolete code instead. For example:

```<code>/* Obsolete code */
New code
</code>```

What is your opinion on commenting? Should we do it? Or does it depend on the situation?

答:
Job security is a valid reason.  If no one but you understands the code, you cannot be fired.

Note to those that have not read Sarcasm for Really Smart People: Not correctly commenting code is unprofessional.


答:
I've seem this battle play out innumerable times. It almost always starts with a few novice programmers (usually using Access) querying directly against the back-end databases and creating performance/locking problems.

The most common reaction is for the DBA to just implement martial law and lock everyone out of direct access to the database with the exact same explanations you gave above. This is unfortunate, because it ignores the fact that the people running those queries aren't just doing it for fun or to spite the DBA, these professionals need access to the data to get their jobs done. The problem is that you have application users and back-end data analysts fighting over resources and you need to appease both groups.

I'm not saying you shouldn't lock down the DB, but just that the DBA shouldn't always let the users of the app trump the needs of the analysts. Instead, he/she should work with the analysts to come up with alternative ways to meet their data needs without bringing down the system.

For example:

- Could a reporting tool be used to minimize the need for ad-hoc queries?

- Can a time window where ad-hoc queries are allowed be established to mitigate the damage of an errant query?

- Can the analysts get training from the DBA on best practices to avoid DB killing queries?

- Most DB platforms have a query governor that limits the damage that you can do with long running queries (though it won't help much with locking issues)

 -Can a DB mirror or data warehouse be set up as an alternative to querying the live system?

TL:DR - Don't look at the people killing your DB with their ad-hoc queries as adversaries that must be stopped, but as another class of users that you must find a way to accomodate their business needs and mitigate the risk of performance impact on your system(s).


答:
If the company doesn't require comments in code, most programmers won't comment because of their laziness, and they will find a clever excuse why comments are never necessary.

On the other hand, sometimes the comments are really unnecessary (for example at trivial getters and setters in Java), and if company creates an official comment-writing policy, programmers are at risk that they will be forced to write comments even in such situations. An ambitious manager can also mandate very complicated comment templates.

This results in a situation where some programmers do write comments and silently curse the laziness of their colleagues, but do not risk discussing this topic openly, because things could get worse.

Title: Why would a company develop an atmosphere which discourage code comments?

Body:
I was taught in university to write comments for our programs. As I write comments, I feel like I have a better organization and understand the programs better.

However, I am in a company where most of the code I encounter doesn't have comments. Why would a programmer not write comments? Are there are any objective reasons? Do you think comments are annoying when you read others' code? I don't write comments either, and I can think of some reasons why not:

Because I can already easily understand the program.

My boss won't care how my program gets the job done.

Nobody is likely to pick up my program after I am gone.

The purpose of comments is usually to include explanations for the program, however, I found that in my company, comments are used to cover obsolete code instead. For example:

```<code>/* Obsolete code */
New code
</code>```

What is your opinion on commenting? Should we do it? Or does it depend on the situation?


答:
If you make a new programming language, having a syntax similar with popular existing languages makes learning easier for your new users. Especially if many concepts are similar between languages.

Also I think that C-style syntax is relatively easy to read. To compare with Pascal, using symbols "{" and "}" for blocks of code is more legible than "begin" and "end", which are optically very similar to identifiers. Python is even more legible, but including whitespace in syntax opens a new set of problems with editing. Another example: Lisp and JavaScript share a few ideas, but when the same thing is written in C-style syntax, it is less obscure.

I am sure many people would disagree with the second paragraph, because everyone has their own favourite language, but I think that the popularity of C-style syntax is partially a historical coincidence, but partially it also shows that authors of C made a few good decisions.


问:
Creating Compelling Desktop Application in .NET
I'm about to create an open source desktop application.  I'm primarily a .NET developer , with experience in ASP.NET and SharePoint.  I've created basic Windows Forms applications before, but I have never developed using WPF or Silverlight before.  I want a compelling, highly interactive UI for my desktop application.  What are my technology choices for doing this, using .NET?  In particular, is HTML5 something I should be considering?</p>

答:
Consider WPF.

If you are unfamiliar with WPF, I recommend Windows Presentation Foundation Unleashed.

WPF allows for content in web browsers or standard windows applications.

WPF also is resolution independent - the content on a mobile device has the same crisp look as the content on a 50 inch tv.

Windows Forms is limited when it comes to a highly interactive UI development compared to WPF.


问:
Generic decorator implementation
I have the following pattern, which I would like to implement using some kind
of generic programming, but I do not see how I can do it.

I have an interface I containing many methods with different signatures.
Each method has a return type of some class type and any implementation should return null on failure, or a concrete object on success.

Now I have a concrete implementation A of I, and a decorator class D of A. For each method

```<code>T m(T1 p1, ..., Tn pn)
</code>```

defined by the interface I, the implementation of m in D follows a fixed pattern:

```<code>class D
{
    private A impl = ...;

    ...

    T D.m(t1 p1, t2 p2, ..., tn pn)
    {
        init();

        T result = impl.m(p1, ..., pn);
        if (result != null)
            successCode();
        else
            failureCode();

        return result;
    }
}
</code>```

The calling code uses the decorator as follows:

```<code>I instance = DecoratorFactory.createIDecorator();
T r        = instance.m(p1, ..., pn);
</code>```

Question: Is there a way to implement this kind of decorator in a generic
way (without writing the same boilerplate for each method)?
Can this be done in Java?

If it is not possible to implement this pattern in Java, is there
an elegant way to implement it in another language?

答:
It's not surprising that you couldn't see how to do this in Java.  Java just doesn't support this sort of thing in any reasonable way, so solutions are complex and involve deep magic.  This is a simple problem in dynamic languages.

All that is required is a handler for calls to missing methods, and way to define methods at run-time.

Then the decorator class just defines a missing method handler that will create the wrappers at run-time on the first invocation.  In Ruby this requires about a dozen lines of code.

Title: Generic decorator implementation


答:
I think what you are looking for is a business rules document.  This would define the rules that the system must enforce and follow.  Included in the business rules would be rules as to what is an acceptable reservation.  If you then are building a validation module, its purpose would be to enforce the business rules.

Take a look at http://www.agilemodeling.com/artifacts/businessRule.htm


答:
What you are probably looking for is called Aspect Oriented Programming. It works with the Proxy-Pattern, which is just what you need.

You can create a dynamic proxy for each object and tell that proxy to intercept said calls and perform your logic. All you need is one dynamic proxy class that contains your interception logic. It will wrap around any object you give it and try to perform your logic.

Start to look here:

http://www.javaworld.com/javaworld/jw-11-2000/jw-1110-proxy.html

http://docs.oracle.com/javase/1.3/docs/guide/reflection/proxy.html

http://www.devx.com/Java/Article/21463

http://www.ibm.com/developerworks/java/library/j-jtp08305/index.html

I haven't read that articles, though. Just browse the web for the implementation/library that fits your needs best.

You might also want to check out AspectJ.

Title: Generic decorator implementation

Body:
I have the following pattern, which I would like to implement using some kind
of generic programming, but I do not see how I can do it.

I have an interface I containing many methods with different signatures.
Each method has a return type of some class type and any implementation should return null on failure, or a concrete object on success.

Now I have a concrete implementation A of I, and a decorator class D of A. For each method

```<code>T m(T1 p1, ..., Tn pn)
</code>```

defined by the interface I, the implementation of m in D follows a fixed pattern:

```<code>class D
{
    private A impl = ...;

    ...

    T D.m(t1 p1, t2 p2, ..., tn pn)
    {
        init();

        T result = impl.m(p1, ..., pn);
        if (result != null)
            successCode();
        else
            failureCode();

        return result;
    }
}
</code>```

The calling code uses the decorator as follows:

```<code>I instance = DecoratorFactory.createIDecorator();
T r        = instance.m(p1, ..., pn);
</code>```

Question: Is there a way to implement this kind of decorator in a generic
way (without writing the same boilerplate for each method)?
Can this be done in Java?

If it is not possible to implement this pattern in Java, is there
an elegant way to implement it in another language?


问:
Are High Level Design and Low Level Design documents needed to follow Agile development process?
Our team is developing a project using an Agile development process. All of our requirements are converted into product backlog items and task are broken down based on that. One of my team member suggested to maintain the High Level Document (HLD) and Low Level Document (LLD) for the requirement.

Do we need to have these documents to follow the Agile process?

答:
Short answer no. Agile does not say much about what you must or must not do. It's mostly a set of values and a way of thinking.

However typically written requirements are pretty light in agile processes. Your HLD and LLD documents sounds heavier then what might be common.

Typically backlogs are filled with stories, stories are mostly invitations to have a design discussion. After a discussion some notes may be written down, some acceptance criteria worked out. But it's all pretty informal on a need to have basis.


问:
Saving mobile application data when no service?
Say I have a mobile application that allows users to enter information which is then uploaded to a central location.  I had planned on building this using only HTML5 and javascript (non-native app), but I'm assuming if someone is in an area where there is no service they simply will not be able to use the app.

As a work around would it be possible to write a native app that saves the information on the device and then uploads it whenever service returns?  If so, is it possible to write a native app entirely in HTML5 and Javascript that does this?

答:
HTML 5 has a local storage feature Check that out.

It's can only store up to 5 meg (on most browsers), If that's not enough you will have no choice to with a native App.

Edit as more info is needed.

Basically there is 2 parts to this:

1) Manifest file This tells the Browser what files need to be stored locally for the web app to work offline. (Basically html and JS files)

2) HTML5 Local storage: Think of this like a local db the can be access by JavaScript.

So when a user visits your site (while online), the browser sees the manifest file and stores ALL the source files your app need to work in Offline Mode as specified in the Manifest. (of course no server side code can work offline, so this is all html and JS)

Also while your user is online, you save all the data he needs to local storage, any changes made while online needs to be updated your server and Local storage.

When offline, your user has access to all the html and JS he need to run his app, he also has access to the HTMl5 Local storage. He can do what ever he wants (whatever you coded for him to be able to do offline). All updates as saved to the local storge.

Once back online, he visits your site again, you see he made changes offline and you sync up the local storage with the server.

Check out this demo
and read this Entire book


答:
No, Agile does not call for the need of HLD (or SRS, business requirements) document or LLD (or technical specification) to be associated with User Stories.  These documents would be highly encouraged for the Waterfall process however.

Simply because Agile does not call for this doesn't mean that it shouldn't exist though.  They are not mutually exclusive.  One can theoretically manage an Agile project and still demand HLD and LLD documents however the case should be made if these documents bring value to the stakeholders.

It is highly encouraged in Agile to only do tasks that bring value to the stakeholder and most would argue these documents do not do this.  They may bring value to the architects or to the developer, but the users and other stakeholders likely do not care about such things unless they specifically require them as deliverables.

Title: Are High Level Design and Low Level Design documents needed to follow Agile development process?

Body:
Our team is developing a project using an Agile development process. All of our requirements are converted into product backlog items and task are broken down based on that. One of my team member suggested to maintain the High Level Document (HLD) and Low Level Document (LLD) for the requirement.

Do we need to have these documents to follow the Agile process?


答: If you are a publicly traded company (or plan to be), it is a violation of Sarbanes-Oxley requirements (in particular, section 404) for developers to have direct access to production data. If the users have sufficient access to be running select queries, they almost certainly have permissions to be tampering with data.  </p>


答:
On error messages meant to be displayed to the user?  Yeah, I'm with you.  Anything that makes the user feel like their machine is yelling at them for being an idiot should be filed under "Bad Idea."

But, error messages to be sent to the log file, particularly on the server?  I know you're supposed to still maintain a sense of professionalism, because those can still wind up on the user's screen.  But I gotta admit, snarking it up is awfully tempting....

Title: exclamation points in error messages

Body:
What do you think about using exclamation points in error messages?  i.e. "The address is not valid!".

Personally, I think it adds nothing, insults the user, and makes the product look like it was written in TRS-80 BASIC by a 12-year-old.


问:
Is the architecture of my project a common one? What's its name?
I am responsible for a software project for a few years now (a Java desktop application, which is mostly event-driven). I started it from scratch, and at the beginning of this project I made some strong choices on the architecture of the software.

My architecture

I introduced the Module class, which represents a functionnal part of the application, with a well-defined responsability. The only thing a Module exposes to the world is a set of "communication handles". There are 4 types of communication handles :

an Emitter<T> can emit a message of type T.

a Handler<T> can receive a message of type T

a Puller<R, Q> can make a query represented by a message of type Q, and will receive a response message of type R

a PullServer<R, Q> can receive a query represented by a message of type Q and will send back a response message of type R.

Then, at the beginning of the execution of the application, I instanciate all the modules that compose the application, and I set up all the connections between them. An Emitter can be linked to one or many Handlers, and a PullServer can serve one or many Pullers (the types of these two endpoints must be compatible, of course).

All the classes used to represent a message are immutable, and are defined in one subproject. Every Module depends on that subproject, and nothing more. This makes the Modules very decoupled (a Module knows nothing about the other Modules, and their input/output to the outside world very clear). Also, the dynamic aspect of the application (the dataflow) is defined in a unique place, in the main function. Also, it is super easy to test a Module, we just have to provide fake Emitters and PullServers, and plug it to the Module's Handlers and Pullers.

My thoughts on this architecture

So, this is the first "big" software project I work on, and I made up this design because it felt like the right thing to do. Now, the project is working just fine, with a total of 57 Modules working together.

One of my co-worker, who joined the project recently, asked me if this was a common architecture, if there was a name for such a design. I don't have an answer, since I am not really familiar with other real-world software architectures.

It seems to me that this design is close the the concept of Actors, that we can find in languages such as Scala (and maybe Erlang). However, Actors do not provide the decoupling provided by my design. And Actors have an additional capability : each Actor has its own message queue, and its own thread of execution (kind of).

Also, I think my design is somewhat related to the Dependency Injection pattern, in the sense that dependencies between the Modules are defined in a central place. However, this pattern deals with interfaces, not with messages. It does not define how the modules communicate (notification, request/response).

The question (finally !)

Do you know of a software project that's architecture is similar to mine? Is there a name for that?

Edit

@Doc Brown suggests that this design is similar to the Flow Design. I cannot agree more. Here is a one to one comparision between those two designs :

My Module is the same thing as a Functionnal Unit.

My Emitter/Handler are the same as the Output-pin/Input-pin, except mine don't have a name. In my design, the "communication handles" are only identified by their types.

The connections between my Modules is the equivalent of their wires.

My Puller/PullServer is similar to their Dependency relations. However, they say there is an explicit dependency from the caller to the callee. In my design they are decoupled.

They define the concept of Boards. That's interesting, I think I'll borrow this idea !

They define the concept of Configuration. I do have the need for configuring a Module in my program, and for that I define a configuration Handler on some of my Modules.

Both solutions are synchronous.

I don't have the concept of map and join. But I don't feel the need for it.

Well found, Doc !

答: Seems like event-driven architecture, but I don't know of any examples exactly like what you are doing.  Is your co-worker asking out of curiosity or could it be a veiled criticism (i.e. why did you do things in this way)?</p>


答: If you have incompetent employees or consultants who can't be trusted not to run a multimillion record cartesion join on prod, then fire them. </p>


问:
How can one manage thousands of IF...THEN...ELSE rules?
I am considering building an application, which, at its core, would consist of thousands of if...then...else statements. The purpose of the application is to be able to predict how cows move around in any landscape. They are affected by things like the sun, wind, food source, sudden events etc.

How can such an application be managed? I imagine that after a few hundred IF-statements, it would be as good as unpredictable how the program would react and debugging what lead to a certain reaction would mean that one would have to traverse the whole IF-statement tree every time.

I have read a bit about rules engines, but I do not see how they would get around this complexity.

答:
The problem is not one well solved by "rules", whether described by "if-then" procedural code or the numerous rules solutions devised for business applications. Machine learning provides a number of mechanisms for modeling such scenarios.

Fundamentally, one has to formulate some scheme for descrete representation of the factors (e.g., sun, wind, food source, sudden events, etc) influencing the "system" (i.e., cows in a pasture). Notwithstanding the misguided belief that one can create a real valued functional representation, as opposed to discrete, no computer in the real world (including the human nervous system) is real value based or computes based on real values.

Once you have your numerical representation for the relevant factors you can construct any of several mathematical models. I would suggest a bipartite graph where one set of nodes represents cows and the other some unit area of pasture. A cow at any instance occupies some unit area of pasture. For each cow there then exists a utility value associated with the current and all other units of pasture. If the model presupposes the cow seeks to optimize (whatever such means to the cow) the utility value of its unit of pasture, then cows will move from unit to unit in effort to optimize.

A cellular automate works well for executing the model. The underlying mathematics in the real valued math world motivating cow moverment is a field gradient model. Cows move from positions of perceived lower utility value to positions of perceived higher utility value.

If one injects environmental change into the system then it will not move to a steady state solution of cow positioning. It will also become a model to which aspects of game theory could be applied; not that such would necessarily add much to this case.

The advantage here is slaughter cows or acquiring new cows can be readily managed by subtracting and adding "cow" cells to the bipartite graph, while the model is running.


问:
Sprint planning and accommodating slack
After reading Tom DeMarco's Slack, I'm wondering how to factor slack into sprints.

For those who haven't read the book, TDM describes 'slack' as providing time for innovation and other good things.

Scrum leans towards eliminating slack and resisting change within the sprint. Allowing stories to be re-prioritised between sprints. I appreciate the purpose of a sprint, and am not trying to ask how to respond to change within them.

My initial thought about adding slack to sprints would be to plan a sprint with 8/9 days of work for a two week sprint. If you're conscious of this decision, can still calculate your velocity accurately? Based on story points completed in your 8/9 day window (vs 10).

Conversely, these are two competing ideas and don't belong together... ?

gnat's focus factor link is interesting.

答:
Scrum leans towards eliminating slack

Yes and No.

Scrum forces you to make an intelligent "time for innovation and other good things".

"Other good things" are what retrospectives and daily stand ups are for.

"innovation" is what technology spikes or spike solutions are for.

They don't go away.  They aren't buried.

They become first-class, highly-valued parts of the process.

Being responsive to change -- with one small constraint -- is the whole point of an Agile method and scrum in particular.

The one small constraint (wait until the end of the sprint) doesn't require building in slack time or otherwise tinkering with scrum or the development team.

It's easy to be responsive (by waiting until the end of the sprint) without building in needless overheads.

Innovation is supported through spike solutions.

Other Good Things are supported through daily stand ups and retrospectives.

Title: Sprint planning and accommodating slack


问:
What's your favourite quote about programming?
What's your favourite quote about programming?

One quote per answer, and please check for duplicates before posting!

答:
Software is hard.

-- Donald Knuth

LastEditorDisplayName: Roger Pate

Body:
Software is hard.

-- Donald Knuth


问:
Logistically, how do you manage embedded SQL?
My current application is running into issues with its ORM, and we're relying on some pretty hairy SQL to express queries that the ORM can't.  Are there best practices in terms of how to manage the SQL queries?  For example, where do these usually live in relation to other parts of the code?  Are they in separate .sql files, or do you edit them directly in your other source files?  If the latter, does your IDE (or editor) allow syntax highlighting?  Are there schemes for Vim or Eclipse which will perform SQL syntax highlighting given a set of tags (like #begin sql and #end sql, or something similar?)

答: For those cases I normally create a stored procedure, in great part because what you just mentioned - I have the database to check syntax and I can use its tools to edit it, and I can also test it. </p>


答: Definitely the route to go here is stored procedures. You might be able to maintain discipline for a while with embedded SQL, but IMO this always breaks down eventually. All it takes is someone going in to modify something a year or two from now and leaving SQL injection vulnerabilities everywhere, which is particularly easy to do with embedded SQL. </p>

Title: Logistically, how do you manage embedded SQL?

Body: My current application is running into issues with its ORM, and we're relying on some pretty hairy SQL to express queries that the ORM can't.  Are there best practices in terms of how to manage the SQL queries?  For example, where do these usually live in relation to other parts of the code?  Are they in separate .sql files, or do you edit them directly in your other source files?  If the latter, does your IDE (or editor) allow syntax highlighting?  Are there schemes for Vim or Eclipse which will perform SQL syntax highlighting given a set of tags (like #begin sql and #end sql, or something similar?)


答:
If you don't like SP's you can always use a View.
So your SQL is stored in the DB.

You can create an Entity in your ORM based on your view's data structure.

See this link to the MySQL docs.


答:
"Flow Design" or "Flow Orientation" is what you are looking for, read this

Link

The german software engineer Ralf Westfal has written a lot of articles about this style of software design, especially in the form of "Event based components". His german blog contains some more pointers to other articles (most of them in german).

Title: Is the architecture of my project a common one? What's its name?

Body:
I am responsible for a software project for a few years now (a Java desktop application, which is mostly event-driven). I started it from scratch, and at the beginning of this project I made some strong choices on the architecture of the software.

My architecture

I introduced the Module class, which represents a functionnal part of the application, with a well-defined responsability. The only thing a Module exposes to the world is a set of "communication handles". There are 4 types of communication handles :

an Emitter<T> can emit a message of type T.

a Handler<T> can receive a message of type T

a Puller<R, Q> can make a query represented by a message of type Q, and will receive a response message of type R

a PullServer<R, Q> can receive a query represented by a message of type Q and will send back a response message of type R.

Then, at the beginning of the execution of the application, I instanciate all the modules that compose the application, and I set up all the connections between them. An Emitter can be linked to one or many Handlers, and a PullServer can serve one or many Pullers (the types of these two endpoints must be compatible, of course).

All the classes used to represent a message are immutable, and are defined in one subproject. Every Module depends on that subproject, and nothing more. This makes the Modules very decoupled (a Module knows nothing about the other Modules, and their input/output to the outside world very clear). Also, the dynamic aspect of the application (the dataflow) is defined in a unique place, in the main function. Also, it is super easy to test a Module, we just have to provide fake Emitters and PullServers, and plug it to the Module's Handlers and Pullers.

My thoughts on this architecture

So, this is the first "big" software project I work on, and I made up this design because it felt like the right thing to do. Now, the project is working just fine, with a total of 57 Modules working together.

One of my co-worker, who joined the project recently, asked me if this was a common architecture, if there was a name for such a design. I don't have an answer, since I am not really familiar with other real-world software architectures.

It seems to me that this design is close the the concept of Actors, that we can find in languages such as Scala (and maybe Erlang). However, Actors do not provide the decoupling provided by my design. And Actors have an additional capability : each Actor has its own message queue, and its own thread of execution (kind of).

Also, I think my design is somewhat related to the Dependency Injection pattern, in the sense that dependencies between the Modules are defined in a central place. However, this pattern deals with interfaces, not with messages. It does not define how the modules communicate (notification, request/response).

The question (finally !)

Do you know of a software project that's architecture is similar to mine? Is there a name for that?

Edit

@Doc Brown suggests that this design is similar to the Flow Design. I cannot agree more. Here is a one to one comparision between those two designs :

My Module is the same thing as a Functionnal Unit.

My Emitter/Handler are the same as the Output-pin/Input-pin, except mine don't have a name. In my design, the "communication handles" are only identified by their types.

The connections between my Modules is the equivalent of their wires.

My Puller/PullServer is similar to their Dependency relations. However, they say there is an explicit dependency from the caller to the callee. In my design they are decoupled.

They define the concept of Boards. That's interesting, I think I'll borrow this idea !

They define the concept of Configuration. I do have the need for configuring a Module in my program, and for that I define a configuration Handler on some of my Modules.

Both solutions are synchronous.

I don't have the concept of map and join. But I don't feel the need for it.

Well found, Doc !


问:
How do you approach database design?
I am primarily a web developer and I have a couple of personal projects which I want to kick off.

One thing that is bugging me is database design. I have gone through in school db normalization and stuff like that but it has been a couple of years ago and I have never had experience with relational database design except for school.

So how you do you approach database from a web app perspective? How do you begin and what do you look out for? What are flags for caution?

答:
Few things not explicitly stated so far by other fellows:

It is best to have the database design done by someone who's professional. It is OK to learn of course, but I would not suggest building a medium or large model if one is not well versed in modeling or database design. The reason for this is that the cost of a wrong design is usually very high.

Know the system objectives and user requirements well.
Without knowing the requirements you can't design the correct data model.

Know which code to do in programs and which code to let the DB take care of.
This is required so that you set the data column's null, not null, etc. properly. This is also required so that you specify your RI correctly.

Determine your primary keys well. Go for simple keys when you can.

Consider integration needs with other applications.

Consider using universal data models and follow industry standards in naming and data column size.

Think of future needs (when known and when applicable)

Have your mode reviewed by others.

Use a tool for modeling - Either an ERD tool or a UML tool.

Review and understand generated DDL code. Don't take it for granted.

Title: How do you approach database design?


答: As other said, you are using event-driven architecture, and it looks like you are using some kind of observer pattern or signal/slots to announce/handle events.</p>


答:
I'd typically vote against stored procs or views unless you've got a great database build and migration system in place -- it is just too easy to get things out of synch.

Insofar as how to store them in your code, typically I'd vote they travel with the appropriate classes that are touching the database and executing the SQL. I don't see any downside to having the queries reside in the normal source so long as you don't have SQL strewn all over the place in your codebase.


答:
If you're using version control and some kind of compare tool you should be able to easily see if someone changes any embedded sql when they check something in. And if something breaks you should also be able to easily find which checkin had the changed code. You may be able to establish some practice of putting sql in variables so it is all defined at the top of your program - or something like that - just to make it easier to check.

I've found mysql to be difficult with SPs, especially where you are dependent on a hoster or isp who may not even providing everything that mysql could do. Otherwise I'm all for SPs, but you should be able to get control of your embedded sql.