问:
What can Go chan do that a list cannot?
I want to know in which situation Go chan makes code much simpler than using list or queue or array that is usually available in all languages.

As it was stated by Rob Pike in one of his speeches about Go lexer, Go channels help to organize data flow between structures that are not homomorphic.

I am interested in a simple Go code sample with chan that becomes MUCH more complicated in another language (for example C#) where chan is not available.

I am not interested in samples that use chan just to increase performance by avoiding waiting of data between generating list and consuming the list (which can be solved by chunking) or as a way to organize thread safe queue or thread-safe communication (which can be easily solved by locking primitives).

I am interested in a sample that makes code simpler structurally disregarding size of data.

If such sample does not exist then sample where size of data matters.

I guess desired sample would contain bi-directional communication between generator and consumer.

Also if someone could add tag [channel] to the list of available tags, that would be great.

答:
A generic queue or array is generally not, by itself, thread safe, just like many other data types. Thread safety is usually accomplished in two ways:

Using mutex locks - each thread that wants to modify a value has to wait.

Delegation - only the owning thread can modify the value.

Mutex locks are fairly straight forward - nobody owns the value, but only one thread can modify it at a time. When one thread is modifying a value, other threads have to wait. The problem with this approach is contention. More than one thread wanting to modify a value at the same time, and the number of threads waiting stacks up.

How delegation is handled is really dependent on the language in question. In Objective C you have GCD to dispatch asynchronous (or even synchronous) requests on the owning thread. You have an opportunity to (asynchronously) have the value modified without holding up the requesting thread. GCD internally schedules these tasks into a queue and executes them when the target thread isn't busy.

Go channels are somewhat a form of delegation. You can use it as a non-blocking queue by using buffered channels. But the biggest difference between Go channels and other approaches  can probably be summed up with the following sentence:

Don't communicate by sharing, share by communicating.

A Go channel is much more than just a queue, it's a communication pipeline. The best way I can illustrate this is by showing an excerpt from one of my own projects:

```<code>for {
    select {
    case client := <-server.accept:
        server.addClient(client)
        go server.serveClient(client)
    case client := <-server.remove:
        server.removeClient(client)
    case envelope := <-server.dropbox:
        switch envelope.cmd {
        case "pub":
            server.publish(envelope)
        case "sub":
            server.subscribe(envelope)
        case "unsub":
            server.unsubscribe(envelope)
        }
    case err := <-server.errors:
        return err
    }
}
</code>```

The above code is running on the main Go routine (the channels are buffered).

<-server.accept - A second Go routine (not shown here) handles new connections and passes them to the accept channel. The main Go routine accepts the new client and adds them to a map of connected clients. Another Go routine is spawned to handle requests from the new client.

<-server.remove - When a client disconnects the Go routine handling its connection passes it back to the main Go routine to be removed.

<-server.dropbox - When a client has something it wants to send it puts it into the "dropbox" to be delivered to other clients, which are registered in the map.

Each client has an inbox channel which the main thread can deliver "mail" to. The Go routine handling the client connection reads the inbox.

As you can see by the example, the code becomes somewhat relatable: A post-office with a drop box to deliver mail, and an inbox for each client to receive it. This is just one example of how channels can be used.

Should channels always be used in every situation? No - I have seen situations where a mutex lock made more sense than a channel. Atomic data structures is an example where mutex locks make more sense.

I think the overall goal of a channel is to make code easier to understand. It conveys intention more precisely, in certain (but many) situations. Internally a channel probably uses mutex locks. I think an important point to take home is - channels are useful; just don't get carried away.

Title: What can Go chan do that a list cannot?

Body:
A generic queue or array is generally not, by itself, thread safe, just like many other data types. Thread safety is usually accomplished in two ways:

Using mutex locks - each thread that wants to modify a value has to wait.

Delegation - only the owning thread can modify the value.

Mutex locks are fairly straight forward - nobody owns the value, but only one thread can modify it at a time. When one thread is modifying a value, other threads have to wait. The problem with this approach is contention. More than one thread wanting to modify a value at the same time, and the number of threads waiting stacks up.

How delegation is handled is really dependent on the language in question. In Objective C you have GCD to dispatch asynchronous (or even synchronous) requests on the owning thread. You have an opportunity to (asynchronously) have the value modified without holding up the requesting thread. GCD internally schedules these tasks into a queue and executes them when the target thread isn't busy.

Go channels are somewhat a form of delegation. You can use it as a non-blocking queue by using buffered channels. But the biggest difference between Go channels and other approaches  can probably be summed up with the following sentence:

Don't communicate by sharing, share by communicating.

A Go channel is much more than just a queue, it's a communication pipeline. The best way I can illustrate this is by showing an excerpt from one of my own projects:

for {
    select {
    case client := <-server.accept:
        server.addClient(client)
        go server.serveClient(client)
    case client := <-server.remove:
        server.removeClient(client)
    case envelope := <-server.dropbox:
        switch envelope.cmd {
        case "pub":
            server.publish(envelope)
        case "sub":
            server.subscribe(envelope)
        case "unsub":
            server.unsubscribe(envelope)
        }
    case err := <-server.errors:
        return err
    }
}

The above code is running on the main Go routine (the channels are buffered).

<-server.accept - A second Go routine (not shown here) handles new connections and passes them to the accept channel. The main Go routine accepts the new client and adds them to a map of connected clients. Another Go routine is spawned to handle requests from the new client.

<-server.remove - When a client disconnects the Go routine handling its connection passes it back to the main Go routine to be removed.

<-server.dropbox - When a client has something it wants to send it puts it into the "dropbox" to be delivered to other clients, which are registered in the map.

Each client has an inbox channel which the main thread can deliver "mail" to. The Go routine handling the client connection reads the inbox.

As you can see by the example, the code becomes somewhat relatable: A post-office with a drop box to deliver mail, and an inbox for each client to receive it. This is just one example of how channels can be used.

Should channels always be used in every situation? No - I have seen situations where a mutex lock made more sense than a channel. Atomic data structures is an example where mutex locks make more sense.

I think the overall goal of a channel is to make code easier to understand. It conveys intention more precisely, in certain (but many) situations. Internally a channel probably uses mutex locks. I think an important point to take home is - channels are useful; just don't get carried away.


问:
What can a technically proficient senior software developer study to keep improving
Say you have been programming for over 10 years. You know many languages, with few of those at very detailed level. You have been designing architecture for solutions, worked on and delivered larger projects. You have been studying patterns, best practices, effective coding guidelines, unit testing, multi-threading, etc.

And then you slowly develop a feeling that most of the books you read, give less and less valuable information per 100 pages of text. So they start giving diminishing returns. You still learn, but you no longer improve by leaps and bounds.

Why does learning become less productive compared to how it was before?

Back then, it used to change your way of thinking, taught you new things and broadened your horizons that later improved either your current profession, or allowed to invent/manage/build something new. Why is it no longer the case?

答:
Each time I go on the site Lambda The Ultimate, I really don't/can't think like I'm knowing-all in the computer sciences field.

LtU will give you a good start point for paradigm and theoretic knowledge left to be learnt.

"The more you know, the more you know how little you know."

ContentLicense: CC BY-SA 3.0


问:
Is it correct to exclude argument names from function prototypes?
I was recently creating a small technical documentation for an application. The document is to be used by newly hired programmers to get acquainted with the application. It is much friendlier than the Javadocs we have, and includes information that usually isn't being documented.

When describing a function, I first bring the prototype and than the description, usage, etc. I have to choose to include argument names or omit them in the prototypes. On one hand, argument names are mostly trivial (like MyClass myClass), on the other hand they sometimes contain information of the purpose of the argument (which I will indicate when describing the function anyway).

I had the same dilemma in C++ when creating a class in two files.

Should I include argument names? Does it really work for readability?

答: Include them where it makes sense, and only there. It's not an all-or-nothing choice.</p>


问:
Is wrapping byte[] for stronger typing good practice?
I'm working on a Java-based library which makes use of PKCS #10 requests.  There are PKCS #10 libraries available for Java (Sun and IBM libraries that come with the respective JDKs), and the open-source Bouncy Castle library.

I'd rather not couple my library to another through the API, so my initial thought was to create a wrapper.  However, PKCS #10 is potentially complex, so the scope of the wrapper would expand quite quickly, and users of that wrapper would probably "unwrap" the wrapper and use one of the aforementioned libraries for any heavy-lifting, particularly if they use PKCS #10 in their own applications already.

My remaining option is to provide a simple wrapper around a byte array.  Is providing a very thin wrapper just for the sake of typing good practice?

答: Yes, this is a good practice, because it gives meaning to those wrapped bytes by introducing a user interface. You also have the option to make using those bytes correctly more easy, because the API is a hint on what can be done with them. Just using plain bytes may lead to a smell called primitive obsession.</p>


答: If you ever intend to generate documentation from the header files it might be a good idea to include the names</p>

Title: Is it correct to exclude argument names from function prototypes?

Body:
I was recently creating a small technical documentation for an application. The document is to be used by newly hired programmers to get acquainted with the application. It is much friendlier than the Javadocs we have, and includes information that usually isn't being documented.

When describing a function, I first bring the prototype and than the description, usage, etc. I have to choose to include argument names or omit them in the prototypes. On one hand, argument names are mostly trivial (like MyClass myClass), on the other hand they sometimes contain information of the purpose of the argument (which I will indicate when describing the function anyway).

I had the same dilemma in C++ when creating a class in two files.

Should I include argument names? Does it really work for readability?


问:
Why is black box called functional testing when it tests also non functional?
This has been bothering me for a while. Security, performance tests etc. are all done typically using the black box approach. But these are nonfunctional,while black box is called functional testing.

Is it because it judges the function and it is just a naming or there is an inconsistency?

References:

Software Engineering by Salleh

Software Engineering and Testing by Gupta, Tayal

Software Engineering by A.A.Puntambekar

Software Testing: a Practical Approach by Sandeep Desai, Abhishek Srivastava

答:
Ok, by a quick google search I found a cite from your first reference:

white box testing techniques are also called structural testing techniques, whereas black-box testing techniques are also called functional testing techniques

I guess you are referring to that. To my understanding the term "functional testing" is used here in a very broad meaning, just to emphasize the difference to "structural testing". From this point of view, "performance" or "security" are also "functions" of a program, since they can be observed by a black-box execution of the program, without knowing details of the source code.

Using the term "functional" in opposition to "non-functional", however, narrows the meaning down to "core functions" or "domain functions". This is a quite different point of view. So if someone speaks about "functional testing", you have to be careful what he might mean and interpret this in relation to the current context.


问:
Should an open source gem contain .rvmrc?
Using .rvmrc seems to be considered a best practice for apps.

But should an open source gem contain .rvmrc in their source code on Github? I think it's not good to require everyone who wants to contribute to use the exact same version of Ruby or gemset as you.

答:
By having the .rvmrc in your source control, you are not forcing everybody to use the same version of Ruby as you do. They can easily change the .rvmrc if they have a need to do so. You are merely explicitly telling them what version you used and therefore making it easier for them to start working with your project.

This is also an advantage for contributors as they won't run into version issues. If your contributors aren't using RVM then they will have to select the correct Ruby version by hand (or just hope for the best) instead of having it done for them automatically.

FYI there is an emerging standard for having a per project file ".ruby-version" that specifies the correct Ruby version in a simple way and RVM and several others Ruby version managers are already supporting it:
https://gist.github.com/fnichol/1912050


问:
Maintain a web application once the only developer is gone
I have a terminal disease and there is a very high chance that I will no longer be in this world by the end of the year.

I have developed a web application that it is extensively used in my family’s business (a small hairdressing shop). No member of my family has neither programming nor system administration skills. I have neither close friends with those skills.

The business makes at most 10k in net profits per year. In fact, the business profits can only afford to pay the salaries of its 3 employees (father, mother and sister) and those are quite low and decreasing each year due to the financial crisis. In fact, I am not an employee of my family’s business, I work for a normal software development company. I developed the application during my free time in order to help them.

So far I do not care if another business also uses my application or even if the application itself loses my ownership. I just want that my family’s business can continue using it, which means system administration support if something goes wrong and development for new features/bugs.

I would like to ask you if you could give me the measures you think I could take in order to guarantee as much as possible the continuity of the application.

The technologies of the application are:

Platform: Tomcat (Java), MySQL and Linux

Frameworks: mainly JPA and ZK

答:
Sorry to hear about your situation.

As for tips I can give, all the above answers are pretty valid. Another thing you could try is freelancing sites like Elance and Freelancer. You can find pretty cheap hourly paid developers that can make some quick maintenance work when needed.

Maybe you can start using it now and develop a relationship with a couple of freelancers which your family would be able to contact in the future when the need arises.


问:
Git Workflow - turning a local reposity into a "central" one
I have a local repository with a toy project that has turned out to be more serious than I had thought. So from a single development branch where I have carelessly committed, I have started to use branches kind of like in the famous http://nvie.com/posts/a-successful-git-branching-model/

I would now like to have a "central" remote repository that I can push my develop and master tree.

The first issue is: how do I do this. Do I initialize an empty repository on my server and reference to this repository as the remote origin in my local repository?

Do I have to create the branches in the remote repository beforehand or is it enough just to push them?

Secondly the first commits in my local repository are really awkward, so I would like to cumulate a lot of those early commits into one, either in the way of --no-ff or as I understand to squash them.

As I understand, this is only working with an intermediate branch. i.e. right now I have 2 branches "develop" and "master" in my local repository. I came up with two ideas how to "change history"

I create two branches develop-squashed and master-squashed. Rebase my original branches to those while squashing commits I want to loose. Upon having -squashed branches being equivalent with the original master and develop branches, I can delete the original ones and "rename" the *-squashed branches to master and develop.

Finally I can push master and develop into the remote repository.

Is that the way to go?

How can I make sure that by rebasing, both branches master and develop both have the same history up to the point when I started to follow the "successful git branching model"? (They have the same history up to that point at the moment).

答:
You have to first clean up the history, than create the central repository on server. Because once you publish the history, you won't be able to get it back.

If the branches have common history throughout the period you want to modify, than you will only have one "*-squashed" branch. Having develop only makes sense since the point it actually differs from master.

Have a look at the git filter-branch command. It should be able to do all the rebasing for you easily (as far as anything involving filter-branch can be called easy, but it will save you a lot of work in any case). The operation you'll want to do is basically simple; just for the first commit you want to keep replace the parent with the cleaned up one.

I would probably not bother unless there is anything that you either can't legally publish or is really very very embarrassing as somebody would have to have a lot of free time to actually look at the early history.

Just initialize empty repository on server, add it as remote and push the branches and tags, yes.


答:
I'm sorry about the situation you face, and I hope you are around to maintain the site for much longer than you expect.

This is a little bit hard to answer without knowing exactly what your site does, but most of the functions I imagine a beauty shop would have can be replaced with free or low cost, easy to use software.

Publicity/Information There are many free website and blog platforms available.  They are generally fairly easy to use.  One of the simplest solutions would be a Facebook page, which even someone with limited computer skills could handle.  This might be an ideal fit for a beauty shop that wants to stay connected with a group of local customers.

Appointment Management - Something as simple as a Google Calendar could be used to record appointments.  It can show availability online.  If you need to accept bookings via the web, there are lots of people offering free or cheap software that can do this.  I don't have any personal experience with them, but some research would probably reveal a workable, inexpensive solution.

Financial Records - Lots of desktop software is available that does this.

With tools like these, you probably won't get something quite as nice as your custom site.  But you should be able to get adequate functionality.  I think making this switch is necessary, because working on someone else's custom-built site is a time consuming job that requires a high level of skill.  Unless you find another developer who, like you, is willing to donate time, I don't see that as a realistic possibility.

Title: Maintain a web application once the only developer is gone

Body:
I have a terminal disease and there is a very high chance that I will no longer be in this world by the end of the year.

I have developed a web application that it is extensively used in my family’s business (a small hairdressing shop). No member of my family has neither programming nor system administration skills. I have neither close friends with those skills.

The business makes at most 10k in net profits per year. In fact, the business profits can only afford to pay the salaries of its 3 employees (father, mother and sister) and those are quite low and decreasing each year due to the financial crisis. In fact, I am not an employee of my family’s business, I work for a normal software development company. I developed the application during my free time in order to help them.

So far I do not care if another business also uses my application or even if the application itself loses my ownership. I just want that my family’s business can continue using it, which means system administration support if something goes wrong and development for new features/bugs.

I would like to ask you if you could give me the measures you think I could take in order to guarantee as much as possible the continuity of the application.

The technologies of the application are:

Platform: Tomcat (Java), MySQL and Linux

Frameworks: mainly JPA and ZK


答:
Post-edit #1 - my answer works equally well for argument names or specifying the variable type, which is what I first read your question as.  My answer is driven in part because I had a similar discussion recently with the use of C#'s var auto-typing keyword and a code sample we received.

In my answer"it" == argument name || variable type

Option A

In cases where it's obvious from the type or immediate next use, then I would go ahead and exclude it in order to reduce the amount that needs to be read.

In other cases where it gives important information that's not obvious, then you should include it.

Caveats

What's obvious to you may or may not be obvious to the new developer reading the documentation.

If it could change then not including it could hide the fact that the documentation is now a bit out of date.  Conversely, it could actually reduce how quickly the documentation gets out of date if it switches from ObviousA to ObviousB.

Option B

If you need consistency throughout your documentation, then you should always include it.  As you stated, there will be cases where it isn't obvious so if you're picking between "always" and "never" then go with "always".

The caveat to Option B is that you are prioritizing consistency over potential readability.  It's a perfectly valid prioritization, but you want to be aware of making that decision.

post-edit #2 - if my answer isn't clear because I tried to be too generic, please let me know and I'll adjust it accordingly.


问:
Log design approach
Logging was always a nightmare for me! Now I have to implement it again for a proxy system.
In this proxy application, some systems ask proxy system to call some other services.
What I have to log is

Request Time

Requester IP

Request Parameters as XML

Requested Service Name

Requested Service Method

Response Time

Response data as XML

Response Message (If any exception occurs it will logged as Message)

I considered to append two lines to my methods:

```<code>// Log Request
Task.Factory.StartNew(() => Logger.Log(RequestParameters.ToXML(),Assembly.GetCallingAssembly().FullName, MethodBase.GetCurrentMethod().Name, DateTime.Now));

// Invoke requested service and get response

// Log Response
Task.Factory.StartNew(() => Logger.Log(Response.ToXML(), DateTime.Now));
</code>```

I also want to log nested transactions.

Assume a transaction contains a request and a response. A transaction may contains many other internal transactions. When I receive a request, I should register a transaction, and insert a request for it, later, when response received, I should update the transaction response. Please note that I'm trying to store request and response relationship for better tracking.

How can I safely add this logging procedure to methods? I want to restrict developers to implement this logging systems in all methods, some thing like interface or inheritance for method body is required. Can I do this by attributes? Then how?

答:
This is the hello world scenario for Aspect-Oriented Programming (AOP) and I'm a HUGE fan of it. Your mention/question of using attributes is exactly the implementation detail that is used.

My personal favourite for .NET, though not free (you can roll your own using reflection, and I have, but the performance is comparatively bad) is PostSharp .

Essentially, you have an Attribute that inherits from a PostSharp aspect attribute (eg. OnMethodBoundaryAspect). You would override OnEntry and OnExit to make your async call(s) to trace.

What happens is that PostSharp plugs into compilation and "weaves" the code from your aspect into the IL that gets produced by the compiler, so the performance is roughly identical to what it would be if you had hand-coded it in the method yourself.

Note: I have zero affiliation with postsharp, and have never had the opportunity (ie. budget) to use it in production - sadly. I have used AOP in .NET with success though.

Title: Log design approach


问:
What's the most absurd myth about programming issues?
To put it another way... What is the most commonly held and frustrating misunderstanding about programming, you have encountered?

Which widespread and longstanding myths/misconceptions do you find hard for programmers to dispel/correct.

Please, explain why this is a myth.

答:
That programming languages change all the time.

This might have been a long time ago in the past...

But nowadays the changes are mostly extra features which try not to break existing code.

ContentLicense: CC BY-SA 2.5


问:
Should I tell the interviewer I already know the answer to the question being asked?
In a programming interview if I am asked a question I already know the answer for, such as giving an algorithm for a particular problem. Should I disclose that to the interviewer? This issue only makes sense when there's a novelty aspect to the question.

One example is "How would you reverse each word in a string, but not their order?". There also seems to be a division between easier stuff, that you are "supposed" to know, such as my example and harder more contrived problems.

Whats your policy and rationale for dealing with this issue?  If you are already familiar with the question/brainteaser, should you disclose this in addition to answering the question?  Is there any ethical dilemma involved with not disclosing your prior knowledge of the question?

答:
I'd still answer the question. I interview programmers very frequently. I'm less interested in the fact that you can solve the problem (unless you simply can't) and more interested in how you solved the problem.

I ask lots, and lots .. and lots of annoying little questions during an interview that are specifically designed (and refined over time) to give me a very good understanding of your actual strengths verses what you put on your CV. I will do my very best to lead you along a trail of subjective banter and then hit you with increasingly harder problems.

Using Frank's example, FizzBuzz, the last thing I want to hear from you is "Oh yes, I know how to use the modulus operator ..." If I'm interviewing you, I know that. I might want to see how quickly your brain switches gears, or I might want to test how well you'll carry out an assignment that seems mundane and stupid. The point is, I'm not just testing your ability to solve problems.

I can make a mouse trap with hundreds of moving parts. If a company is in the business of catching mice .. well ... :)


问:
What is Delegation and why is it important in iOS programming?
At the moment I am teaching myself iOS programming, and one concept I find really hard to wrap my head around is delegation. What is it? Why and how is it used? What is the advantage? The technical writing from the book I'm reading makes it hard to understand. </p>

答:
To understand delegates, you have to understand protocols.

A protocol is like a service contract. When an object (most often a UIViewController subclass, but not always) signs that contract, it is saying "I am interested in providing logic to back the message you send me". This is similar to NSNotificationCenter in regards to signing up for a level of interest, the difference being an object that employs delegation can only have one delegate at a time, where as multiple objects can sign up for the same NSNotification.

Apple uses delegation pervasively. More and more, though, you're seeing Apple move a lot of their API over to blocks, which are similar to callbacks in other languages.

That being said, delegation helps maintain MVC, even though I would argue delegation is a design pattern in and of itself. It helps to separate models from controllers. Such as in John Cartwright's example, a UITableView knows how to display rows and sections. It knows how to reuse UITableViewCells for performance reasons. It knows all of the other stuff a UIScrollView knows. But it doesn't know which cells to display. It doesn't know what to populate those cells with. It doesn't know which cells to reuse for a given NSIndexPath. This really should be the job of the controller, anyways. Delegation allows the table view to offload this non-view logic onto an object that should have that responsibility anyways.

More than that, you're not locked into one delegate for the entire lifetime of an object. You could very easily have multiple datasources for a given UITableView and switch them around at run time as needed.

So, on the one hand, delegation is great for supplying data to and responding to interactions from an object. You'll see it in a lot of UIKit classes, such a UITableView, UIPickerView, UICollectionView, etc.

But delegation is also very useful when you want to pass information between objects. You can very easily create your own protocols and sign up your own objects to follow them. Furthermore, protocol methods are @required by default, but you can specify some methods to be @optional. This can give you some nice flexibility if you need it. Let's say you have a parent view controller and a child view controller. Maybe you're using the new Containment API to do this. Typically, if you need to pass information from the parent to the child, you do this with a property. Done. But what if you need to pass information from the child back to the parent? Maybe something changes in the child and you need to notify the parent. Sure, you could do some KVO on certain values. But maybe you want to know when a button is pressed. Simply create a new protocol in the child view controller

```<code>@protocol MyChildDelegate
- (void)buttonWasTappedInChild:(MyChildViewController *)childViewController;
@end

@interface MyChildViewController : UIViewController

@property (weak, nonatomic) id <MyChildDelegate> delegate;

@end
</code>```

In MyChildViewController, when your button is tapped, simply check if your delegate responds to the delegate message (if it's required and your delegate doesn't implement the method, you'll crash. You can make the method @optional if you need to) and send it:

```<code>- (IBAction)someButtonTapped:(id)sender {
    if ([self.delegate respondsToSelector:@selector(buttonWasTappedInChild:)]) {
        [self.delegate buttonWasTappedInChild:self];
    }
}
</code>```

Then set the delegate of your MyChildViewController to self and implement - (void)buttonWasTappedInChild:(MyChildViewController *)childViewController in your parent view controller. BOOM! You have information passed from a child up to the parent. The relationship between the two objects doesn't even need to be as close as parent/child. It's a service contract, so as long as the object signing up holds up its end of the bargain by implementing the required methods, you're golden!

NOTE: Delegates should be weak/assign properties, otherwise you'll enter a retain cycle where neither object can be deallocated.

Hope this helps!

Body:
To understand delegates, you have to understand protocols.

A protocol is like a service contract. When an object (most often a UIViewController subclass, but not always) signs that contract, it is saying "I am interested in providing logic to back the message you send me". This is similar to NSNotificationCenter in regards to signing up for a level of interest, the difference being an object that employs delegation can only have one delegate at a time, where as multiple objects can sign up for the same NSNotification.

Apple uses delegation pervasively. More and more, though, you're seeing Apple move a lot of their API over to blocks, which are similar to callbacks in other languages.

That being said, delegation helps maintain MVC, even though I would argue delegation is a design pattern in and of itself. It helps to separate models from controllers. Such as in John Cartwright's example, a UITableView knows how to display rows and sections. It knows how to reuse UITableViewCells for performance reasons. It knows all of the other stuff a UIScrollView knows. But it doesn't know which cells to display. It doesn't know what to populate those cells with. It doesn't know which cells to reuse for a given NSIndexPath. This really should be the job of the controller, anyways. Delegation allows the table view to offload this non-view logic onto an object that should have that responsibility anyways.

More than that, you're not locked into one delegate for the entire lifetime of an object. You could very easily have multiple datasources for a given UITableView and switch them around at run time as needed.

So, on the one hand, delegation is great for supplying data to and responding to interactions from an object. You'll see it in a lot of UIKit classes, such a UITableView, UIPickerView, UICollectionView, etc.

But delegation is also very useful when you want to pass information between objects. You can very easily create your own protocols and sign up your own objects to follow them. Furthermore, protocol methods are @required by default, but you can specify some methods to be @optional. This can give you some nice flexibility if you need it. Let's say you have a parent view controller and a child view controller. Maybe you're using the new Containment API to do this. Typically, if you need to pass information from the parent to the child, you do this with a property. Done. But what if you need to pass information from the child back to the parent? Maybe something changes in the child and you need to notify the parent. Sure, you could do some KVO on certain values. But maybe you want to know when a button is pressed. Simply create a new protocol in the child view controller

@protocol MyChildDelegate
- (void)buttonWasTappedInChild:(MyChildViewController *)childViewController;
@end

@interface MyChildViewController : UIViewController

@property (weak, nonatomic) id <MyChildDelegate> delegate;

@end

In MyChildViewController, when your button is tapped, simply check if your delegate responds to the delegate message (if it's required and your delegate doesn't implement the method, you'll crash. You can make the method @optional if you need to) and send it:

- (IBAction)someButtonTapped:(id)sender {
    if ([self.delegate respondsToSelector:@selector(buttonWasTappedInChild:)]) {
        [self.delegate buttonWasTappedInChild:self];
    }
}

Then set the delegate of your MyChildViewController to self and implement - (void)buttonWasTappedInChild:(MyChildViewController *)childViewController in your parent view controller. BOOM! You have information passed from a child up to the parent. The relationship between the two objects doesn't even need to be as close as parent/child. It's a service contract, so as long as the object signing up holds up its end of the bargain by implementing the required methods, you're golden!

NOTE: Delegates should be weak/assign properties, otherwise you'll enter a retain cycle where neither object can be deallocated.

Hope this helps!


问:
How do I handle having so many SQL queries?
I have an MVC3 project that uses SQL Server.

I use data from the SQL database all the time and I often find that I'm reusing/duplicating some SQL queries. I thought I'd solve this problem by creating a few static "helper" classes that just contain a bunch of static methods for retrieving common things.

```<code>GetAllUsers(database As MyEntity)
GetAllNonActivatedUsers(database As MyEntity)
GetUser(database As MyEntity, userId As Integer)
</code>```

The problem is that this made things slightly worse. Now instead of having SQL queries all over my controller actions, there are large numbers of them in these helper classes. The names of these methods are becoming silly.

```<code>GetPendingUserApplicationByApplicationId(database as MyEntity,
    applicationId As Integer, userId As Integer)
</code>```

At this stage I'm thinking of scrapping the helper classes and going back to just random SQL queries throughout my controller actions.

Where have I gone wrong and how do people manage their SQL queries?

Is it ok to duplicate SQL queries?

答:
Well, first of course, you are going to have lots of queries because you expect the application to do lots of things.

Databases have a couple of things that can help, but you can make things worse by using them badly.

ORMs are one tool that will help write the queries for you. But you will still have a lot of queries if you have a lot of database work that needs to be done.

Next, you can use Views to create some of the main things you will want to use over and over. Views are good for complex things that you will need to make sure have the same calculations in multiple situations. For instance, we have views that collect all the data from various table for financials which ensures that all financial data is based on the same set of business logic. Do not, however, use views to call views.

You can use stored procedures and then just call them in multiple places. (Make sure you put them in source control though, SPs are code!)

However, you may have to learn to live with the fact that there is lots of code. Our database has well over a thousand stored procedures. Organizing them by schema has helped. If your database doesn't have schemas, organizing by using a systematic naming convention helps. That way, you know all the things that relate to finance have the word finance in them and those relating to users have user in them. That helps you find the one you are looking for when you need to reuse it.

Code reuse can be a wonderful thing, but there is a very strong caveat when querying databases. If the queries are slightly different, then they must be two separate queries rather than one that sends more data than the application needs at that point. Adding fields you don't need to queries so you can use them elsewhere can cause horrible performance issues that are very hard to correct (I just spent several days trying to performance tune such a mess and ended up eliminating over 400 lines of unnecessary SQL! I also improved performance by cutting the time to execute more than 60%). So don't go on that path just to have fewer queries. More specific queries is generally better than fewer general ones for database performance.

ContentLicense: CC BY-SA 4.0


问:
Conducting a requirements analysis interview
Why do requirements interviews never pan out as they are planned - and how do I prepare for that? I'm looking for the following kind of help regarding how to prepare for these interviews and what I can pay attention to in order to make the most of them.

My information project, centered around management reporting within a firm, is currently in it's definition stage. All my stakeholders are managers of greater or lesser scope.

I had my previous two interviews planned out quite extensively, but on both occasions my interviewees both went off in completely different tangents, delivering quite interesting results. I completely ignored the question flow I had prepared, and tried to go along with the interviewees. But instead of going towards a common concept that can be developed on, I feel that I get in-depth pictures of each individual's local information requirements.

How can I conduct an interview that helps me get the participants on board and thinking towards a common solution, but doesn't inhibit their own thoughts which deliver me interesting material on data sources, formatting and communication paths?

答:
I've found requirements gathering to go most smoothly when done in three stages:

Get together to let the stakeholders talk only about the problem.  You want to gather as much information as possible about what the problem is with the current way they are doing things, only talking about potential solutions if it helps frame the problem better.  They need to get it off their chest anyway, and attempting to keep stakeholders from talking about the problem is usually futile, so you may as well plan for it.  Also, non-programmers find it easier to talk in these terms, so you get a better idea of the requirements if you welcome this part of the discussion.

Either yourself or in a smaller, more technical group, you translate the problem statement into some rough drafts of possible solutions, creating more than one option if necessary.

Get back together with the stakeholders to let them poke holes in the proposed solutions.  Make it clear how you've taken their problem description into account.  Refine the requirements together until everyone is happy, which might take more than one meeting.  Again, non-programmers find it easier to discuss a concrete proposal than to imagine potential abstract solutions.

Usually when people have problems, it's because they're trying to skip step 1 and cram steps 2 and 3 into the same meeting.


问:
Fastest way to find the closest point
I have a list in Python 2.7 of about 10000 point co-ordinates, like

```<code>[(168, 245), (59, 52), (61, 250), ... (205, 69), (185, 75)]
</code>```

Is there a faster way to search for all the points in a bounding box, instead of just iterating over the entire list each time and checking if the co-ord is inside the 4 sides??

I'm using this "algoritm" to see if any point, which is randomly moving, has come inside the stationary bounding box..(if it helps)

答:
As stated by you, there is no way of being faster than O(n). Every point in the list might be a hit, so you have to scan the entire list.

It would be possible to arrange the list such that you can terminate the search early if you can prove that none of the following points will be in the desired bounding box. For instance, by sorting the point by their X coordinates, you can stop searching when the value becomes higher than your upper boundary. Depending on what kind of point lists you get, other schemes may be more efficient.

Title: Fastest way to find the closest point


答:
If possible I'd use a different data structure, one that is designed for spatial indexing. e.g. a quadtree (there are many others though)

This should allow (assuming non-degenerate data) to find a closest point in typicaly O(log n) comparisons. You could also use a spatial DB to do this for you .

edit: quadtrees really help when your points are (relatively) static to your search box, your edit suggests you have the opposite problem in which case you may not be able to do better than O(n) i.e. you probably dont want to construct a quadtree every time the points move unless you are going to be checking many bounding boxes for each move

Title: Fastest way to find the closest point

Body:
I have a list in Python 2.7 of about 10000 point co-ordinates, like

```<code>[(168, 245), (59, 52), (61, 250), ... (205, 69), (185, 75)]
</code>```

Is there a faster way to search for all the points in a bounding box, instead of just iterating over the entire list each time and checking if the co-ord is inside the 4 sides??

I'm using this "algoritm" to see if any point, which is randomly moving, has come inside the stationary bounding box..(if it helps)


答:
If the points are constantly moving, then it's impossible to do better than O(n), because you have to check each point every time it moves.  You have some code somewhere that moves the points, just add the bounds check into that code.  Keeping a list sorted, or updating a quadtree or something would only be more efficient if the point positions were not changing frequently and instead you were checking several different bounding boxes, like searching for points on a map, for example.

If the points are moving according to a preset pattern, like in a straight line at a constant velocity, then you can change your algorithm to only do the bounds check when the direction or speed is changed.  For example, if you are moving one pixel per second, and the bounding box is 10 pixels away, you know you don't have to check that point for another 10 seconds.  100 points is a pretty small number though, and at that small of a scale, the overhead from the extra complexity may not outweigh the extra iterations of the simpler algorithm.

Also, that small of a scale makes me wonder if you're sure the bounds checking is your bottleneck.  A modern computer should be easily able to bounds check 100 points in under 10 microseconds.  Have you actually measured it?

Title: Fastest way to find the closest point


问:
A Unicode sentinel value I can use?
I am desiging a file format and I want to do it right. Since it is a binary format, the very first byte (or bytes) of the file should not form valid textual characters (just like in the PNG file header1). This allows tools that do not recognize the format to still see that its not a text file by looking at the first few bytes.

Any codepoint above 0x7F is invalid US-ASCII, so that's easy. But for Unicode it's a whole different story. Apart from valid Unicode characters there are private-use characters, noncharacters and sentinels, as I found in the Unicode Private-Use Characters, Noncharacters & Sentinels FAQ.

What would be a sentinel sequence of bytes that I can use at the start of the file that would result in invalid US-ASCII, UTF-8, UTF-16LE and UTF-16BE?

Obviously the first byte cannot have a value below 0x80 as that would be a valid US-ASCII (control)character, so 0x00 cannot be used.

Also, since private-use characters are valid Unicode characters, I can't use those codepoints either.

Since it must work with both little-endian and big-endian UTF-16, a noncharacter such as 0xFFFE is also not possible as its reverse 0xFEFF is a valid Unicode character.

The above mentioned FAQ suggests not using any of the noncharacters as that would still result in a valid Unicode sequence, so something like 0xFFFF is also out of the picture.

What would be the future-proof sentinel values that are left for me to use?

1) The PNG format has as its very first byte the non-ASCII 0x89 value, followed by the string PNG. A tool that read the first few bytes of a PNG may determine it is a binary file since it cannot interpret 0x89. A GIF file, on the other hand, starts directly with the valid and readable ASCII string GIF followed by three more valid ASCII characters. For GIF a tool might determine it is a readable text file. This is wrong and the idea of starting the file with a non-textural byte sequence came from Designing File Formats by Andy McFadden.

答:
0xDC 0xDC

Obviously invalid UTF-8 and ASCII

Unpaired trail surrogate in lead position regardless of endianess in UTF-16. It doesn't get more invalid UTF-16 than that.

Title: A Unicode sentinel value I can use?


问:
Architecture suggestions on a multi-project multi-database 'intranet'
Here is the situation I have inherited:

We have approximately 10 websites (Asp.net web forms) that each have their own database.

Each of these databases houses some site specific data, and each has some form of a user table that will map to what is called a User Service.

The User Service is just another website that has a database with one table (User) that have about 3 different unique identifiers for a user: a UserId guid, an internal desktop application id (third party app, needed to map back to it), and a username.

On all the different websites the databases have the User table, sometimes called Person, or Student, or whatever else, and they are inconsistent in which UserService.User.[IdentifyingColumn] they map to.

The Problem:

It is getting to a point where these application are now needing to share some data with each other, and I see that need increasing as the departments are streamlined even more.      With this current set up, it is a lot of hoop jumping to get the right UserId column to match to the right UserId column in the UserService.

Confused yet? Me too..

The Question:

How to approach correcting the issue? I have a few different ideas, some I like more than others, but in order to implement them I need some solid benefits I can bring up to the head of IT, as well as justify the programming time taken for the re-write.

Idea 1: Create a true intranet application. One web application with one database. This way they all live in the same project, and sharing data between the various departments is very simple and quick.

Idea 2: Create a "Master Key" identifying field that will be the end all to identify a user. Make this key available on each database and so there will not be any odd mapping and the various sites can talk to each other. To me this one solves one problem, mapping each db to the next one. It is still very fragmented and there is very little code re-use.

Idea 3: Work with it in the current form trying to continue the present fashion of many small databases and sites.

Which of the above options would you suggest, and why?

答:
The scenario you describe is a perfect match for a Single Sign On service. There are several paths you can follow to a solution:

You mention that this is for an Intranet. Assuming you are using Windows Server for security, you have everything you need in place for a Single Sign-On solution. Your applications can use Windows Authentication and the users on the Domain will automatically be logged in once they navigate to your site.

OAuth is another option for creating the infrastructure you mentioned (one application provides information to another based on trust established by an Identity Provider). Again, Microsoft provides an OAuth solution called Windows Identity Foundation (WIF) that provides the infrastructure for what's called "Claims Aware" applications.

Windows Azure Access Control Service/Active Directory is an option if you see the need to expose your application to the public. You'll even be able to configure your app to accept logins from third party providers like facebook, Windows Account (formerly live ID) and Twitter.

Using these as a foundation for your identity management, will allow you to focus more on the important parts of your application.


答:
Assuming a Windows domain environment, Windows authentication would be by far the most sensible way to go.

Unless the sites and databases are all very small, I would avoid having 1 merged site/database for all and keep the sites all separate for a couple of reasons:

avoid downtime for all systems if you only need to change one system

different teams can work in isolation on different apps

Title: Architecture suggestions on a multi-project multi-database 'intranet'

Body:
Here is the situation I have inherited:

We have approximately 10 websites (Asp.net web forms) that each have their own database.

Each of these databases houses some site specific data, and each has some form of a user table that will map to what is called a User Service.

The User Service is just another website that has a database with one table (User) that have about 3 different unique identifiers for a user: a UserId guid, an internal desktop application id (third party app, needed to map back to it), and a username.

On all the different websites the databases have the User table, sometimes called Person, or Student, or whatever else, and they are inconsistent in which UserService.User.[IdentifyingColumn] they map to.

The Problem:

It is getting to a point where these application are now needing to share some data with each other, and I see that need increasing as the departments are streamlined even more.      With this current set up, it is a lot of hoop jumping to get the right UserId column to match to the right UserId column in the UserService.

Confused yet? Me too..

The Question:

How to approach correcting the issue? I have a few different ideas, some I like more than others, but in order to implement them I need some solid benefits I can bring up to the head of IT, as well as justify the programming time taken for the re-write.

Idea 1: Create a true intranet application. One web application with one database. This way they all live in the same project, and sharing data between the various departments is very simple and quick.

Idea 2: Create a "Master Key" identifying field that will be the end all to identify a user. Make this key available on each database and so there will not be any odd mapping and the various sites can talk to each other. To me this one solves one problem, mapping each db to the next one. It is still very fragmented and there is very little code re-use.

Idea 3: Work with it in the current form trying to continue the present fashion of many small databases and sites.

Which of the above options would you suggest, and why?


答:
In UTF-8, the bytes C0, C1, and F5 - FF are illegal. The first byte must either be ASCII or a byte in the range C2-F4, any other starting byte is not valid UTF-8.

In UTF-16, the file normally starts with the Byte Order Mark (U+FEFF), otherwise applications have to guess at the byte order. Codepoints in the range D800-DBFF are lead bytes for a surrogate pair, and DC00-DFFF are the trailing bytes for a surrogate pair.

Thus, I'd use the byte combo F5DC. These two values are:

Not ASCII

Not valid UTF-8

Either interpreted as a UTF-16 trailing byte in a surrogate pair (not legal), or the codepoint U+F5DC, which is a private use character, but only by applications that stubbornly try to interpret this as UTF-16 even without a BOM.

If you need more options, F5DD through to F5DF all have the same 3 properties, as do F6DC - F6DF, F7DC - F7DF and F8DC - F8DF, for a total of 16 different byte combos to pick from.

Title: A Unicode sentinel value I can use?

Body:
I am desiging a file format and I want to do it right. Since it is a binary format, the very first byte (or bytes) of the file should not form valid textual characters (just like in the PNG file header1). This allows tools that do not recognize the format to still see that its not a text file by looking at the first few bytes.

Any codepoint above 0x7F is invalid US-ASCII, so that's easy. But for Unicode it's a whole different story. Apart from valid Unicode characters there are private-use characters, noncharacters and sentinels, as I found in the Unicode Private-Use Characters, Noncharacters & Sentinels FAQ.

What would be a sentinel sequence of bytes that I can use at the start of the file that would result in invalid US-ASCII, UTF-8, UTF-16LE and UTF-16BE?

Obviously the first byte cannot have a value below 0x80 as that would be a valid US-ASCII (control)character, so 0x00 cannot be used.

Also, since private-use characters are valid Unicode characters, I can't use those codepoints either.

Since it must work with both little-endian and big-endian UTF-16, a noncharacter such as 0xFFFE is also not possible as its reverse 0xFEFF is a valid Unicode character.

The above mentioned FAQ suggests not using any of the noncharacters as that would still result in a valid Unicode sequence, so something like 0xFFFF is also out of the picture.

What would be the future-proof sentinel values that are left for me to use?

1) The PNG format has as its very first byte the non-ASCII 0x89 value, followed by the string PNG. A tool that read the first few bytes of a PNG may determine it is a binary file since it cannot interpret 0x89. A GIF file, on the other hand, starts directly with the valid and readable ASCII string GIF followed by three more valid ASCII characters. For GIF a tool might determine it is a readable text file. This is wrong and the idea of starting the file with a non-textural byte sequence came from Designing File Formats by Andy McFadden.


答:
Single Sign On is an excellent idea.  Just so you know, you don't necessarily need to use a specific technology, such as Active Directory, WIF or OAuth.  You can implement it with just ASP.NET forms auth.  Here's how you do it:

Selling it to the head of IT

Don't make it just about developer happiness, there's a significant user happiness benefit of SSO.

Take your current workload and project the time required to keep mucking with an imperfectly architected system over a year.  Compare that with the time required to do a re-write.  Most of the time, if it breaks even after a year, it's a good trade.

Deciding on How

Figure out the most common way users are identified, (such as AD name, or email address) and try to centralize on that - it should reduce the scope of the re-write.

Once you have the best key defined, pick a technology or method that leverages that.

Random Tips from my experience

I've had the least friction with OAuth.  Mainly because we used google apps, so everyone already had a corporate google account.

Windows Authentication has problems depending on if it's set up with NTLM or Kerberos - I had a particular problem with NTLM over a VPN.

ADFS was just too much hassle to get working correctly for anyone outside of our domain, it really wasn't worth it.

To keep your application maintainable, I would make the configuration as simple as possible.  To your question about the separate databases, if they don't buy you anything by being separate, reduce the complexity and merge them.  Since they are an intranet, I'm assuming they won't ever be deployed separately.


答:
As Dave said in the comments, there's always a tradeoff.

I see a few points in favour of your approach:

It's self-documenting: void AnswerRequest(CertificateRequest request) might be more descriptive than void AnswerRequest(byte[] request).

You will probably create a few methods that operate on the byte[]. They might fit nicely as instance methods on your wrapper class: request.getPublicKey() is nicer than Pkcs10Tools.ExtractPublicKey(requestByteArray).

Information hiding: If you ever decide to change the internal representation of the class (e.g., by adding fields to cache certain values extracted from the byte array), you can do that without changing the code using the class.

It's extendable, if you decide to go from a simple wrapper to a more advanced class.

Drawbacks:

If most of the work is done by external libraries, the consumers of your class will be using new CertificateRequest(myByteArray) and request.getByteArray() a lot.

Title: Is wrapping byte[] for stronger typing good practice?

Body:
I'm working on a Java-based library which makes use of PKCS #10 requests.  There are PKCS #10 libraries available for Java (Sun and IBM libraries that come with the respective JDKs), and the open-source Bouncy Castle library.

I'd rather not couple my library to another through the API, so my initial thought was to create a wrapper.  However, PKCS #10 is potentially complex, so the scope of the wrapper would expand quite quickly, and users of that wrapper would probably "unwrap" the wrapper and use one of the aforementioned libraries for any heavy-lifting, particularly if they use PKCS #10 in their own applications already.

My remaining option is to provide a simple wrapper around a byte array.  Is providing a very thin wrapper just for the sake of typing good practice?


问:
Written communication skills courses, how important are they for developers?
We usually worry about coding standards, ethics, latest technology etc. But at times we tend to ignore our writing skills and communicating skills.
Do we need to pursue a communication skills courses? Which ones do you prefer? Any online courses available which you might have tried? </p>

答:
The ability to write and communicate clearly is important, how you picked up that skill (course, self taught, mentored) isn't.

Amazon is chock full of books about it and personally that's the way I'd go as I think it's useful to have something you can dip back into every now and then, rather than a course which can fade in the memory if you don't get to put it to use immediately.


问:
What classes to put exactly in a class diagram?
What classes must I put in a class diagram? Only classes used in Business Layer and associations between them? Or also other classes in the Data Access Layer, Service Layer, etc.?</p>

答:
You should include all classes in your program, as a class diagram is suppose to describe the entire structure of your program/application.

However, in many applications this process could turn quite complex, so try to isolate the main components (Data Access Layer, Service Layer, Business Layer, etc.) and graph them independently, with proper documentation as to how they interact with each other.

For the class diagram to be useful, you need to divided it by layers, and by components within these layers, if necessary. If it is still too complex, it means you might need to rethink the relationships among your classes. Mapping them all out can help you understand which ones are needed, which ones can be combined, or which deleted, and improve it to the point you have a simpler class diagram, thus a simpler program structure.


答:
I try to include every class, but sometimes during implementation I may find that a class is rather big, so I split it into small helper classes.  I typically don't bother putting them into the class diagram because it would offer little value.  They are not design artifacts.

But start off by including everything in your diagram.

Title: What classes to put exactly in a class diagram?

Body: What classes must I put in a class diagram? Only classes used in Business Layer and associations between them? Or also other classes in the Data Access Layer, Service Layer, etc.?</p>


问:
Login on every page requires SSL on all pages
Our website has a login form that shows up in the header on every page on the website. This is what my boss wants however we need to get PCI compliant and it says any sensitive form (login/password) requires SSL. So does that mean the entire website has to be running under SSL while a user is not logged in?

Another question related to that, we have third party security software scanning and testing our site and it sends HTTP post to the login form on all the pages and reports it is unsecured because it submit's it under HTTP. I am wondering how a company like say Godaddy does it because they have a login/password on their homepage yet I can access it via HTTP and submit my login information just fine. By that logic they are not secure because it allows me to do that right? I feel like I am missing something but not sure what.

-EDIT-
Some information that came from the security site:

Description
A vulnerability exists that allows an attacker to harvest sensitive information (login credentials, etc) that are thought to be SSLsecured.

Specifically, a form was found on an HTTP (unencrypted) page that sends information to an HTTPS (encrypted) page. An attacker
could leverage cache poisoning (DNS/DHCP/ARP/etc) or another vulnerability (e.g. XSS) to cause the HTTP page to send
information to an attacker-controlled website instead of the legitimate HTTPS site.

Furthermore, toolkits exist to automate the process of harvesting such credentials, connecting to the legitimate HTTPS site and
establishing the attacker as a transparent proxy between the victim and the legitimate host where the attacker sees all
information in cleartext (including login credentials, etc).

Victim<---------HTTP--------->Attacker<---------HTTPS--------->Legitimate Site

CVSS Score
2.1

Solution

Do not allow any information you want SSL secured to originate from an unsecured page.

答:
Technically, only the target of the form needs to be a SSL protected page for the submission to be encrypted. I saw this done at a previous job where we had a login form in the header.

HOWEVER

By doing this you are losing the clarity that we've been telling users to look for. Users are instructed to look to the URL bar to see if the website is using an encrypted connection for their information. By having the page not delivered via SSL, users may mistakenly believe that their form (username and password) isn't encrypted either.

Furthermore, as pointed out by Craig below, if the page you're submitting from isn't encrypted, you cannot assert that the page has not been intercepted and altered. That familiar form that you know has always submitted to a HTTPS url may have been intercepted and altered before it was rendered.

Your best bet is to just offer SSL on all pages if you insist on having the login form in the header. SSL is relatively cheap to implement as far as server resources, and it gives your users the extra security they deserve.


问:
Version control: Dealing with incomplete/broken code
It seems to be a generally accepted good practice not to push invalid, broken, or incomplete code. But one of the huge advantages of version control systems is that it gives you a remote place for your code, so you can work on the same codebase from more than one place.

Suppose you are working on a feature with a couple other developers, and a bad winter storm is announced; everybody agrees to go home and keep working rather than get caught in the storm, but nobody is at an ideal stopping place. What do you do?

Create different branches for each developer and commit your changes to that, push those branches to remote and hope you can clean it up later on remote without making life difficult?

Create a different remote just for incomplete code?

Copy your code to your personal flash drive and hope you don't lose it later, or get caught violating company policy?

Something else?

(We use git, but I would hope the answer could be general to any version control system.)

答: Branches are your best option.  The golden rule is to not break the build.  Assuming that is the main trunk and is properly building, then creating a branch and putting your temporary work there is fine.  I much rather see incomplete work stored in version control than left on a computer that gets destroyed though.</p>


答:
Exactly those classes which are necessary to understand the aspect of the system which that particular class diagram depicts.

It could be the entire domain model, or all classes that make up the external API of a particular layer or subsystem, or whatever you think is important.

But note that class diagrams are not the only type of diagram, nor the most useful one.


问:
Single-Tenant Databases - creating and updating new tenants via PHP
We've built a single-tenant webapp in PHP and as it stands each hosted 'site' has its own database.

However we need to be able to run a script to create their database, assign a mysql user, and insert the default sql.

Now, we've got the database and user stuff working fine, its just the importing of the SQL. From what I can tell, PHP quite simply sucks when it comes to handling sql files, so storing a 'template' sql file seems to be out of the question.

My next thought was maybe storing a live database which is then cloned, giving the site its pre-populated database, however I cant see how this would work.

At the same time, I'd rather not 'hard code' the table creations into PHP as if we perform any updates we want to be able to update the SQL direct from our backend control panel.

Surely there has to be a logical way of handling creations and updates on a multi-tenant SaaS?

答:
We ended up going with a rather dirty method.

The sql file has a comment below each query like so:

```<code>-- split --
</code>```

When the sql file is loaded up by the php script, it simply explodes the sql data, using the split. It then just loops through the exploded array data and runs each query.

I dont like it, but its the best option out of a bad bunch really.

Body:
We ended up going with a rather dirty method.

The sql file has a comment below each query like so:

-- split --

When the sql file is loaded up by the php script, it simply explodes the sql data, using the split. It then just loops through the exploded array data and runs each query.

I dont like it, but its the best option out of a bad bunch really.


问:
Why can't the PHP engine handle HTTP communication?
The PHP engine interprets the PHP code and is perfectly capable of working with sockets, forming HTTP packets, etc.  Why then do we need a separate Apache server, when the http serving duties could be embedded into the php application along with the page creation code?</p>

答:
As of PHP 5.4 we don't need a separate web server, the CLI SAPI provides one build in. It's a fairly new addition to the language, and I wouldn't use it on production:

This web server is designed for developmental purposes only, and should not be used in production.

The build in web server might not be ready for production (yet?), but it does prove that PHP is more than capable of working without a third party web server. As for building a web server in PHP, that's also possible and a good example is nanoweb. The project appears to be dead, but you can still download its source and fool around with it.


答:
In addition to Yannis' answer, I want to add a few points.

The PHP engine can handle sockets so you could write a basic web server. You can also write a web server in Visual Basic 6 with the Winsock control - but it's not the right tool for the job.

Apache is a hugely powerful web server. It makes no sense to reinvent the wheel, particularly for a non-commercial project with limited scope, when the PHP team can leverage the testing, research and development that went into building Apache.

The other thing you definitely need to consider is that PHP doesn't support threads. There are workarounds (using shell_exec, for example), but you would be unable to write a multithreading server.

Title: Why can't the PHP engine handle HTTP communication?

Body: The PHP engine interprets the PHP code and is perfectly capable of working with sockets, forming HTTP packets, etc.  Why then do we need a separate Apache server, when the http serving duties could be embedded into the php application along with the page creation code?</p>


答:
A class diagram represents an individual component of a system, or the system as a whole. At the highest level you have a System context diagram which shows the individual components of a system.

Class diagrams could represent all classes in a small project however you would be far better placed to have multiple diagrams representing each component in your project.


答:
If you're trying to use a non-printable character to indicate "not text," then you'll find it hard to beat 0x89:

It's outside the US-ASCII range

In ISO-8859-1 it's a non-printable character ("CHARACTER TABULATION WITH JUSTIFICATION "). Likewise with Shift-JIS, which I believe is still in common use. Other 8-bit encodings may, however treat this as a valid character.

In UTF-8 it's an invalid first-byte for a multi-byte sequence (top bits are 10, which are reserved for characters 2..N of a multi-byte sequence)

Generally, when you form magic numbers, "non-text" is a minor point. I'll have to look up the reference, but one of the standard graphics formats (TIFF, I think) has something like six different pieces of useful information from its magic number.

Title: A Unicode sentinel value I can use?


问:
How to rewrite from scratch a code for which I own the copyright so I can use it on my job without losing the rights to the first version?
Well I don't want to make it open-source! That's the problem. But I do want to use it on my current job. Company did not agree to sign any alternative license with me and told me to rewrite everything from scratch so they will own it. :(

So how can I do it in a safe way so later on the company don't come back to me and say that I am using the code I wrote for them, which will be similar to the first version I wrote and own the copyright, on my personal projects or even on another job?

How would you rewrite a second version of a hash map without making it look like the first version? This sounds kind of hard to me. :(

答:
This is a great opportunity to use a pre-existing third-party open source solution, if one exists for your use case. Consider the advantages to both you and your employer:

You

No need to worry about messy IP.

You can learn an industry standard framework or library, which is something you can add to your resume.

Your Employer

No need to worry about messy IP.

No need to spend money paying an employee to write something from scratch.

The code is more likely to have been tested by multiple people in multiple environments, meaning it should be more stable and secure.

If the open source project is well known, it will be easier to bring in other programmers in the future.


答:
First, you should consult an attorney to find out what options you have.

But, a hashmap is a standard collection, if you have made one that has a specific purpose, change the data types it is working with, perhaps, and it will be different, especially if you can have some attributes in one program that isn't in the other.

And, if you sit down with a blank sheet of paper and rewrite the code, I expect it will be different, as you have probably learned some ideas since you wrote your original one.

IP is always tricky as they can't tell you to not use what you have learned, but don't copy from your own projects, just write everything from scratch, and it will help to alleviate these issues, I expect.

But, again, talk with a lawyer.

Title: How to rewrite from scratch a code for which I own the copyright so I can use it on my job without losing the rights to the first version?

Body:
Well I don't want to make it open-source! That's the problem. But I do want to use it on my current job. Company did not agree to sign any alternative license with me and told me to rewrite everything from scratch so they will own it. :(

So how can I do it in a safe way so later on the company don't come back to me and say that I am using the code I wrote for them, which will be similar to the first version I wrote and own the copyright, on my personal projects or even on another job?

How would you rewrite a second version of a hash map without making it look like the first version? This sounds kind of hard to me. :(


答:
Writing skills and communication skills are incredibly important.  There's a quote by Karl Fogel http://www.producingoss.org "S/he who communicates the best, has the most influence in a project".

In other words, you might be a nova-hot programmer, but if you can't communicate your ideas and changes to the rest of your team, your contributions won't make it.

As Jon stated you don't need to learn from a course, but I'd recommend at least learning from someone who is an expert in professional writing. They can help you shape your writing and once you get into a good habit you'll be fine for the rest of your career.  For example I'm currently writing a technical book and both my editor and an experienced author have helped me immensely in changing my written prose into something that readers can hopefully learn from.

Don't neglect the other types of communication, there are still many people who prefer phone calls, in person meetings, IRC or other forms (we all absorb information differently).  Always try to find out the preferred method of the people you are working with.

Title: Written communication skills courses, how important are they for developers?

Body:
We usually worry about coding standards, ethics, latest technology etc. But at times we tend to ignore our writing skills and communicating skills.
Do we need to pursue a communication skills courses? Which ones do you prefer? Any online courses available which you might have tried? </p>


问:
How would I combine 'Command' and 'Composite' to simulate a time delay?
As a learning exercise (I am not in school - just an old guy trying to learn something new), I am trying to write a logic gate simulation that incorporates propagation delay. The user should also be able to group gates together to create higher-level objects.

I want to apply design patterns to my problem, but I am having a hard time.

I am reading Head First Design Patterns, and I see that the Command pattern is a good way to simulate electrical pulses through a circuit with a delay. I also see that the Composite pattern is a good way to simulate nested units. I just don't know how to mix the two.

In other words, as I loop through my gates, I see that gate 'x' should fire. It has a 15 nanosecond delay, so I create a command with a time stamp of 15 ns from current game time. Where is the dispatcher? In the example of the diner, with the command being the 'Order', the waitress and the cook each dispatch the command and have the option of introducing a delay. If I have a 'composite' gate, does it also have its own dispatcher? Do I need to use a Singleton to manage the queue?

I read what I could find, but I still need a push in the right direction:

https://stackoverflow.com/questions/2015549/using-command-design-pattern

https://stackoverflow.com/questions/12016314/client-server-command-design-pattern-with-variable-delays

https://stackoverflow.com/questions/10560892/composite-of-commands-design-pattern

https://stackoverflow.com/questions/8874705/how-can-i-calculate-propagation-delay-through-series-of-combinational-circuits-u

答:
You may want to look at an example from Programming in Scala, as they have a simulator that does what you are trying to do in Java:

http://www.cs.helsinki.fi/u/wikla/OTS/Sisalto/examples/html/ch30.html#sec6

By looking at their approach you may find how to change your program to get the behavior you want.

You mentioned that you can't add it easily, so why not explain what your approach is, and what the difficulty that you encounter is, so people can give you some suggestions you may not have considered.

As mentioned, design patterns are ways to talk about what your code is doing, as a shorthand, but the idea of trying to force design patterns in just seems like a bad idea.

Basically a propagation delay shouldn't be hard.

You can have a base class that is Gate, and in her put in a delay.

All gates extend from this, and set the actual delay.

Now, when you are following a signal, when in a gate, that thread may sleep for the simulated delay, but this also means you need to map the real-time to your simulated time, as your simulator will be slower than a real system would be.

If you find that you have too many threads, then just put into a sorted list, by next one on top, and when you pause, just put the time the delay is done and on each loop the simulator will pick those that are now ready, do the next action, and then the next delay happens.

This would be similar to a game loop.


答:
In other words, as I loop through my gates, I see that gate 'x' should fire.

Then you're not using the command pattern.

If I have a 'composite' gate, does it also have its own dispatcher?

Dear god no. The entire point of the composite pattern is that you can supply a composite object to a location that is expecting merely one object. This allows you to compose behavior in a sane way.

Do I need to use a Singleton to manage the queue?

Hell no. Do you only have one cook and one waitress in the entire world? Do they only have one kitchen?

Mixing the command and composite pattern is fairly straight-forward. You have some interface that represents a command. Each concrete command can override (or otherwise satisfy it in non-inheritance languages) that interface to provide some behavior. Your delay is one such simple behavior.

The composite pattern provides two (or more) objects/behaviors behind a single interface. The simplest use for this example would be a composite command that takes two other commands and then when told to execute, triggers the two stored commands. This way you can take your isolated 'delay' command and any arbitrary other command to create a delayed command.

Title: How would I combine 'Command' and 'Composite' to simulate a time delay?

Body:
As a learning exercise (I am not in school - just an old guy trying to learn something new), I am trying to write a logic gate simulation that incorporates propagation delay. The user should also be able to group gates together to create higher-level objects.

I want to apply design patterns to my problem, but I am having a hard time.

I am reading Head First Design Patterns, and I see that the Command pattern is a good way to simulate electrical pulses through a circuit with a delay. I also see that the Composite pattern is a good way to simulate nested units. I just don't know how to mix the two.

In other words, as I loop through my gates, I see that gate 'x' should fire. It has a 15 nanosecond delay, so I create a command with a time stamp of 15 ns from current game time. Where is the dispatcher? In the example of the diner, with the command being the 'Order', the waitress and the cook each dispatch the command and have the option of introducing a delay. If I have a 'composite' gate, does it also have its own dispatcher? Do I need to use a Singleton to manage the queue?

I read what I could find, but I still need a push in the right direction:

https://stackoverflow.com/questions/2015549/using-command-design-pattern

https://stackoverflow.com/questions/12016314/client-server-command-design-pattern-with-variable-delays

https://stackoverflow.com/questions/10560892/composite-of-commands-design-pattern

https://stackoverflow.com/questions/8874705/how-can-i-calculate-propagation-delay-through-series-of-combinational-circuits-u


答:
In order to be secure, the form must be hosted on a page delivered via SSL.  Without SSL, the end user has no way of knowing that the form data will be delivered where they expect it to be  delivered -- the action of the form could have been tampered with by an attacker while they were downloading the page, or they could be looking at a fake version of your site produced by a server they were redirected to via a DNS hijacking attack, or similar.

That said, while I'm not a PCI compliance expert, I was under the impression that the PCI regulations only apply to the transmission of cardholder data, and that therefore only payment-related forms need to be protected.  Unless you are holding users' payment details permanently and allowing them to generate additional transactions without confirming that they hold the card, login forms should not be required to be PCI compliant.

Title: Login on every page requires SSL on all pages

Body:
Our website has a login form that shows up in the header on every page on the website. This is what my boss wants however we need to get PCI compliant and it says any sensitive form (login/password) requires SSL. So does that mean the entire website has to be running under SSL while a user is not logged in?

Another question related to that, we have third party security software scanning and testing our site and it sends HTTP post to the login form on all the pages and reports it is unsecured because it submit's it under HTTP. I am wondering how a company like say Godaddy does it because they have a login/password on their homepage yet I can access it via HTTP and submit my login information just fine. By that logic they are not secure because it allows me to do that right? I feel like I am missing something but not sure what.

-EDIT-
Some information that came from the security site:

Description
A vulnerability exists that allows an attacker to harvest sensitive information (login credentials, etc) that are thought to be SSLsecured.

Specifically, a form was found on an HTTP (unencrypted) page that sends information to an HTTPS (encrypted) page. An attacker
could leverage cache poisoning (DNS/DHCP/ARP/etc) or another vulnerability (e.g. XSS) to cause the HTTP page to send
information to an attacker-controlled website instead of the legitimate HTTPS site.

Furthermore, toolkits exist to automate the process of harvesting such credentials, connecting to the legitimate HTTPS site and
establishing the attacker as a transparent proxy between the victim and the legitimate host where the attacker sees all
information in cleartext (including login credentials, etc).

Victim<---------HTTP--------->Attacker<---------HTTPS--------->Legitimate Site

CVSS Score
2.1

Solution

Do not allow any information you want SSL secured to originate from an unsecured page.


答:
You need to speak with an attorney who specializes in copyright.  That's copyright, not intellectual property. "Intellectual property" is a false combination of patent and copyright, which are two completely separate fields of law.

I'm assuming you're in the United States for the rest of this.

My personal recommendation is that, before you go any farther, you take your current source and do a formal copyright registration on it, including filing a complete copy of your work with the US Copyright Office, just like with a book or a song.  (Note: Filing a full copy of the work along with the registration application is required by law for registration.)

Every copyright attorney in the United States will tell you that there is no substitute for a copyright registration certificate.  There has been exactly one case* in all of history where the guy with the copyright registration certificate didn't win.

Copyright registration is cheap.

After you have the copyright registration certificate in your hands, then you start doing their rewrite.  You can start doing design work, but do not write a single line of their code without first protecting yours.

 * (Specifically, that was the George Harrison "My Sweet Lord" case: although the Beatles did have the copyright registration certificate, the judge ruled that there was no possible way he could have completely independently reinvented the melody and organization from "He's So Fine" (The Chiffons): there HAD to have been copying, even unconsciously.)


答:
Section 6.3 (a) of the Self-Assessment Questionnaire D (https://www.pcisecuritystandards.org/documents/pci_saq_d_v2.pdf) says

6.3 (a) Are software development processes based on industry
standards and/or best practices?

I would say that encrypting login information is based on best practices, and not doing it definitely isn't. BTW remember that you can't force a user to submit data using SSL - that's impossible. Anyone can submit anything they want, it's up to you how to treat it.

(BTW one common gotcha is not protecting against XSS properly, if you are using ASP.NET MVC check out the @Html.AntiForgeryToken() function call. And obviously don't allow SQL injection (or command injection) but you already knew that :)

Also, section 8.4 says:

"8.4 (a) Are all passwords rendered unreadable during transmission and storage on all system components using strong cryptography?

Note that section 8 is actually talking about assigning unique IDs to each person with computer access, but you could argue that it's pretty much indicative of needing to securely encrypt passwords when logging into your website.

So depending on your assessment level (you might be A, B, C or D) you will need to encrypt login information for PCI compliance.

Oh and just because another company who claims to be PCI compliant does something strange, doesn't mean that you can too - definitely not a good guide to go by. Maybe they got special dispensation or have another compensating measure. (IMHO, be wary of anyone who tells you about what is compliant and what isn't, you need to get yourself a QSA - Qualified Security Assessor who can give you an answer).


问:
Polling and control devices
I am in the early stages of planning for an input device which will consist of some as-yet-to-be determined number pf physical controls. From previous experience with such devices I have found that it would be extremely advantageous to have the device return data about the state of all controls in response to a query from the system, as opposed to reporting changes as they occur.

Assuming an acceptable poll frequency of 1000 queries per second or higher, is the embedded hardware sufficiently advanced to support this? Would a driver for such a device be excessively resource-intensive? What would a good ballpark estimate for the ram/cpu required on both the "server" and "client"?

答:
Assuming an acceptable poll frequency of 1000 queries per second or
  higher, is the embedded hardware sufficiently advanced to support
  this?

The short answer is yes :-). At 1000 queries/second, you have 1 millesecond to receive, handle, and reply to each query. There are several factors to consider. Two of the more important ones are:

Do I have enough processing instructions to receive, handle and reply to the query. This includes reading the query, parsing the query, reading data from hardware registers, formatting the data for output, sending data, and overhead associated with handling the interrupt.

Does the I/O channel being used have the bandwidth to carry the data?

You can get reasonably-priced dual core ARM processors on development boards running in the GHz range, which gives you a million instructions every millesecond. With a USB 2.0 interface, you can transfer up to 480K bits (15000 32 bit words) in the same period of time.

Would a driver for such a device be excessively resource-intensive?

No. Assuming a multi-core processor operating > 1 GHz, if your interrupt handling overhead and processing is 20K instructions, you are using ~ 1% of the CPU to handle your interrupts.

What would a good ballpark estimate for the ram/cpu required on both
  the "server" and "client"?

The RAM requirements depend on how much your application needs to cache. On the embedded device, you might size your RAM to handle three buffers, one to read information from the physical controls, one to hold the data while it is being formatted for output, and another buffer for the output itself. Each buffer is sized based on the number of bits of information per device.

Title: Polling and control devices


问:
Why use a database instead of just saving your data to disk?
Instead of a database I just serialize my data to JSON, saving and loading it to disk when necessary. All the data management is made on the program itself, which is faster AND easier than using SQL queries. For that reason I have never understood why databases are necessary at all.

Why should one use a database instead of just saving the data to disk?

答:
You can query data in a database (ask it questions).

You can look up data from a database relatively rapidly.

You can relate data from two different tables together using JOINs.

You can create meaningful reports from data in a database.

Your data has a built-in structure to it.

Information of a given type is always stored only once.

Databases are ACID.

Databases are fault-tolerant.

Databases can handle very large data sets.

Databases are concurrent; multiple users can use them at the same time without corrupting the data.

Databases scale well.

In short, you benefit from a wide range of well-known, proven technologies developed over many years by a wide variety of very smart people.

If you're worried that a database is overkill, check out SQLite.


答:
Whilst I agree with everything Robert said, he didn't tell you when you should use a database as opposed to just saving the data to disk.

So take this in addition to what Robert said about scalability, reliability, fault tolerance, etc.

For when to use a RDBMS, here are some points to consider:

You have relational data, i.e. you have a customer who purchases your products and those products have a supplier and manufacturer

You have large amounts of data and you need to be able to locate relevant information quickly

You need to start worrying about the previous issues identified: scalability, reliability, ACID compliance

You need to use reporting or intelligence tools to work out business problems

As for when to use a NoSQL

You have lots of data that needs to be stored which is unstructured

Scalability and speed needs

You generally don't need to define your schema up front, so if you have changing requirements this might be a good point

Finally, when to use files

You have unstructured data in reasonable amounts that the file system can handle

You don't care about structure, relationships

You don't care about scalability or reliability (although these can be done, depending on the file system)

You don't want or can't deal with the overhead a database will add

You are dealing with structured binary data that belongs in the file system, for example: images, PDFs, documents, etc.

Title: Why use a database instead of just saving your data to disk?

Body:
Instead of a database I just serialize my data to JSON, saving and loading it to disk when necessary. All the data management is made on the program itself, which is faster AND easier than using SQL queries. For that reason I have never understood why databases are necessary at all.

Why should one use a database instead of just saving the data to disk?


问:
Client Server .NET application with queuing message
I am new, so forgive me if my question is mistaken or anything, just give me an alert and I'll be glad to fix it.

Me and my team is about to develop a system where the database is located in a private server, and the applications is distributed between clients on distant location.

It is actually a simple CRUD application, but our primary concern is how poor the internet connection on some remote clients.

I thought to give a try to WCF queue message so that when the connection is down, I can save the message to later send it again when it is up, but I don't have a real clear solution in mind.

Currently, my solution would be something like this :

CLIENT

MySolution.sln

-- MyDataAccess

---- Entities (Contains my object class definitions and properties)

---- Repositories (Handles database communication)

---- Services (Handles message queue to server CRUD)

-- MyClassLibraries (Contains third party's DLLs)

-- MyHelper (Contains helper classes and functions)

-- MyCore (Main application project)

---- Model

---- View

---- ViewModel

and for the server :

SERVER

-- MyBackgroundService (Responsible for fetching incoming message and doing CRUD to database)

Is there a better solution to this? I am not good enough yet to see it.

Please let me know if I violate some rules here.

Cheers !

答: look into MSMQ services or just plain MSMQ itself.  Configured correctly you can make the OS handle the details that makes certain that the delivery will always occur assuming the network link is restored at some point.</p>


答:
When you have simple data, like a list of things as you describe in the comments of your question, then an SQL database won't give you much. A lot of people still use them, because they know their data can get more complicated over time, and there are a lot of libraries that make working with database trivial.

But even with a simple list that you load, hold in memory, then write when needed, can suffer from a number of problems:

Abnormal program termination can lose data, or while writing data to disk something goes wrong, and you can end up killing the whole file. You can roll your own mechanisms to handle this, but databases handle this for you using battle-proven techniques.

If your data starts growing too big and updating too often, serializing all your data and saving is going to be a big resource hog and slow everything down. You'd have to start working out how to partition things, so it won't be so expensive. Databases are optimized to save just the things that change to disk in a fault tolerant way. Also they are designed, so you can quickly just load the little bits of data you need at any given time.

Also, you don't have to use SQL databases. You can use NoSQL "databases" which many do, just use JSON to store the data. But it is done in a fault-tolerant way, and in a way where the data can intelligent split up, queried, and intelligently split across multiple computers.

Also, some people mix things up. They might use a NoSQL data store like Redis for storing login information. Then use relational databases to store more complex data where they need to do more interesting queries.