问:
How concerned should a new programmer be with the various licenses (GPL, Apache, etc)
I'm pretty new to programming, and I've just started using GitHub to store and hold my source code (I keep losing stuff stored locally). As it stands all that's in there right now are source code files, nothing more, but I expect that to change as time goes on and I get better at this. Given that all the repositories in the free accounts are public, how much do I need to worry about licensing? </p>

<p>Would I be fine with just downloading a copy of the GPL, placing a copyright notice in the Readme and calling it a day? I'm fully aware that people can download and modify my stuff, and I'm OK with that, but I at least want to ensure that I get credit for my work should they decide to do so. </p>

答:
Since the repositories are public, it is especially important to put a license on your source code. By default, all works are "all rights reserved", so anyone who finds your repository is not allowed to do anything beyond read it.

If you are okay with the terms of the GPL it is very easy to apply the license to your program. Simply follow these guidelines from the FSF. In addition to putting a license file in the project, they also advise adding a copyright notice and your contact information to each file and including an option in the program to display license information.

If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms.

To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the “copyright” line and a pointer to where the full notice is found.

       Copyright (C)

This program is free software: you can redistribute it and/or modify
        it under the terms of the GNU General Public License as published by
        the Free Software Foundation, either version 3 of the License, or
        (at your option) any later version.

This program is distributed in the hope that it will be useful,
        but WITHOUT ANY WARRANTY; without even the implied warranty of
        MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
        GNU General Public License for more details.

You should have received a copy of the GNU General Public License
        along with this program.  If not, see http://www.gnu.org/licenses/.

Also add information on how to contact you by electronic and paper mail.

If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode:

  Copyright (C)
        This program comes with ABSOLUTELY NO WARRANTY; for details type show w'.
        This is free software, and you are welcome to redistribute it
        under certain conditions; typeshow c' for details.

The hypothetical commands show w' andshow c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an “about box”.

You should also get your employer (if you work as a programmer) or school, if any, to sign a “copyright disclaimer” for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see http://www.gnu.org/licenses/.

The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read http://www.gnu.org/philosophy/why-not-lgpl.html.


问:
How do you organize your local development environment?

Possible Duplicate:

  How do you organize your projects folders?

I'm interested to learn how everyone keeps their local development projects organized in a logical manner. What do you do to keep your dev projects organized in a manner that allows you to easily find things?

答:
i use a structure similar to Bob's but i also have a separate root for documents with projects and admin folders. I don't like mixing dead trees and code in the same hierarchy.

[yes, i know it's two places to back up; i find the convenience worthwhile]

ContentLicense: CC BY-SA 2.5


答:
TL;DR: yes, you should be concerned about licenses, unless you agree to give your code away; the latter is perfectly valid.

If you choose GPL from the start, you're relatively fine, since you yourself will not be bound by it and will be able to re-license your code under different terms.

OTOH if you accept substantial chunks of GPL code by other developers into your project, you'd have to get their agreement if you were ever to re-license the whole codebase. This can become quite problematic.

If you start with a less-binding license, like MIT or BSD, you'll be able to fork your code into a GPL or commercial product, since these licenses allow whatever use (they mostly limit authors' liability). Note that parts which were under MIT/BSD license before relicensing under GPL will stay under MIT/BSD afterwards (for all I know).

GPL also has a well-known limitation: if you statically link GPL code to other software, that other software must be licensed under GPL, too. LGPL lifts this restriction for library code, so if you're developing a library, consider LGPL before GPL.

If you want to forget about licenses completely, you can offer your code as public domain: absolutely zero strings attached, and zero liability. Some projects, notably SQLite, thrive in such circumstances.

ContentLicense: CC BY-SA 3.0

Title: How concerned should a new programmer be with the various licenses (GPL, Apache, etc)

Body:
I'm pretty new to programming, and I've just started using GitHub to store and hold my source code (I keep losing stuff stored locally). As it stands all that's in there right now are source code files, nothing more, but I expect that to change as time goes on and I get better at this. Given that all the repositories in the free accounts are public, how much do I need to worry about licensing? </p>

<p>Would I be fine with just downloading a copy of the GPL, placing a copyright notice in the Readme and calling it a day? I'm fully aware that people can download and modify my stuff, and I'm OK with that, but I at least want to ensure that I get credit for my work should they decide to do so. </p>


问:
Could we set priorities only relative to each other instead of fixed numbers?
AFAIK the lowest priority has the highest number in scheduling and in my system all priorities must be different. But isn't other policies thinkable? For instance, how about a policy where priorities are not numbers but say that a task's priority would be defined only in term of another task's priority, and that other task would be the closest in priority to the task whose priority we are setting. Then we would never use actual numbers for priorities, but we would keep a data structure sorting the tasks in priorities and when a task comes as new or is getting a different priority assigned, then this structure is rebalanced. Would this priority mechanism be feasible or do you not agree that it's a working idea? </p>

答:
Why is it needed?  There's nothing from stopping you from designing a super-flexible priority system but, unless it's actually solving a real problem, adding the additional complexity to something as performance critical as the scheduler is going to be a hard sell.

A simpler solution would be to put a daemon in userspace that can periodically tell the kernel to update the priorities of running processes as new relationships get put in place.  This would keep the kernel-space scheduling code simple & efficient while allowing you all the flexibility you need.


答:
Two main points to start with:

Licensing != Copyright (read as "licensing is not equal to copyright")

(Software) Licensing refers to how others may use the code and / or binaries.  "Others" means people who don't own the copyright to the code.

Copyright refers to who owns the code.  Check out the Berne Convention for a modest primer on copyright.  In this case, since you wrote it then it's your code and you own the copyright to it.  Copyright can quickly become thorny depending upon employment, contract, IP agreements, etc...

If you post your code publicly, some people will steal it (if it's any good).  And that's regardless of the license you place on the code.  Most people, however, will honor the license you place on your code.  If you use a particularly onerous license though, then more people will be tempted to steal it.

GPL tends to be more onerous than others like BSD, MIT, Apache, etc... But that's a matter of personal opinion.  Commercial / for-sale licenses are even more onerous.

To answer your direct questions:

No, you don't need to worry too much about licensing your code at this point.  It's unlikely that your early code will be of significant value to others, so no one else will be able to use it.  And that's not a slight on you, we all started from the same place.

As you get more experienced and your code quality improves, then yes, you'll need to worry about licensing.  Why?  Because others will want to use your code.

You do need to worry about the licenses of other projects that you may incorporate into yours.  First, their license may or may not permit you to use it the way you want to. Second, they may have picked a viral license like the GPL which will force your project to be GPL.  That may be okay, that may not be.

I would discourage a knee-jerk "slap GPL on everything" type reaction to licensing.  GPL has some persistent aspects that may discourage others from wanting to use your code.  And the terms of the GPL may not meet your future needs very well.

For now, I would stick with "all rights reserved" for your (non-)license and focus on getting better at coding.  Worry about licensing when others will want to use your code.


问:
C# Design for SQL connection and commands
Currently I'm working on system that works with database, and I would like to have it done elegant way. So I have abstracted DBConnection into one class, DBCommands into another class. (DBCommands : DBConnection)

There is also a class SQLUsage in which I'm creating new thread that works in a loop, it checks all the time if there's any object in BlockingCollection to take care of, if there is that thread is processing it, and it uses DBConnection and DBCommands for it. I am having a problem accesing DBCommands from SQLUsage, since the DBCommands object is created in DBConnection (I have to pass MySqlConnection object into DBCommands)

Is that good solution? Or I should change the design, I would like to use those classes in another app as well (part of same, bigger system).

I'll tell you bit more about this app. It is a server app that handles connections from multiple clients. Each client sends some info to server, that is stored in BlockingCollection<thatinfo>. Another thread is using items from BlockingCollection<thatinfo> to communicate with mysql server, and insert some data to it, according to objects<thatinfo>.

And I'm having problem with design. So far I have a main class, class for handling TCP/IP connections, thatinfo class, SQLUsage, DBConnection and DBCommands class.

Since BlockingCollection is initiated in main class and it is passed to both TCP/IP handling class and SQL Handling class it is not a problem. My problem is to properly design SQLHandling classes. I want it to be done in elegant way.

So I figured out it would be good to abstract connection and commands from the class where I process the info. So I already have working SQLConnection class, I had some commands in it as well and it worked. But next step was to abstract commands in another class, since there will be many overloaded methods (for example Insert with 1 arg, Insert with 2 args etc.)

So my question is not about the code, I know how to create it, it's more about design. If abstracting sql commands in another class was good idea or not? Should both DBConnection and DBCommands inherit from SQLHandling class? or only DBConnection : DBCommands ?

And another question, probably easier to answer, is there more elegant way to do sql commands than just overloading methods? Like 1 universal INSERT method that handles all arguments?

For now having few overloaded insert methods seems to be a good idea since in this app I'm working on, there will be only 2 different kinds of inserts (just different amount of arguments), but in another app I wanted use the same classes I could really use universal Insert method.

答:
I don't see a really answerable question in there anywhere, but I can at least address some general concerns here. Over the years I've noticed a few common mistakes in this area. I'll list them below, in hopes of helping you avoid them:

Re-using the same SqlConnection object.  It's counter-intuitive, but .Net is designed such that it's more effective in most cases to create a new DbConnection object for each call to the database. Of course there are exceptions, but if you find yourself wanting to keep re-using a single shared DbConnection, you'll have problems. It's worth noting that this is thanks to a connection pooling feature that is implemented by the provider, and that some providers may do this differently... however, most of the major providers do implement connection pooling, such that this does hold.

Failing to properly close your database connections. Since we're now creating a new DbConnection object for each query, it's important that we also close all these connections. Failure to do so can result in locking the database for new access... effectively creating a denial of service situation. Often, someone will remember to call .Close() for each of their connections, but they will forget that if the .Close() is not correctly placed in a finally block, an exception could cause this call to never be executed. You must ensure your .Close() calls are placed within a finally block, and the easiest way to do this in .Net is with a using block.

Methods that accept only sql command strings. Often there will be method somewhere that accepts an sql string, and returns a DataSet, DataTable, or even DbDataReader (fwiw, my preference is an IEnumerable<IDataRecord>). Perhaps this is paired with a similar method that updates the database. The problem with these methods is that, if they accept only an sql string as input, they practically force you to write code that will be horribly vulnerable to Sql Injection attacks. The idea of running all your sql through a common place is on the right track, but it's missing an important piece: these methods must also provide a way to accept sql parameter data that is separate from the sql command string. There are a number of ways to do this, so picking a particular best one is outside the scope of this post. The one piece of additional advice I can give is to avoid overloading the method to not require this if there really are no parameters for a query. That overload tends to get abused, resulting in security holes. IMO, it's better to force callers to explicitly pass some kind of construct with zero query parameters, and thus ensure at least some familiarity with the concept.

Formatting a date string for a call to a database. If you're trying to format a date for use in an sql query, you're doing something wrong. Date values in the database should use a datetime type for the column. Sql Server has several available, including datetime, date, and datetime2, and these types are typical of other databases. When sending date information to the database as part of a query, make sure to use a query parameter that is explicitly typed to the matching type in the SqlDbType enumeration, and assign a .Net DateTime type to the parameter value. String dates should never enter into it. This leads nicely to the next item...

Allowing .Net to try to guess your parameter types. I often see examples posted that demonstrate the SqlParameterCollection.AddWithValue() method, and I'm not a fan. When you use this method, .Net will try to infer the type of your parameter. Frankly, there are several situations where it's just not very good. Using strings as dates is one example. Choosing NVarChar when it should choose VarChar is another. Choosing the wrong length for a VarChar/NVarChar is a third. Any of these can be overcome, and most of the time the query will still work... but it can also fail in unexpected places, and worse, those failures will be in production, rather than during testing. Additionally, sometimes a type mismatch can result in per-row conversions in computing a results set, which can slow things down considerably. Or a type mismatch can result in the database failing to use an obvious important index for a query, making the query take orders of magnitudes longer than it should. Better to favor the SqlParameterCollection.Add() method that asks you to give it an explicit parameter type. Again, this is provider-specific, but most providers make these two methods available.

Public methods that ask for an sql command string. As I said earlier, forcing all database through a handful of methods is a good thing... but to make sure this is enforced, those methods need to be private. My data layers will typically have one method for data retrieval, one that only makes changes (insert, update, delete), and maybe one more that returns multiple result sets in the same call (SqlDataReader can do this, though it often isn't used). However, these methods should be private. What you want for the public-facing part of your data layer is one public method per query, and these many public methods then call into the few private methods to complete their tasks. Instead of asking for an sql command, the public methods ask for typed arguments that match the parameters that will be used with the query. These types should most-often be .Net basic types, like int, string, and DateTime, to avoid mixing data and business layers, though occasionally asking for a complicated business object may be expedient... not the purest design, but sometimes sullying the pure design can be okay in the name of less code, DRY, and YAGNI.

OwnerDisplayName: Lichoniespi

OwnerDisplayName: Joel Coehoorn


问:
Coding convention question about AS3 duplicate variable definition
AS3's got some awkward rules about variable scope, due to its use of hoisting.  I don't like pointlessly leaving a bunch of compiler warnings lying around, but it's more important to me for my code to readable and properly written, regardless.  This produces a couple of duplicate variable definition warnings:

```<code>    private function arrangeElementsLine(pElementSize:Dimensions):void
    {
        if (m_eOrientation == HORIZONTAL)
        {
            for (var i:uint = 0; i < target.numElements; i++)
            {
                var layoutElement:ILayoutElement = target.getElementAt(i);
                layoutElement.setLayoutBoundsSize(pElementSize.x, pElementSize.y);
                layoutElement.setLayoutBoundsPosition(pElementSize.x * i, 0);
            }
        }
        else
        {
            for (var i:uint = 0; i < target.numElements; i++)
            {
                var layoutElement:ILayoutElement = target.getElementAt(i);
                layoutElement.setLayoutBoundsSize(pElementSize.x, pElementSize.y);
                layoutElement.setLayoutBoundsPosition(0, pElementSize.y * i);
            }
        }
    }
</code>```

Is it generally considered to be better and more conventional to remove the redundant var and :<type> syntax for i and layoutElement in the second for loop, or is it more proper to just leave them in there (due to the way their usage is isolated to those two for loops)?  Thanks!

EDIT

This was asked a while back, but when I asked this, part of what I was working on was making something run more efficiently; so I put if outside of any for statements and avoided method calls inside the for statements.

答:
Instead of using the same variable, make them unique by putting more of their purpose into their names:

```<code>var horizontalLayoutElement:ILayoutElement = target.getElementAt(i);
...
var verticalLayoutElement:ILayoutElement = target.getElementAt(i);
</code>```

or if you don't like such long variable names:

```<code>var hLayoutElement:ILayoutElement = target.getElementAt(i);
...
var vLayoutElement:ILayoutElement = target.getElementAt(i);
</code>```

You can also emulate hoisting by putting all your variables declarations at the top of your functions, but since this makes code much harder to read due to the distance in code between declaration and usage, I would avoid it.

Body:
Instead of using the same variable, make them unique by putting more of their purpose into their names:

var horizontalLayoutElement:ILayoutElement = target.getElementAt(i);
...
var verticalLayoutElement:ILayoutElement = target.getElementAt(i);

or if you don't like such long variable names:

var hLayoutElement:ILayoutElement = target.getElementAt(i);
...
var vLayoutElement:ILayoutElement = target.getElementAt(i);

You can also emulate hoisting by putting all your variables declarations at the top of your functions, but since this makes code much harder to read due to the distance in code between declaration and usage, I would avoid it.


问:
The Agile process: how and what should be documented?
A while ago the company I work for had outsourced a development project to a third party. They employed agile practices in developing the solution. However when asked for documentation they would just say it was required as it was incorporated in a wiki or as part of their sprints.

They did leave at the completion of the project, with all but one of the project team. The project wiki site has now been closed down once the yearly subscription was due.

When they left they took most of the knowledge and understanding of what was developed with them.

So I do have 2 main questions;

Is this normal for agile or just an excuse for not wanting to write it?

What are the industry norm for documentation in agile projects to record development
requirements, designs, key decisions and context?

答: There should be some description of the features, user stories, and test cases somewhere, at minimum. IT might be in ReadMe files in the projects, it might be in the source-code comments, it might be in design documents; it might be all of the above... or it might be MIA!


问:
What are the advantages of converting empty strings to evaluate to true as compared to false?
When converting a string to a boolean, what are the advantages of having a programming language evaluate an empty string as true and what are the advantages of having it evaluate it to false?</p>

答:
Consider this pseudo-code:

```<code>print "First name: " + firstname
if middlename:
  print "Middle name: " + middlename
print "Last name: " + lastname
</code>```

This and many related cases is where "empty string is false-ish" is useful. Keep in mind that direct evaluation of non-boolean values as boolean is usually restricted to script-ish languages that where build with user interfaces in mind.

Body:
Consider this pseudo-code:

print "First name: " + firstname
if middlename:
  print "Middle name: " + middlename
print "Last name: " + lastname

This and many related cases is where "empty string is false-ish" is useful. Keep in mind that direct evaluation of non-boolean values as boolean is usually restricted to script-ish languages that where build with user interfaces in mind.


答:
In the context of JavaScript (I'm guessing this is what generated the question), an empty string evalutes to false in a boolean context because it allows you to use the pattern if (str). If an empty string didn't evaluate to false (along with other states like null or undefined), you would have to do the following: if (typeof str !== "undefined" && str != null && str !== "").

This is far more verbose.

An alternate interpretation is that the default state of a primitive evaluates to false. For booleans, this is false. For integers, this is 0. For strings, that would be an empty string. Conceptually, there's no guarantee of nulls existing in a given type system, a value should have a default state.

Title: What are the advantages of converting empty strings to evaluate to true as compared to false?

Body: When converting a string to a boolean, what are the advantages of having a programming language evaluate an empty string as true and what are the advantages of having it evaluate it to false?</p>


答:
Converting a string to boolean true or false and other implicit conversions are charterized thusly...

The advantages: possibly more succinct,clever looking code; possibly some more fluidity and expressiveness when writing code quickly; maybe good for quick and loose prototypeing or scripting

are easily outweighted by the

Disadvantages: confusing, lacking portability, reduces maintainability, and verges on intentional obfuscation

Because

Hiding complexity behind built-in 'tricks' of each language is clever at first and devastating later. if the subject is complex, like str can be undefined type, str can be null, str can be defined, not null, but blank, YOU the programmer must be explicit how you want deal with this. at the point of usage. not buried in some docs on the JavaScript API

Also note that many of these pros and cons also apply to excessive use of operator overloading, which this is a special case of, basically.


答:
Advantages: You save two seconds of coding time having to type less.

Disadvantages: Code is less intention-evident, making you waste the two seconds you saved having to carefully read and mind-evaluate the line of code everytime you come across it.


问:
Best Practice - Loop Exit Via Iterator Modification
I had an interesting discussion with my boss today regarding exiting a loop before the terminal condition is met. He had a construct in some of his VB6 code that looked something like this:

```<code>Dim Termination As Int
Termination = 10

For Iterator1 = 1 To Termination
    If Iterator1 = 5 Then
        Iterator1 = Termination
    End If
Next
</code>```

I questioned this implementation, contending that an Exit For was the proper way to exit a loop prematurely based on a condition, like this:

```<code>For Iterator2 = 1 To 10
    If Iterator2 = 5 Then
        Exit For
    End If
Next
</code>```

I noted that in practice these probably both evaluate to the same machine language JMP opcode. My boss asserted that his implementation may be more efficient since it would have only one JMP, the one at the end of the loop, instead of two, one at the end and one in the middle for the Exit For statement.

I prefer the second implementation for readability and semantics. Also, in the latest versions of Visual Studio for .Net if you add lines after the Exit For statement you'll be warned that there are unreachable lines in your code. However, you don't get this warning in VB6, which is where the debate started.

So what's the best practice here? Is the first example better in VB6 or is the second example better in all situations? What are the advantages / disadvantages of each approach.

Edit: Removed magic number from code example to enhance question clarity.

答:
Any time you exit a loop before meeting the condition you set at the top of the loop, you're causing some unexpected behaviour. That's generally not a good thing (it's the same problem people have with the oft maligned GOTO statement.) If you manually manipulate the data to meet the top condition, that's almost worse.

If I want to loop until I break out of it manually, I'd use some version of "while(true){}" and then explicitly break out with an exit() statement. That lets the reader know that the top condition of the loop doesn't govern when the loop stops, and doesn't leave them scratching their heads when the code exits at 10, after only looping 5 times.

Exiting a loop via an setting an arbitrary value to the iterator is the sort of thing I'd expect to see in VB6 though. That's practically a metaphor for the whole language.


答:
Performance shouldn't be your first priority.  Of higher importance should generally be code readability and maintainability.  Exit For states, in code, exactly what you want to do, semantically.  It's blatantly obvious to the reader exactly what the code is doing.

When setting the loop variable it's a lot less clear.  I need to spend time trying to figure out what's going on; is the loop variable set to the end, ahead one, the start, somewhere in the middle, or what?  That's time I shouldn't need to be spending.

Beyond that, you're also now repeating the constant 10 in that loop.  What if someone goes to change the loop variable to go to 15 instead.  They may not bother to look through the entire body of the loop and just expect it to work fine going up to 15 instead.  You now have a very evil bug.  When I come along to debug the code I may not know if someone intended the loop variable to be moved to another internal location, or if it really should be the end of the loop.

Another key difference is that End For ends the current iteration of the loop right now.  Setting the loop variable means that the current iteration ends and then the loop stops.  If there is more code in the current iteration of the loop then that's different.  It's only the same if the code is at the end of the loop.

As for the performance differences, I wouldn't expect there to be any particularly significant difference.  In the event there is a difference at all, it's almost certainly going to be very, very, very tiny, and not enough to matter.  If, by some surprising series of events you've managed to determine that this path of this loop is executed so frequently, and in a context where performance is so vital, that this change results in a noticeable and essential performance difference through your in depth performance tests and profiling, then consider using the less readable version (possibly with supporting comments).

Title: Best Practice - Loop Exit Via Iterator Modification

Body:
I had an interesting discussion with my boss today regarding exiting a loop before the terminal condition is met. He had a construct in some of his VB6 code that looked something like this:

```<code>Dim Termination As Int
Termination = 10

For Iterator1 = 1 To Termination
    If Iterator1 = 5 Then
        Iterator1 = Termination
    End If
Next
</code>```

I questioned this implementation, contending that an Exit For was the proper way to exit a loop prematurely based on a condition, like this:

```<code>For Iterator2 = 1 To 10
    If Iterator2 = 5 Then
        Exit For
    End If
Next
</code>```

I noted that in practice these probably both evaluate to the same machine language JMP opcode. My boss asserted that his implementation may be more efficient since it would have only one JMP, the one at the end of the loop, instead of two, one at the end and one in the middle for the Exit For statement.

I prefer the second implementation for readability and semantics. Also, in the latest versions of Visual Studio for .Net if you add lines after the Exit For statement you'll be warned that there are unreachable lines in your code. However, you don't get this warning in VB6, which is where the debate started.

So what's the best practice here? Is the first example better in VB6 or is the second example better in all situations? What are the advantages / disadvantages of each approach.

Edit: Removed magic number from code example to enhance question clarity.


问:
Best OOP design pattern for a sequence of operations
I am working on an application, a module of which does the following financial operations sequentially:

When a user requests for a certain amount to be transferred into her bank account:

check whether any transaction can happen now? (transaction can be carried out only during a certain time period)

check whether the user has requested for a minimum amount to be withdrawn

check whether the user has any default account

The result of all the above actions should be logged.

If all the above condition satisfies, the transaction is carried out. In future, there might be some additional checks.

Which object oriented design pattern should be best suitable for the above case?

答:
The correct pattern here is really depends on a context.
Before picking any particular pattern to stick to, I will try to find out answers to those questions:

Is it required to create different combinations of (1,2,3) checks at run-time ?

Do they need the same variables to perform their actions or they are greatly different?

How precise the error messages should be?

In case of failure do user retry from (1)st step always?

How concurrency is handled?

Does each method adds something to the request or simply validates? (say Default acct id?)

Based on a gut feeling I would code them as a plain methods with aggregating parameter for error codes.

```<code>public void DoTransaction(IErrorAgregator error, TransactionRequest request)
{
    if(!IsTransactionInCertainTimePeriod(request, error)) return;
    if(!IsTransactionAmountInUserBounds(request, error)) return;
    if(!UserHaveDefaultAccount(request, error)) return;
    bankingTransactor.PerformTransaction(request);
}
</code>```

It might be a good idea to put DoTransaction in the "ITransactionValidationStragegy" interface and create a layer super-type which will contain validation boilerplate code.

However, in this design I am assuming that validation logic is determined at compile time.

Body:
The correct pattern here is really depends on a context.
Before picking any particular pattern to stick to, I will try to find out answers to those questions:

Is it required to create different combinations of (1,2,3) checks at run-time ?

Do they need the same variables to perform their actions or they are greatly different?

How precise the error messages should be?

In case of failure do user retry from (1)st step always?

How concurrency is handled?

Does each method adds something to the request or simply validates? (say Default acct id?)

Based on a gut feeling I would code them as a plain methods with aggregating parameter for error codes.

public void DoTransaction(IErrorAgregator error, TransactionRequest request)
{
    if(!IsTransactionInCertainTimePeriod(request, error)) return;
    if(!IsTransactionAmountInUserBounds(request, error)) return;
    if(!UserHaveDefaultAccount(request, error)) return;
    bankingTransactor.PerformTransaction(request);
}

It might be a good idea to put DoTransaction in the "ITransactionValidationStragegy" interface and create a layer super-type which will contain validation boilerplate code.

However, in this design I am assuming that validation logic is determined at compile time.


问:
good replacement for commenting out code?
It bothers me to see commented out code and it seems often-times a symptom of developers not being proficient in advanced source control features, but on the other hand source control does not really go all the way in solving the problem that commenting out is intended for.  I've occasionally seen requirements flip-flop in such a way that code that would have been deleted suddenly is needed again.  If the code is really deleted, there doesn't seem to be a clear procedure for locating exactly where to find that deleted code in source control.

Is there a better way out there to save developer work that may be needed again besides the tried-and-true "commenting out"?

答:
We're pretty rigorous about this, and the guideline is that commented-out code shouldn't be checked in.  The rationale behind this is that you can never really know whether the engineer forgot to uncomment it before checking it in.  Even with a comment explaining why the code is commented out, there's still an element of doubt. If you need it back, you can get it back from source control.

In my opinion, the danger of changing requirements is less than the danger (and probable uncertainty) of seeing a block of checked in commented out code (particularly at some point far in the future) and wondering whether it should be there or not.

At the end of the day, even with specifications, user stories, Jira tickets and all that jazz, "the code is the documentation" - it's the only definitive reference as to what something actually does.

Of course it's just a guideline;  I'm sure you're going to get some really great answers to this -- I'm looking forward to reading them!

Succinctly:  don't check in the commented code, instead leave yourself a note in your issue tracker.  Write in the revision number and location of the alternate implementation.  The code remains clean, and you help your future self. If/when the requirements change, the implementation ticket will (should) get reopened, and you can use your breadcrumb to find the previous version.  Some issue trackers automatically track the change in source control directly on the ticket - that's another aid to you.


答: Assuming that source control is in place, creating a branch (or shelf/stash) for the commented out code would probably be easier to maintain than having to go through a bunch of files and un/re-comment a whole bunch of code. It also serves the secondary purpose of logically separating that code from the rest of the code base which is more stable.</p>

Title: good replacement for commenting out code?

Body:
It bothers me to see commented out code and it seems often-times a symptom of developers not being proficient in advanced source control features, but on the other hand source control does not really go all the way in solving the problem that commenting out is intended for.  I've occasionally seen requirements flip-flop in such a way that code that would have been deleted suddenly is needed again.  If the code is really deleted, there doesn't seem to be a clear procedure for locating exactly where to find that deleted code in source control.

Is there a better way out there to save developer work that may be needed again besides the tried-and-true "commenting out"?


问:
What are the best practices and pitfalls of doing a JS app powered purely by RESTful API?
We are starting to build a new app and I would like to explore the idea of doing a thick JS client (backbone / angular) with only RESTful API exposed by our application layer.  What are some of the best practices and potential pitfalls for doing this kind of web app?</p>

答:
If you are going to have only a REST API (and no actual server-side "pages"), the biggest challenges that come to mind for me are:

Accessibility

It's sad, but most screen readers are way behind the times and still can't cope with dynamic content. The modern solution is WAI-ARIA, and it's a steep learning curve.

Indexing (SEO)

To Googlebot and other spiders, your site is essentially a blank page. If you need content to be indexed, you'll have to do more than that. For truly "bare" APIs that don't serve HTML at all, you'll probably want to follow Google's recommendation of using your own JavaScript-capable spider to take snapshots of pages and serve up hashbang links.

Cross-resource transactions

Not every workflow is going to be cleanly encapsulated by a single resource. You might need to update an /invoice and /account at the same time. There still aren't any real standards for this; the typical answer seems to be to encapsulate the transaction itself as a resource, and handle atomicity in the REST API for the transaction resource. A shopping cart is a good example of a transaction; once you checkout, the entire basket is "committed" at once.

Web Optimization

You're taking on more than 10x the amount of JavaScript that is found in more conventional web apps. All of this has to be served to the client and run at some point, so minification and performance optimization are not optional, and it can be harder to optimize the client than the server when you consider that some of your users will still be running IE8 or IE7 on Windows XP on an original AMD Athlon machine that their nephew built for them 7 years ago. Also, since you'll be frequently changing your scripts, you can't just minify, you also have to version, otherwise your app will mysteriously break due to caching and such.

Error Handling

Most back-end web frameworks have this built-in. You just hook up a global exception handler, some logging, custom error pages, and you're done. It can be rather difficult to do this in JavaScript. You can hook up a global error handler to $.ajax or whatever, but even that is fraught with problems, since some error codes have semantic meaning (404, 409, etc.) Assuming you're even willing to go to the effort of setting up a logging API to collect errors, you'll have to make a trade-off between verbosity and bandwidth, and also put some kind of security or rate limiting on it so that people can't just spam your logging API to DoS your site.

Testing

At least in my experience, testing becomes more difficult because you need to maintain parallel suites of unit tests for client and server. If you do browser-based integration testing, it will be harder to tell if the failures are coming from the client or server side, unless you also maintain another suite of API-only integration tests. Basically, it's like adding another "tier".

Authentication/Authorization

There are standards for this (e.g. OAuth), but they're a pain to implement compared to more traditional models. This is especially true if you're running a mixed HTTP/HTTPS site and have to deal with crap like CORS. It's very much a solvable problem and lowest on my list for a reason; it'll just be extra work and bite you at odd times, because many of the back-end frameworks can be a bit... imperious about how authentication is supposed to work, and over-utilize things like session state.

Also, your app is basically spilling its guts to everyone who uses it, making it trivially easy to reverse-engineer the API, so you'd better make sure you have lots of validation in place, otherwise any random script kiddie can 0wn you. Not that this is a new problem, you're just making it a little easier for them by providing a direct line.

All that being said, these are not even close to being showstoppers. Aside from the vastly improved user experience, you gain huge benefits from this model through reusability and separation of concerns. It becomes much harder (and much less necessary) for developers to abuse session state or other temporary data. And you can truly have front-end and back-end specialists, rather than having to expose your back-end guys to markup or your front-end guys to controllers.

I very much prefer this architecture but do be aware of the trade-offs you're making. It's still kind of a new/immature field - and people are still making a lot of mistakes. I wouldn't trust any "best practices" guide this early in the game.


问:
MVVM application architecture, where to put dependency injection configuration class, BusinessLayer and Common interfaces?
Planning my architecture for an MVVM application I come to this:

MyApp.UI

View

MyApp.BusinessLayer

ViewModel

MyApp.DataAccessLayer

RepositoryImplEF

MyApp.DomainLayer

DomainObject

RepositoryInterface

MyApp.Common

Logging

Security

Utility (contains some reflection method used by many levels)

CustomException

MyApp.UnitTest

I was inspired by Domain-driven-desing, test-driven-development and onion architecture but not sure to have done all well.

I am not sure of a couple of things:

where to put dependency injection configuration class? In the common project?

where to put BusinessLayer interfaces? in Domain layer?

where to put Common interfaces? in Domain layer? But Common in referenced from domain (for some reflection utilities and for DI if the response to 1. is yes) and circular reference isn't good

答:
IoC container initialization is usually located in the bootstrapper. This class is part of your infrastructure/initialization and does not really belong to any "common" thing. Since you don't plan to work with your domain model via messaging/services but using BL/DAL, I would strongly recommend to put IoC related stuff to modules, assuming you use a container that supports modules. This way you can keep your bootstrapper thin and do your registrations per module and modules are located in corresponding projects.

Concerning the BL, the question is what do you plan to put there. If your domain model is anemnic, you will have a huge business "managers" projects with all logic concentrated there. I would not call this part of your domain model. If, at the other hand, your domain model is planned to be a rich model, you will have a bunch of behaviours in your domain classes by definition. The rest of business logic would be separated to complex validations, commands and queries. What you call DAL with repositories are in fact queries. I would prefer trying to implement CQRS.


问:
Avoiding boilerplate in PHP classes
I am working on a PHP code and as it grows getting more and more tired of repeating the same standard pattern again and again and again:

```<code>class BolerPlate
{
    protected $property1;
    protected $property2;
    ...

    public function __construct ($property1, $property2, ...)
    {
        $this->property1 = $property1;
        $this->property2 = $property2;
        ...
    }
}
</code>```

So I am re-typing here each property name 4 (!) times just to get the standard setup! In each class! It doesn't look elegant nor DRY to me. And re-typing the same names creates more bug opportunities.

I wonder if there is any more elegant way or best practices to get the same setup with a code easier on the eyes :)

EDIT. What I have in mind is some sort of factory method where I can supply the list of properties only once each. Or using variable variables and iterate over all properties?

答:
First off, I understand your pain. If you use namespaces, add a use statement and type hint for any class dependency bringing the total to six.

Variable variables or any other hackery may save you some bulk now, but it's going to hurt you in the long run. Traits assume you are re-using code, which probably isn't the case, or at least it won't be every time.

The best thing you can do is minimize dependencies per class and try to keep things from getting out of hand. You can use macros, templates or whatever you want to call them to only type it once per dependency. This helps with keystrokes, but the resulting code will still be repetitive.

Sorry, this is the current state of PHP.

Title: Avoiding boilerplate in PHP classes


问:
Dependency Injection Confusion
I think I have a decent grasp of what Dependency Inversion principle (DIP) is, my confusion is more around dependency injection.

My understanding is the whole point of DI is to decouple parts of an application, to allow changes in one part without effecting another, assuming the interface does not change.

For examples sake, we have this

```<code>public class MyClass(IMyInterface interface)
{
   public MyClass
   {
      interface.DoSomething();
   }
}

public interface IMyInterface
{
    void DoSomething();
}
</code>```

How is this

```<code>var iocContainer = new UnityContainer();
iocContainer.Resolve<MyClass>();
</code>```

better practice than doing this

```<code>//if multiple implementations are possible, could use a factory here.

IMyInterface interface = new InterfaceImplementation();
var myClass  = new MyClass(interface);
</code>```

It may be I am missing a very important point, but I am failing to see what is gained. I am aware that using an IOC container I can easily handle an objects life cycle, which is a +1 but I don't think that is core to what IOC is about.

Edit

Here is an expanded example:

```<code>void Main()
{
    IRepository repository = new AddRepository();
    var maths = new PointlessMaths(repository,5);
    Console.WriteLine(maths.Result);
}

public interface IRepository
{
    int DoSomething(int id);
}

public class AddRepository : IRepository
{
    public int DoSomething(int id)
    {
        return id + 1;
    }
}

public class SubtractRepository : IRepository
{
    public int DoSomething(int id)
    {
        return id - 1;
    }
}

public class PointlessMaths
{
    public int Result {get;set;}
    public PointlessMaths(IRepository repository, int id)
    {
        Result = repository.DoSomething(id);
    }
}
</code>```

答:
Using DI container as a service locator is in fact an anti-pattern, it is widely discussed. Sometimes you have to do this but generally speaking you should avoid this. Basically by calling container.Resolve you are not doing any IoC and IoC is what DI containers intent to do.

What we really use DI containers for is to inject dependencies when needed using custructor parameters or property injection. You register your classes that implement your interfaces well in advance, when your application initialises/starts and there you specify all the details - simple initialization, using parameters, using factories and so on, specifying the life scope, etc, etc. When all this is done you don't really need to care as long as your constructors have parameters, where your registered classes can be injected to. So when you do this

You of course have to have the bootstrapper that resolves your main application class but since this class would already have injected parameters, all the rest can go automatically. And if you need ISession or ICustomerRepository or IWhatEverElseYouNeed, you will get it without worrying to instantiate it every time you need it.

Title: Dependency Injection Confusion


问:
Optional semicolons
Most often, in a general-purpose imperative language - semicolons as statement-delimiters are either required, or completely disallowed (e.g. C and Python).

However, some languages, like JavaScript, allow you to opt out of delimiting your statements with semicolons, in favor of other delimiters (such as a newline).

What are the design decisions behind this? I understand that semicolons are essential when writing multiple statements on the same line, but is there another reason to make them mandatory (except following C)?

答:
Semicolons are not always all-or-nothing like you mention in your question. For example, Lua's grammar is carefully designed to be free form (all whitespace, including newlines, can be ignored) but also without needing to use any semicolons. For example, the following programs are equivalent:</p>

```<code>--One statement per line
x = 1
y = 2

--Multiple statements per line
x = 1 y = 2

--You can add semicolons if you want but its just for clarity:
x = 1; y = 2
</code>```

Title: Optional semicolons

Body:
Semicolons are not always all-or-nothing like you mention in your question. For example, Lua's grammar is carefully designed to be free form (all whitespace, including newlines, can be ignored) but also without needing to use any semicolons. For example, the following programs are equivalent:

--One statement per line
x = 1
y = 2

--Multiple statements per line
x = 1 y = 2

--You can add semicolons if you want but its just for clarity:
x = 1; y = 2


问:
OOP Objects, nested objects, and DAO's
Here's something I keep struggling to figure out the best solution to. I've had this problem while working with PHP and Java so it's a fundamental understanding of OOP issue. Examples are in PHP.

Let's say I have a few object's here. Song, Artist, ArtistProfile, User.

So in some instances I want the ArtistProfile and an array of User objects (subscribers) when I call the Artist (e.g. the artist's profile page), in other instances I only want the Artist info, like when viewing a page of the song.

Should I be nesting one object as part of another or should I be creating more specific objects for different usages.

Option 1: Nested

```<code>Class Song {
   private $songId;
   private $songName;
   private $year;
   private $Artist; //Artist object
}

Class Artist {
   private $artistId;
   private $name;
   private $age;
   private $subscriberArr; //Array of User objects which then have more nested objects such as a Role object, Profile object
   private $profile; //Profile object which could also have more nested objects
}

Class User {
   private $userId;
   private $name;
   private $age;
   private $role; //Role object
   private $profile; //UserProfile object
}
</code>```

Option 2: Build more objects

```<code>Class Song {
   private $songId;
   private $songName;
   private $year;
   private $artistId;
}

Class Artist {
   private $artistId;
   private $age;
   private $name;
}

Class User {
   private $userId;
   private $name;
   private $age;
   private $roleId;
}

Class SongWithArtist {
   private $song; //Basic Song object
   private $artist; //Basic Artist object
}

Class ArtistWithProfile {
   private $artist; //Basic artist object
   private $profile; //Profile object
   private $subscriberArr; //UserDisplay object containing basic User object
}

 Class UserWithProfile {}
</code>```

Option 1 means wasting a lot of time/resources grabbing information I may not need for that page but easier to manage. Option 2 is messy and requires keeping track of which object is what but faster and far less db calls. Which is the 'correct' option and/or is there a 3rd correct option?

答:
Should I be nesting one object as part of another or should I be creating more specific objects for different usages.

Follow OO principles first which means "more specific objects."
In doing so your classes may "line up" with your database schema or not but do not let DB schema trump good OO design.

Single Responsibility Principle will help guide you in what classes to build. SRP means, for example, that a Song is a song. It is not an artist, it is not a list of subscribers, so it should not have artist or subscriber stuff in it. Only song stuff.

The above means that you will have lots of small, independent, fully functional things - classes. By "fully functional" I mean, if a Song is a name, date, and id then that's what's in it. period. The fact that a certain artist sings that song does not inherently, fundamentally define what a Song is. This means other classes to model relationships like "an artist's song repertoire" for example.

Small functional classes leads to good DAO's and flexibility for your user interface.

Option 1 means wasting a lot of time/resources grabbing information I may not need for that page but easier to manage. Option 2 is messy and requires keeping track of which object is what but faster and far less db calls

You are falling victim to premature optimization. How can you know up front that option 2 will have "fewer DB calls?" What does that mean anyway?

This is simply the wrong way to think about your domain classes/model. This is why you end up duplicating your DB schema:

.

```<code>Class SongWithArtist {
  private $song; //Basic Song object
  private $artist; //Basic Artist object
}
</code>```

When what you should have is something describing the real world:

```<code>Class ArtistPortfolio {
    private Artist $theArtist;
    private List<Song> $portfolio;  // list of songs (s)he sings
}

Class ArtistSubscribers {
    private Artist $theArtist;
    private List<User> $subscribers;  // list of people who like this artist
}

// And it would probably make sense to combine the above 2 classes:

Class ArtistProfile {
    // an Artist object, not just an id. We're doing OBJECT oriented programming.
    private Artist $theArtist;

    private List<Song> $portfolio;  // list of Song objects
    private List<User> $subscribers; // list of User objects
}

// and if you need a list of profiles...
Class ArtistProfiles {
    private List<ArtistProfile> $profiles; // a list of type ArtistProfile

    public ArtistProfile GetProfileByArtist (Artist thisArtist){}
    public ArtistProfile GetProfileByName (string name) {}
    public ArtistProfile GetProfileById (string id) {}
}

// I'd say a ArtistProfile could be part of an Artist..

Class Artist {
    private $id;
    private $name;
    private ArtistProfile $profile; // this is composition.
}

//In lieu of the above, an DAO oriented Artist composition ...
// Just go with the refactoring flow!
Class Profile {
    private $id;
    private $name;
    private $birthdate
}

 Class Repertoire {
    // a Profile object, not just an id. We're doing OBJECT oriented programming.
    private Profile $theArtist;

    private List<Song> $portfolio;  // list of Song objects
    private List<User> $subscribers; // list of User objects
}

Class Artist {
    private Profile $me;
    private Repertoire $myStuff;
}
</code>```

Too Many DB Calls!

NOT. You can instantiate a Artist object without populating the $myStuff and in turn, defer populating $subscribers / portfolio lists until needed. This is called lazy loading.

Title: OOP Objects, nested objects, and DAO's

Body:
Should I be nesting one object as part of another or should I be creating more specific objects for different usages.

Follow OO principles first which means "more specific objects."
In doing so your classes may "line up" with your database schema or not but do not let DB schema trump good OO design.

Single Responsibility Principle will help guide you in what classes to build. SRP means, for example, that a Song is a song. It is not an artist, it is not a list of subscribers, so it should not have artist or subscriber stuff in it. Only song stuff.

The above means that you will have lots of small, independent, fully functional things - classes. By "fully functional" I mean, if a Song is a name, date, and id then that's what's in it. period. The fact that a certain artist sings that song does not inherently, fundamentally define what a Song is. This means other classes to model relationships like "an artist's song repertoire" for example.

Small functional classes leads to good DAO's and flexibility for your user interface.

Option 1 means wasting a lot of time/resources grabbing information I may not need for that page but easier to manage. Option 2 is messy and requires keeping track of which object is what but faster and far less db calls

You are falling victim to premature optimization. How can you know up front that option 2 will have "fewer DB calls?" What does that mean anyway?

This is simply the wrong way to think about your domain classes/model. This is why you end up duplicating your DB schema:

.

Class SongWithArtist {
  private $song; //Basic Song object
  private $artist; //Basic Artist object
}

When what you should have is something describing the real world:

Class ArtistPortfolio {
    private Artist $theArtist;
    private List<Song> $portfolio;  // list of songs (s)he sings
}

Class ArtistSubscribers {
    private Artist $theArtist;
    private List<User> $subscribers;  // list of people who like this artist
}

// And it would probably make sense to combine the above 2 classes:

Class ArtistProfile {
    // an Artist object, not just an id. We're doing OBJECT oriented programming.
    private Artist $theArtist;

    private List<Song> $portfolio;  // list of Song objects
    private List<User> $subscribers; // list of User objects
}

// and if you need a list of profiles...
Class ArtistProfiles {
    private List<ArtistProfile> $profiles; // a list of type ArtistProfile

    public ArtistProfile GetProfileByArtist (Artist thisArtist){}
    public ArtistProfile GetProfileByName (string name) {}
    public ArtistProfile GetProfileById (string id) {}
}

// I'd say a ArtistProfile could be part of an Artist..

Class Artist {
    private $id;
    private $name;
    private ArtistProfile $profile; // this is composition.
}

//In lieu of the above, an DAO oriented Artist composition ...
// Just go with the refactoring flow!
Class Profile {
    private $id;
    private $name;
    private $birthdate
}

 Class Repertoire {
    // a Profile object, not just an id. We're doing OBJECT oriented programming.
    private Profile $theArtist;

    private List<Song> $portfolio;  // list of Song objects
    private List<User> $subscribers; // list of User objects
}

Class Artist {
    private Profile $me;
    private Repertoire $myStuff;
}

Too Many DB Calls!

NOT. You can instantiate a Artist object without populating the $myStuff and in turn, defer populating $subscribers / portfolio lists until needed. This is called lazy loading.


问:
Best Way to Handle dynamic infograph with javascript?
I've currently been assigned a project to create the following with javascript, you can view the final product here:
http://i1245.photobucket.com/albums/gg583/leetpete1994/Infografic-TrafficSources_zpsf50dfa6d.png

It's basically my job to take the provided PDF and create a way to dynamically display the data that the image conveys. The data itself is going to be calculated elsewhere, so all I have to worry about is accepting the values for each beaker, and filling them appropriately.

My idea right now:

Right now my idea is using the canvas. I've created a beaker class, and then made the 5 beakers an instance of the class. This works pretty well, and I'm sitting with a canvas that has 5 empty beakers in the correct place. I've divided each beaker by 100, then I can fill each one correctly the amount of pixels needed to be whatever percent it happens to be, but this is where I run into issues. Each beaker is a different shape, and as each one gets filled the shape changes. Therefore, I'm having a difficult time trying to actually draw in the liquid in the beakers. Secondly, if I do manage to draw the liquid in correctly, it's going to cover details of the beaker. If I did liquid first then beakers it would be the opposite problem.

So, is there a better way to go about doing this, or to easily draw the odd shapes onto the canvas? I'm beginning to think using the canvas is not going to be the best way. I know I could just make several images for each at different liquid levels, but I want to avoid using that many images in the final product.

答:
First, In my opinion the best way to handle this: have a look at using SVG and javascript via Raphaël.js (http://raphaeljs.com/).

However, if you feel like hacking together a lot of low-level operations with Canvas, have a look at Canvas clipping and compositing. At simplest you would need a bitmap into which first render the liquid level and add the beaker shape on top, using compositing.

Here are two relevant links:
http://tutorials.jenkov.com/html5-canvas/composition.html
https://stackoverflow.com/questions/2337382/html5-canvas-compositing-source-in
(alas, my rep doesn't allow for the clipping links)


答:
The question is, where is the knowledge about which concrete implementation of a dependency is needed, and the setup (e.g. configuration or other dependencies)  this dependency needs is best kept. This may or may not be in the dependant object. As always, the answer depents. But consider a complex object which needs other dependencies and maybe configuration data like urls or passwords. This dependency may also be the dependency of other objects. In this case, the knowledge of the setup should clearly not be located in the dependant objects, because it would be redundant and/or clutter class relationships and thus create more overall complexity than with a DI-Container, which keeps this knowledge in one place.

You could of course implement a factory for this case. But what if your application has lots of complex depenendcies, which all need some kind of factory. Now you have the problem of factories floating around, all containting part of the knowledge how the dependencies of the application are interconnected. Using a container in this case, adds much to the clarity and transparancy of the system. DI-Containers at this level are often used as a factory of factories.

The more complex the application gets, the more it is useful to have a central place interconnecting the parts.

Title: Dependency Injection Confusion

Body:
I think I have a decent grasp of what Dependency Inversion principle (DIP) is, my confusion is more around dependency injection.

My understanding is the whole point of DI is to decouple parts of an application, to allow changes in one part without effecting another, assuming the interface does not change.

For examples sake, we have this

```<code>public class MyClass(IMyInterface interface)
{
   public MyClass
   {
      interface.DoSomething();
   }
}

public interface IMyInterface
{
    void DoSomething();
}
</code>```

How is this

```<code>var iocContainer = new UnityContainer();
iocContainer.Resolve<MyClass>();
</code>```

better practice than doing this

```<code>//if multiple implementations are possible, could use a factory here.

IMyInterface interface = new InterfaceImplementation();
var myClass  = new MyClass(interface);
</code>```

It may be I am missing a very important point, but I am failing to see what is gained. I am aware that using an IOC container I can easily handle an objects life cycle, which is a +1 but I don't think that is core to what IOC is about.

Edit

Here is an expanded example:

```<code>void Main()
{
    IRepository repository = new AddRepository();
    var maths = new PointlessMaths(repository,5);
    Console.WriteLine(maths.Result);
}

public interface IRepository
{
    int DoSomething(int id);
}

public class AddRepository : IRepository
{
    public int DoSomething(int id)
    {
        return id + 1;
    }
}

public class SubtractRepository : IRepository
{
    public int DoSomething(int id)
    {
        return id - 1;
    }
}

public class PointlessMaths
{
    public int Result {get;set;}
    public PointlessMaths(IRepository repository, int id)
    {
        Result = repository.DoSomething(id);
    }
}
</code>```


答:
The answer is to delete it.  The question is then what to do with it after deleting so that one can find it again.  This depends in part on the VCS.

Just deleting has the problem that you can't easily find something with blame (git and svn both have a feature to show where something was added - and the Coding Horror blog post - Who Wrote This Crap?).

However, if you put a comment in its place it does show up in the annotations and in the current code.

One could (for example), replace the block of code with

```<code>/* code removed here that does frob()
 * no longer needed because of XYZ requirement
 * see f7f6023 for removed code
 */
</code>```

You could probably simplify that to one line or something so that it isn't quite the eyesore that I have it.  The idea is to leave a 'folded corner of the page' in the code so that someone can find it again.  Granted, don't do this for every block of code you take out.  If you're just taking out a rather boring line, take it out and be done with it.  No need to clutter the mind when reading the source (that is the spot for the commit message)

I'll point out that git has a slight advantage here of being able to specify the checksum of the parent more easily than other VCS can specify the location of the parent (it might be in a branch, it might not be)

If you are on Github or a similar in house repository, one could instead extract it out to a gist and reference that in the comment.

If you aren't in as enlightened of an a VCS system, one can move the idea of a gist into its own 'snippets' directory that one references for sizable chunks of functionality that you want to keep around.

The extraction method of the gist and the snippets has the advantage that one can search easily within this code.  You shouldn't be using it only for deleted code, but rather the templates for how to do something.  That something was deleted at some point in time isn't a reason not to save that snippit.

To this end, I'd suggest also looking that the question Best practices for sharing tiny snippets of code across projects for ideas on ways to best do that.

Another approach is to save the patch you did that removed the code in question in the issue tracking system itself.  Saving the patch for the code remove also saves the code that was removed.  Searching the issue tracking system then will also search removed code.

Body:
The answer is to delete it.  The question is then what to do with it after deleting so that one can find it again.  This depends in part on the VCS.

Just deleting has the problem that you can't easily find something with blame (git and svn both have a feature to show where something was added - and the Coding Horror blog post - Who Wrote This Crap?).

However, if you put a comment in its place it does show up in the annotations and in the current code.

One could (for example), replace the block of code with

/* code removed here that does frob()
 * no longer needed because of XYZ requirement
 * see f7f6023 for removed code
 */

You could probably simplify that to one line or something so that it isn't quite the eyesore that I have it.  The idea is to leave a 'folded corner of the page' in the code so that someone can find it again.  Granted, don't do this for every block of code you take out.  If you're just taking out a rather boring line, take it out and be done with it.  No need to clutter the mind when reading the source (that is the spot for the commit message)

I'll point out that git has a slight advantage here of being able to specify the checksum of the parent more easily than other VCS can specify the location of the parent (it might be in a branch, it might not be)

If you are on Github or a similar in house repository, one could instead extract it out to a gist and reference that in the comment.

If you aren't in as enlightened of an a VCS system, one can move the idea of a gist into its own 'snippets' directory that one references for sizable chunks of functionality that you want to keep around.

The extraction method of the gist and the snippets has the advantage that one can search easily within this code.  You shouldn't be using it only for deleted code, but rather the templates for how to do something.  That something was deleted at some point in time isn't a reason not to save that snippit.

To this end, I'd suggest also looking that the question Best practices for sharing tiny snippets of code across projects for ideas on ways to best do that.

Another approach is to save the patch you did that removed the code in question in the issue tracking system itself.  Saving the patch for the code remove also saves the code that was removed.  Searching the issue tracking system then will also search removed code.


问:
Interviewing a developer who's skilled in a language you don't know
Background:

I'm an experienced developer and technical architect (C#, Delphi, Java, Clojure, Assembler, Perl, various esoteric functional programming languages)

We need to hire some Ruby developers for a growing Ruby on Rails project

I don't personally know much Ruby at all, but need to evaluate some candidates

What's the best way to fairly evaluate a developer who is hopefully skilled in a language you don't personally know well?

答:
My opinion is good code is somewhat universal.  Have him show you some things he's programmed, see how well they run, and then look at his code.  Even if you're unfamiliar with the language, you can usually get an idea of what type of programmer he is by looking at his code.

More importantly though, actually have him write code in the interview. It can be something rather simple that only takes 20-30 minutes.  If you're hiring someone for a job for years to come, he should be able to at least give you 30 minutes to assess if he can do the job.  I'm amazed at how many people hire programmers without even testing if they can really program.

If they've got some impressive looking past projects with nice looking code, and if they can whip out a nice, simple little test program with well organized code, than you can get a pretty good feeling about their ability.


问:
How does aggregation work when databases are involved?
So I'm reading a book on Design Patterns (Design Patterns Explained 2nd Edition), and all throughout the book it says to "favor aggregation over inheritance".

I'm trying to wrap my head around trying to design something, and I feel so stupid.

So conceptually, I have Recruiters. I figured these recruiters can be an abstract class, because I have a couple different types of recruiters... full time and part time. The thing is, I want each recruiter to be able to have references to other recruiters because they might work together and need to share and combine information.

Each Recruiter would have one or more Regions that they oversee, perhaps sharing it with other Recruiters. All the region is a conceptual aggregate of SubRegions. The SubRegions define places that fall along certain geographical boundaries. These contain some numerical statistic information about recruitments for that SubRegion as a whole.

The Subregions consist of Recruitments, which contains detailed information about particular recruiting events for a SubRegion. They also contain other statistical information that makes sense to be under Recruitments(because they're very specific to the Recruitment), but not under SubRegions. Every time some information from the recruitment is updated, it needs to create a new record of that transaction so I can keep a history of how the numbers are adjusting.

Now, I want all of these to be able to be stored in a database. I am very naive when it comes to database design and structuring, especially when it comes to dealing with abstract classes and interfaces which are new to me.

Everything in the database is going to be linked in some way, among different tables. Say, the Recruiters are going to be a table, and there is going to be a Region table, a SubRegion table, and a Recruitment table.

Where do I need to put the logic, and how do I put it, such that I can make sure I can save everything out to the database, keyed together nicely, but loosely coupled in the code?

答:
Tables primarily describe relationships, not neccessarily objects. Your design contains the following relationships:

```<code>Recruiter n:m Region
Region    1:n SubRegion
SubRegion 1:n Recruitment
</code>```

… and each of these could be a table of its own. Instances of recruiters and regions etc. are referenced here by an ID. Given an object, it can look up attributes in the database by its ID:

I'm subregion 14. What are my recruitments?

```<code>SELECT Recruitment FROM SubRegion_Recruitment WHERE SubRegion = 14
</code>```

Of course, you would abstract this through something like data access objects or similar.

Body:
Tables primarily describe relationships, not neccessarily objects. Your design contains the following relationships:

Recruiter n:m Region
Region    1:n SubRegion
SubRegion 1:n Recruitment

… and each of these could be a table of its own. Instances of recruiters and regions etc. are referenced here by an ID. Given an object, it can look up attributes in the database by its ID:

I'm subregion 14. What are my recruitments?

SELECT Recruitment FROM SubRegion_Recruitment WHERE SubRegion = 14

Of course, you would abstract this through something like data access objects or similar.


问:
Overcoming slow problem solving due to increased knowledge of what might go wrong
This has been troubling me for some time, and I'd really appreciate the input of other professionals.

Short background: I started programming when my parents bought me my first computer in 1988 (at age 14, I'm 39 now). I followed a couple of other career paths before finally becoming a professional programmer in 1997. Late bloomer, perhaps, but that's how it was. I'm still happy with my choice, I love programming, and I consider myself good at what I do.

Lately, I've been noticing that the more experience I gain, the longer it takes me to complete projects, or certain tasks in a project. I'm not going senile yet. It's just that I've seen so many different ways in which things can go wrong. And the potential pitfalls and gotchas that I know about and remember are just getting more and more.

Trivial example: it used to be just "okay, write a file here". Now I'm worrying about permissions, locking, concurrency, atomic operations, indirection/frameworks, different file systems, number of files in a directory, predictable temp file names, the quality of randomness in my PRNG, power shortages in the middle of any operation, an understandable API for what I'm doing, proper documentation, etc etc etc.

In short, the problems have long since moved from "how do I do this" to "what's the best/safest way of doing it".

The upshot is that it takes me longer to finish a project than a novice. My version may be rock solid, and as impenetrable as I know how to make it, but it takes longer.

The "create file" example above was just that, an example. Real tasks are obviously more complex, but less suited for a generic question like this one. I hope you understand where I'm going with this. I have no problem coming up with efficient algorithms, I love math, I enjoy complex subjects, I have no difficulties with concentration. I think I do have a problem with experience, and consequently with a fear of errors (intrinsic or extrinsic).

I spend almost two hours a day reading up on new developments, new techniques, languages, platforms, security vulnerabilities, and so on. The conundrum is that the more knowledge I gain, the slower I am in completing projects.

How do you deal with this?

答:
The truth is that modern systems are becoming increasingly complex. The computer is now similar to that game "Jenga" where you have all of these pieces relying on many of the others. Pull out the wrong piece and you have an error, pull out a correct/necessary piece and you still may produce an error. The more complex the system the more time you are likely to spend thinking of ways to make your code more robust, and hopefully more secure as well. Speed would be nice, but I think speed takes a back seat a lot these days when you hear in the news that "XYZ" company was hacked into and 6 million customer's credit card numbers were stolen.

Your clients may not want to hear that their program needs to be secure, robust, etc.. But you could tell them that their car does not need seatbelts and airbags nor their house need locks and doors... because who wants to hear all that?

If you are over-thinking you are going about things the right way, except that you need to pick a strategy that seems "concrete" and just go with it.


问:
How do you organize your local development environment?

Possible Duplicate:

  How do you organize your projects folders?

I'm interested to learn how everyone keeps their local development projects organized in a logical manner. What do you do to keep your dev projects organized in a manner that allows you to easily find things?

答:
I use the following structure for my project on Java (three top-level directories):</p>

```<code>Project/ - the projects main directory
   src/ - source files
   doc/ - documentation sources, generated HTML, PDF files
   build/makefiles and configurable template files for local paths and versions
   ChangeLog - a text file to track changes in the project
   README-DEV - describes how to build the project
   tests/ - everything concerning unit-testing
   kit/ - third party libs, sources

TSTProject/ - test-cases (over 2000 XML files), scripts for automated testing

Project_BRANCHES/ - branches, usually a branch per public release
</code>```

Body:
I use the following structure for my project on Java (three top-level directories):

Project/ - the projects main directory
   src/ - source files
   doc/ - documentation sources, generated HTML, PDF files
   build/makefiles and configurable template files for local paths and versions
   ChangeLog - a text file to track changes in the project
   README-DEV - describes how to build the project
   tests/ - everything concerning unit-testing
   kit/ - third party libs, sources

TSTProject/ - test-cases (over 2000 XML files), scripts for automated testing

Project_BRANCHES/ - branches, usually a branch per public release


答:
The simple answer is: accept it.

In all systems there's trade-offs to be made between reliability, robustness, security, speed, hardware cost, development cost, time to market, you name it. You will not always agree with how the customer makes those trade-offs, but you're not the one making those decisions. All you can do is provide a considered opinion. Software development covers the full gamut, from "my personal web page" to "run the nuclear reactor", and the code has to be written accordingly. If a crash means "reload my personal web page" then who really cares if that happens? But if a crash means "Chernobyl" then your preference for solid code is if anything a bit casual for my liking.

There are some clients who will happily accept "Proof of Concept" level code and run it in their live systems, and often they have systems administrators who are well used to that. IME their systems are usually unavailable for an hour or so in the middle of the night while a bunch of scheduled restarts happen. But they've made the business decision that that is how they want to roll. Ideally because their field is so fast-moving that high-quality code would never be ready, but often because they can't see the value (if a system "just works" they never notice it, therefore that system does not represent value for money). If it bothers you too much, try to avoid those clients.

Keeping up to date is time we all have to spend, or at least should spend. Sometimes that will get you work, other times it just keeps your mind in good shape. Either way, try to enjoy it.

Title: Overcoming slow problem solving due to increased knowledge of what might go wrong

Body:
This has been troubling me for some time, and I'd really appreciate the input of other professionals.

Short background: I started programming when my parents bought me my first computer in 1988 (at age 14, I'm 39 now). I followed a couple of other career paths before finally becoming a professional programmer in 1997. Late bloomer, perhaps, but that's how it was. I'm still happy with my choice, I love programming, and I consider myself good at what I do.

Lately, I've been noticing that the more experience I gain, the longer it takes me to complete projects, or certain tasks in a project. I'm not going senile yet. It's just that I've seen so many different ways in which things can go wrong. And the potential pitfalls and gotchas that I know about and remember are just getting more and more.

Trivial example: it used to be just "okay, write a file here". Now I'm worrying about permissions, locking, concurrency, atomic operations, indirection/frameworks, different file systems, number of files in a directory, predictable temp file names, the quality of randomness in my PRNG, power shortages in the middle of any operation, an understandable API for what I'm doing, proper documentation, etc etc etc.

In short, the problems have long since moved from "how do I do this" to "what's the best/safest way of doing it".

The upshot is that it takes me longer to finish a project than a novice. My version may be rock solid, and as impenetrable as I know how to make it, but it takes longer.

The "create file" example above was just that, an example. Real tasks are obviously more complex, but less suited for a generic question like this one. I hope you understand where I'm going with this. I have no problem coming up with efficient algorithms, I love math, I enjoy complex subjects, I have no difficulties with concentration. I think I do have a problem with experience, and consequently with a fear of errors (intrinsic or extrinsic).

I spend almost two hours a day reading up on new developments, new techniques, languages, platforms, security vulnerabilities, and so on. The conundrum is that the more knowledge I gain, the slower I am in completing projects.

How do you deal with this?


答:
You're not any slower in completing projects. Previously, you thought your novice projects were done when they really were not. You should sell this quality to clients.

"This company might get it done faster and cheaper, but is it really done? Or will you be hunting bugs for years?"

Beyond that, you need to know and accept the old idiom: "Perfect is the enemy of good."


问:
Good or bad code? Or "a secret reason"?
I think this code:

```<code>if(file_exists("amodule.inc.php"))
    require_once("amodule.inc.php");
</code>```

is misleading because of the use of the require_once.

I think that - to keep the logic and "wording" in line - "include_once" would be appropriate (where there are a number of arguments to not use the "if" at all but I would like to concentrate on "require vs include").

As far as my understanding goes, the ONLY difference between "require" and "include" is that "require has a consequence (halt) if the file does not exist vs. include proceeds with just a warning.

But, in the example, if the file does not exists, the require_once code will not executed anyways. Therefore the "require" misleads from my point of view.

From a superficial view, one could argue that the above code using require_once and

```<code>if(file_exists("amodule.inc.php"))
    include_once("amodule.inc.php");
</code>```

are "identical" what, from my view, is not. Because:

A "rough" analysis (like an automated check of a project) would throw a message, that "amodule.inc.php" is a vital project file, which the code shows, is not.

Also, in a (not very likely) cas that between the execution of the "if" statement and the require_once statement, the file could be deleted. Then, even worse, the code would NOT execute like expected (to run without load) but give up.

So, how would you guys out there argue?

答:
You are right about the first difference. Include and require are the same, except require will stop your program from running, if the file is missing, whereas include will continue to run and show an error.

From the PHP Manual:

require is identical to include except upon failure it will also produce a fatal E_COMPILE_ERROR level error. In other words, it will halt the script whereas include only emits a warning (E_WARNING) which allows the script to continue.

So if you have a large number of arguments, then, yes the include_once would be preferable, but without seeing the code, it would depend on what you want to happen if the file is missing.

OwnerDisplayName: jwka

Title: Good or bad code? Or "a secret reason"?


问:
Can I run both .Net and Java framework in one computer?
I have .NET 2.5 installed in my computer unit, as a beginner I used VB.net
As I went along I've also installed new .dlls that would help me with my VB.net programming
Now, I want to study java as well, leading to Android programming.

If I install the JDK 7.0, can I still be able to program in VB.net? Will installing JDK overwrite .dlls essential to the .NET framework? Should I get a new developing PC that focuses with JAVA/Android development?

答:
You will be able to have both Java and .NET frameworks installed on the same machine at the same time with no problem.

On a side note - is there a reason you are using such an old version of .NET? If there isn't a specific reason you need to use version 2.5, I would use a more up-to-date version.

OwnerDisplayName: anon


答:
Sounds like it's time for you to join the dark side: management.

I'm not suggesting you give up programming and become a manager. But it seems like all the experience you've quoted up until now has been technical in nature. In simple operation of writing out a file, you can think of 10 different aspects that a less mature developer would never consider. Not necessarily a bad thing, but...

The dark side is all about present value. It's about making minimal investment for maximum gain (cost-benefit analysis). In business everything boils down to how much will this cost me, probability of success, probability of failure, probability of spectacular failure and potential gain. Do the math; act accordingly.

This works just as well when you are a developer: create a temporary file, ignoring permissions and name collisions - 5 min. Net gain, the rest of the team can start working on whatever code depends on the presence of that file. Is it a perfect solution? Absolutely not. Will it get you 99%, 95%, maybe 90%? Yeah, it probably will.

Another question to ask: How do you feel about technical debt? Some people think it must be eliminated. I think those people are wrong. Just like in business, technical debt allows you to borrow "cash" or "time" in order to deliver something sooner.  What's better: A perfect solution in 2 years or a complete hack that a customer can use and purchase in 4 months? Every situation is different, but in some situations if you wait 2 years, your customer will already sign up with your competition.

The key is to manage technical debt the same way a well-run business manages financial debt. If you don't take on enough, you are not getting optimum return on investment. If you take on too much, the interest will kill you.

So my advice: Start evaluating your work based upon whether you're maximizing your value instead of maximizing your thoroughness. And if you practice this, you will develop the same intuition that you already developed in your technical area.

As a side note, I recently started doing the pomodoro technique and it has helped a lot. Instead of going on a tangent of a tangent, focus in small time intervals and then allocate pomodoros for future work/research. It's amazing how many times I made a note to research a topic but an hour later when the time came, I thought to myself, "there's at least 3 other things I could do with my time today which are all more valuable."


问:
Two or one git repo for Android app + web service backend?
I'm wondering what the best practice is for my git repository structure where I have an Android application + a web service backend. In general, I'd like to release these two independently (e.g., perf fixes to the backend with no changes to the front-end), but I am worried that if I keep these in two separate repos I'll lose the ability to see combined app + web service changes (e.g., there's a change in the APIs on the server).

What are other Android developers doing to manage their source code + release process? Should I use one git repo with separate folders or two git repos?

I should note that I'd like to set this up as push-to-deploy -- any changes to my master branch will trigger a tag and deploy.

答: It's two different projects, so use two different repos. It's not hard to have post commit hooks in both. Having multiple projects in the same repo just makes it messier to work on one while you're able to see the other, which leads to multiple copies, which leads to confusion.... if you're using a hosting service like GitHub you can see the changes to all the repos under an Organization (and other services have similar idioms) on one page. </p>


问:
The Agile process: how and what should be documented?
A while ago the company I work for had outsourced a development project to a third party. They employed agile practices in developing the solution. However when asked for documentation they would just say it was required as it was incorporated in a wiki or as part of their sprints.

They did leave at the completion of the project, with all but one of the project team. The project wiki site has now been closed down once the yearly subscription was due.

When they left they took most of the knowledge and understanding of what was developed with them.

So I do have 2 main questions;

Is this normal for agile or just an excuse for not wanting to write it?

What are the industry norm for documentation in agile projects to record development
requirements, designs, key decisions and context?

答:
Is this normal for agile or just an excuse for not wanting to write it?

My theory is that it's why agile spread so fast, especially scrum. I've seen too many team wanting agile to protect themselves (instead of the whole company). The problem is that in many case, the methodology is used against them by management (because they want to protect themselves too!).

Does this means agile doesn't work at all? Of course not, this just means that agile helps you to solve few common problems, but you are still in charge of all the others. And in many case agile is just not suitable for that team in that company.

What are the industry norm for documentation in agile projects to record development requirements, designs, key decisions and context?

To be short:

The team should define how much documentation they need

They know the domain, they are the experts and more importantly they build the thing!

That's what Working software over comprehensive documentation in the Agile Manifesto means.


问:
Is there any alternative to function pointers in c++?
I am a novice c++ programmer who kept an idea that function pointers are a thing of C and OOP in C++ does not recommend its usage.

I know what I write here is vague/broad. But it will be great if somebody could comment whether my idea is completely wrong or something sensible.

Thanks.

答:
Here is one example where use of member function pointer - within a class, as an implementation detail - is perfectly acceptable, if one works with performance-sensitive code for different CPU architectures.

See the C++ FAQs for the proper use of member function pointer. It requires a different syntax than static function pointers.

(Thanks for Kaz for the suggestion.)

```<code>class SomePerformanceCriticalOperation
{
private:
    // the type declaration of a member function pointer

    typedef int (SomePerformanceCriticalOperation::*ProcessPtr)(size_t bytesToProcess, void* dataPtr);

    // the instance of a member function pointer, to be assigned to a member function
    // (inside the constructor)
    ProcessPtr m_ptr;

public:
    SomePerformanceCriticalOperation()
    {
        cpu_features feat = ::GetCpuFeatures();
        if (TestBit(feat, cpu_features_SSE41))
            m_ptr = &SomePerformanceCriticalOperation::Process_SSE41;
        else if (TestBit(feat, cpu_features_SSSE3))
            m_ptr = &SomePerformanceCriticalOperation::Process_SSSE3;
        else if (TestBit(feat, cpu_features_SSE3))
            m_ptr = &SomePerformanceCriticalOperation::Process_SSE3;
        else if (TestBit(feat, cpu_features_SSE2))
            m_ptr = &SomePerformanceCriticalOperation::Process_SSE2;
        else if (TestBit(feat, cpu_features_MMX))
            m_ptr = &SomePerformanceCriticalOperation::Process_MMX;
        else
            m_ptr = &SomePerformanceCriticalOperation::Process_CPlusPlus;
    }

    // The CPU-specific functions, as usual. (Omitted.)

    int Process_SSE41(size_t bytesToProcess, void* dataPtr) { ... }
};
</code>```

Body:
Here is one example where use of member function pointer - within a class, as an implementation detail - is perfectly acceptable, if one works with performance-sensitive code for different CPU architectures.

See the C++ FAQs for the proper use of member function pointer. It requires a different syntax than static function pointers.

(Thanks for Kaz for the suggestion.)

class SomePerformanceCriticalOperation
{
private:
    // the type declaration of a member function pointer

    typedef int (SomePerformanceCriticalOperation::*ProcessPtr)(size_t bytesToProcess, void* dataPtr);

    // the instance of a member function pointer, to be assigned to a member function
    // (inside the constructor)
    ProcessPtr m_ptr;

public:
    SomePerformanceCriticalOperation()
    {
        cpu_features feat = ::GetCpuFeatures();
        if (TestBit(feat, cpu_features_SSE41))
            m_ptr = &SomePerformanceCriticalOperation::Process_SSE41;
        else if (TestBit(feat, cpu_features_SSSE3))
            m_ptr = &SomePerformanceCriticalOperation::Process_SSSE3;
        else if (TestBit(feat, cpu_features_SSE3))
            m_ptr = &SomePerformanceCriticalOperation::Process_SSE3;
        else if (TestBit(feat, cpu_features_SSE2))
            m_ptr = &SomePerformanceCriticalOperation::Process_SSE2;
        else if (TestBit(feat, cpu_features_MMX))
            m_ptr = &SomePerformanceCriticalOperation::Process_MMX;
        else
            m_ptr = &SomePerformanceCriticalOperation::Process_CPlusPlus;
    }

    // The CPU-specific functions, as usual. (Omitted.)

    int Process_SSE41(size_t bytesToProcess, void* dataPtr) { ... }
};


问:
Database is performing slow, even all the tables are having normalization
An interviewer asked me this question:

Tables are created with appropriate normalization rules, However the database is performing slow. [Ie.: The select, insert statements are taking time to do his operation.] What are areas we need to look to improve the database performance.

Obviously this is a vague question. What sorts of things might be wrong with a database that is running slowly, even when normalized?

答:
Making INSERT statements run faster is a bit of an arcane art. But that's probably not the focus.  The point of a database isn't putting data into it; it's getting it back out in interesting and useful ways.  So the main things to focus on are SELECT statements.

The first thing I would look at is checking the query plans on slow queries.  See if you have any table scans that are taking up a significant percentage of your time.  A table scan is when the database engine has to examine every row individually to see if it meets a WHERE criterion.  If you find one of these, you can make the query run faster by indexing the table on the appropriate WHERE criteria.  This can take search times from O(N) down to O(log N) or even O(1).

Some databases will make it easy on you: their query plan analyzer will point out that you're missing an index and suggest what you ought to create.

Also, check out the joins on your query.  Make sure they aren't using too broad of joining criteria, and be careful that you're not using left outer joins when a full join would work.  Both of these issues can cause a poorly-written query to produce too many rows and take longer to run.

If you don't have missing indices or bad joins, a more advanced trick is denormalization: setting up columns on tables that duplicate data that can be found in other tables, to allow you to avoid joins or aggregates that can be expensive.  This has to be done carefully, though, with triggers so that the data remains in sync, and is best done only if you know what you're doing and if there aren't any better alternatives available.