问:
Tree vs Graphs in search
Could anyone give a clear and concise explanation for when you use graphs vs when to use trees for data structures?</p>

答:
Trees are Graphs.

They are specifically directed, acyclic graphs where all child nodes only have one parent. If you need more than one parent then you use a DAG. If you need cycles or the graph needs to be undirected you'd use some kind of graph implementation. Note that the time and space complexity increases dramatically once you move into full graphs.

Title: Tree vs Graphs in search


问:
Tips or techniques to use when you don't know how to code something?
I have a background as UI designer. And I realized that it is a bit hard for me to write a pieces of logic. Sometimes I get it right, but most of the time, I end up with something hacky (and it usually takes a lot of time). And is not that I don't like programming, in fact, I'm starting to like it as much as design. It's just that sometimes I think that I'm better at dealing with colors an shapes, rather than numbers and logic (but I want to change that).

What I usually do is to search the solution on the Internet, copy the example, and insert it into my app (I know this is not a very good practice).

I've heard that one tip was to write the logic in common English as comment before writing the actual code.

What other tips and techniques I can use?

答:
I think that you've sort of answered your own question, and I don't mean that in a bad way -- it's a common piece of advice that the best way to learn how to code is simply by coding. I would personally try to avoid copying code directly from a source unless it's absolutely clear-cut as to what's going on (that is to say, that there isn't necessarily another good way to do something), though many of those sorts of issues are syntactical. Taking the time to understand what's going on and how you (or someone else) is implementing it matters the most.

In the time I've spent learning how to develop, I've found that working with MVC technologies is a great way to understand how to do design, such as Rails (what I'm working with right now) or iOS/Cocoa Touch. Because you're working in such an object-oriented environment of design, once you start thinking in terms of models and their logic being separated from the view (with controllers being the glue that binds them), you also start thinking in terms of how you can keep your objects abstracted in a logical, yet (hopefully!) uncomplicated manner.

This is based on my own experiences, of course, but I hope my thoughts on your question can be of some help.

ContentLicense: CC BY-SA 3.0


答:
Baby steps.

Break up a big problem into smaller problems. Then solve the smaller problems.

Bonus points if you can back up your solutions to the smaller problems with automated unit tests.

Title: Tips or techniques to use when you don't know how to code something?

Body:
I have a background as UI designer. And I realized that it is a bit hard for me to write a pieces of logic. Sometimes I get it right, but most of the time, I end up with something hacky (and it usually takes a lot of time). And is not that I don't like programming, in fact, I'm starting to like it as much as design. It's just that sometimes I think that I'm better at dealing with colors an shapes, rather than numbers and logic (but I want to change that).

What I usually do is to search the solution on the Internet, copy the example, and insert it into my app (I know this is not a very good practice).

I've heard that one tip was to write the logic in common English as comment before writing the actual code.

What other tips and techniques I can use?


答:
In addition to the answers already given, one of the best ways to get jump-started is to learn from an application that is simple and where the source code is available.

This is where such social repositories like Github shine. An incredible place to browse through for examples. And when you find one, you can immediately fork it as your own and do what you want to the application, so once you have it:

you can run it

tweak it here and there and see how things change

as you get more comfortable, you make bigger changes

you'll soon find you are really learning

Another option is to use the classic example reference implementations that are documented in so many different places. For example Java's Spring framework uses the venerable "Pet Store" example. I think you can even find that example on Github.

Other frameworks / technologies such as Groovy's Grail framework use other classics like a Book application for persisting and viewing Books and Authors, etc.

The final option that I've tried is following a good programming book and start typing up the examples by hand and putting them into a repository like Github; this has at least two benefits: 1) there is a reference for you with your own notes that will help you remember cool things in a way that you will remember and 2) if you get into tough spots you can easily get friends or colleagues to see your code and chime in with advice.

Science and especially programming is really built on the experiences of others. Figuratively speaking, copying/pasting and then tweaking until you understand is what helps developers become engineers.


问:
What is the difference between debugging and testing?
Introduction To Software Testing (Ammann & Offutt) mentions on p.32 a 5-level testing maturity model:

Level 0 There’s no difference between testing and debugging.

Level 1 The purpose of testing is to show that the software works.

Level 2 The purpose of testing is to show that the software doesn’t work.

Level 3 The purpose of testing is not to prove anything specific, but to reduce
the risk of using the software.

Level 4 Testing is a mental discipline that helps all IT professionals develop
higher quality software.

Although they don't go into much further detail. What are the differences between debugging and testing?

答:
Speaking in everyday, practical terms, I think it totally depends on the context.

In a med-large team, working to high / very high standards (think banking, military, large scale, high budget or business critical systems) then I think clearly "debugging" should be "a result of testing", and they are clearly very different things. Ideally testing leads to debugging (in a staging environment) and in production we need close to zero of either.

Testing is wide in scope, regular and very formalised - while debugging is a particular process that happens occasionally when there's a need to fix a particular failure - which is not obvious and requires a deeper investigation of a system's functioning and resultant outputs.

Here in my mind testing is something essential, while debugging is a specific tool needed only when the resolution to a failure is opaque.

I totally understand the obvious utility in TDD for large teams and or systems than simply cannot afford to be "buggy". It also clearly makes a lot of sense for complex (often  "back-end") systems or if there is a high proportion of complexity in the code compared to the output. Then "testing" has a realistic chance of informing when and why failures occur. Systems that do a lot of complex work and or result in clearly measurable outputs are generally readily testable, and so testing is distinct from debugging. In these cases testing strongly implies a procedure based, formalised method of confirming or dis-confirming the match of expectations and actual output. Testing happens all the time, and occasionally informs us of the need for debugging.

It would be lovely if this was a ubiquitous truth, I'd love it if my dev cycles were delimited by clearly defined binary output (red, green) but...

In my case (which is admittedly particular - working 98% solo on small-mid sized, under-funded web based, data focused corporate admin systems) I just really can't see how TDD could possibly help me. Or rather "debugging" and "testing" are virtually the same.

Mainly though the use of the term "testing" implies / closely relates to the methodology of TDD.

I know this is a totally, utterly un-Zeitgeist "shun the non believer, shun, shun", despicably un-cool thing to say. But thinking about my context, with a practical hat on I just don't even vaguely, in my wildest imagination see how TDD could possibly help me deliver more value for money to my clients.

Or rather, I strongly disagree with the common assumption that "testing" is a formal code based process.

My basic objection (applicable in my particular *context*) is that...

If I cant write code that works reliably - then how the hell am I supposed to write code that works reliably to test said presumably sub standard code.

To me I have never seen any example nor argument that (in my particular context) enthused me sufficiently to even bother thinking about writing a single test, I could be writing some laughably insubstantial testing code right now, maybe "does my repository return a User entity with Name == X, when I ask it for exactly - and only - that?", but there's probably more utility in me writing this streaming, maybe-the-internet-really-is-just-pure-foolish-spouting-self-gratifying-wildly-under-informed-blood-boilinglyignorant-wastefully-silly trash, but I just feel the need to play devil's advocate here. (Kind of hoping someone will show me the light and convert me, maybe this will end up giving my clients better value for money?).

Arguably "debugging" sometimes is the same as "testing". By this I really mean that in my daily working life I spend at least a third of my time playing about with the local version of my system in different browsers, desperately trying various different wacky things out in an attempt to break my work and then investigating the reasons why it failed and correcting them.

I 100% agree with the obvious utility in the TDD mantra "red/green/refactor", but for me (working in low-med budget, solo dev RIA land) I would really really love for someone to please show me how I could possibly, logically and vitally realistically get any additional value from writing more (just as potentially flawed testing code) than I do from actually interacting with the full (and essentially only) output of my efforts which are essentially bound to real human interaction.

For me when developers talk about "testing" it generally implies TDD.

I try to code as if there were tests, I think all the patterns / practices and trends that all this testing focused development has encouraged are fantastic and beautiful, but for me in my little world "testing" is not writing more code, its actually testing real world outputs it in an approaching realistic manner, and that's virtually the same as debugging, or rather the active change here is the "debugging" which is a direct result of human, output centric non automated "testing". This is in contrast to the generally accepted view of "testing" as something automated and formal, and "debugging" as something human and ad-hoc or unstructured.

If the goal is really value for money / effort, and you're making web based interactive applications, then the output of the effort is the web pages and very essentially how they react to human input - so "testing" is best achieved by testing those web pages, through real human interaction. When this interaction leads to unexpected or undesirable outputs, then "debugging" occurs. Debugging is also closely related to the idea of real time inspection of program state. Testing is generally associated with automation which I think is often an unfortunate association.

If the goal is really value for effort, and automated testing is efficient and highly beneficial, while debugging is either just an output of that testing, or a poor substitute for automated testing, then why is the second most visited website in the world (Facebook) so often riddled with blindingly obvious (to users, but clearly not the testing team and testing code) bugs?

Maybe its because they're concentrating on the reassuring green lights and forgetting to actually use the outputs of their work?

Do too many developers think testing is something you do with code, and debugging is something you do occasionally with the IDE because an icon turns red and you can't work out why? I think these words have unfortunate value judgements associated with them, which generally obscure the practical reality of what we should focus on to close the gaps between expectations and outputs.


答:
I usually write things down on paper while I'm thinking things through.  That way I can write pseudo-code or do drawings (usually both), and I don't have to worry about the limitations of the drawing software or what can fit in a comment.

I find that if I'm doing something at least mildly complicated, I really need to get things down on paper first, or else I end up with something hacky, like you mentioned.

If I end up with something hacky, it frequently almost works.  Sometimes I can hack on it until it finally does work, sometimes not.  If I take the time to work it out on paper, it often works without too much trouble.


问:
How to design a scalable notification system?
I need to write a notification system manager.

Here is my requirements:

I need to be able to send a Notification on different platforms, which may be totally different (for exemple, I need to be able to send either an SMS or an E-mail).

Sometimes the notification may be the same for all recipients for a given platform, but sometimes it may be a notification per recipients (or several) per platform.

Each notification can contain platform specific payload (for exemple an MMS can contains a sound or an image).

The system need to be scalable, I need to be able to send a very large amount of notification without crashing either the application or the server.

It is a two step process, first a customer may type a message and choose a platform to send to, and the notification(s) should be created to be processed either real-time either later.

Then the system needs to send the notification to the platform provider.

For now, I end up with some though but I don't know how scalable it will be or if it is a good design.

I've though of the following objects (in a pseudo language):

a generic Notification object:

```<code>class Notification {
    String                 $message;
    Payload                $payload;
    Collection<Recipient>  $recipients;
}
</code>```

The problem with the following objects is what if I've 1.000.000 recipients ? Even if the Recipient object is very small, it'll take too much memory.

I could also create one Notification per recipient, but some platform providers requires me to send it in batch, meaning I need to define one Notification with several Recipients.

Each created notification could be stored in a persistent storage like a DB or Redis.

Would it be a good it to aggregate this later to make sure it is scalable?

On the second step, I need to process this notification.

But how could I distinguish the notification to the right platform provider?

Should I use an object like MMSNotification extending an abstract Notification? or something like Notification.setType('MMS')?

To allow to process a lot of notification at the same time, I think a messaging queue system like RabbitMQ may be the right tool. Is it?

It would allow me to queue a lot of notification and have several worker to pop notification and process them. But what if I need to batch the recipients as seen above?

Then I imagine a NotificationProcessor object for which I could I add NotificationHandler each NotificationHandler would be in charge to connect the platform provider and perform notification.

I can also use an EventManager to allow pluggable behavior.

Any feedbacks or ideas?

Thanks for giving your time.

Note: I'm used to work in PHP and it is likely the language of my choice.

Edit (according to morphunreal's answer)

How many messages per second are you sending (Define current/initial levels, define a maximum level that the system should handle before being re-designed)

What hardware constraints does the system have (memory, cpu etc available to the system)

How will hardware scale (ie, adding more servers, cloud computing etc)

What languages / systems will be generating notifications?

It is on my own, I'm in charge to create the notification programmatically but constructed from an UI.

Does the generator know the recipients of the message (?) or are they provided by some other means (ie, business rules for certain alert types go to certain recipients)

It should be possible to create a notification for a specific recipients, a group of recipients (for example using a tag system), or for a whole platform.

Are there business rules for adding CC/ BCC / Read receipts

Yes. Note that this is really platform specific and the read or cc are not available on all platforms.

Does the generator know the type of message it's sending (ie, SMS/ email) or is it based off the recipient

It is based on the recipient, however, as the recipient is platform related, and platforms have different way to handle data, the UI is likely to be platform specific to allow to set up images, a sound or something.

Does the generator require confirmation of messages being sent/received/read (async vs synchronous sending)

Well the system should be error prone but we would like to handle the error to define a set of rule, for example, if the server is unreachable, the notification should be requeued for further process, but if the notification is incorrect (or has been defined as is by the platform provider) it should not be requeued but notified.

Are there requirements to store a history of message sources / recipients (how long for?)

Yes, we likely want to make some statistics and report.
* Define Notification End Points

What services are being used to send messages?
Depends, some are classical REST webservice, other are some exotic protocol, it is really up to the provider.

What feedback / confirmation is provided (sync / async)

Depends, some are synchronous and reply with an error while some other need to be pulled afterward to check for errors.

Is it likely to add new end-points [even if so, does it even need to be abstracted]

Yes, actually, our app is growing and we likely want to be able to add new provider, but it is a ratio of something like 1 or 2 per year.

答:
Start by separating out your functional and non-functional requirements, and carefully defining them. It's very easy to over-design a system based on ambiguous requirements.

For Example, your non-functional requirements in regards to scalability is quite ambiguous. It can relieve a lot of mental load if you put actual numbers on your system. For example,

How many messages per second are you sending (Define current/initial levels, define a maximum level that the system should handle before being re-designed)

What hardware constraints does the system have (memory, cpu etc available to the system)

How will hardware scale (ie, adding more servers, cloud computing etc)

Now that you have that out of the way, you can set up some tests to ensure that the systems design / architecture is capable of fulfilling your non-functional requirements.

As for the business/ functional requirements of sending notifications/ messages, the following clues may help (if you provide more information I can add to this answer):

Define notification sources

What languages / systems will be generating notifications

Does the generator know the recipients of the message (?) or are they provided by some other means (ie, business rules for certain alert types go to certain recipients)

Are there business rules for adding CC/ BCC / Read receipts

Does the generator know the type of message it's sending (ie, SMS/ email) or is it based off the recipient

Does the generator require confirmation of messages being sent/received/read (async vs synchronous sending)

Are there requirements to store a history of message sources / recipients (how long for?)

Define Notification End Points

What services are being used to send messages

What feedback / confirmation is provided (sync / async)

Is it likely to add new end-points [even if so, does it even need to be abstracted]

I'm hesitant to provide a concrete architecture example as it would depend heavily based on the factors involved; but often the simplest message systems involve a basic queue, either in memory/application, no-SQL, disk, or relational database. Then a separate process (or several separate processes if distributed) can poll the queue for their message types [ie a cron job]; and send off as necessary.

This could also be enhanced using some push-based techniques (ie PostgreSQL NOTIFY/LISTEN) if there is a requirement for messages to be sent immediately.

The advantage of a simple queue, is that the system generating the message has little work to do, and the processing system can be balanced based on hardware/performance requirements.


答:
I agree with thinking on paper.  As a rule, I identify every item of information that I'll need and where it will be coming from, first. It doesn't have to be elegant, just accurate.  Business logic questions and design strategies usually come during this process.

With that, as a java developer working end to end on an application, I further divide things by tiers: presentation, web, business logic, and the data access layer.  When I have time, I usually write out my class names during this part.

Last of all I always endeavor to run tests for the back end, before I write code.  You can wire everything up elegantly, but if you can't hit the back end: database or web service for example, it won't work!


答:
Imagine you have to make a report about your problem to someone else.

 Analyze the problem. Try to formulate it as clearly as you can. Write pseudocode, draw diagrams.

 Think about what could be causing the problem and why your approach is wrong.

Ask yourself if there are any other perspectives you can view your problem from.

 Don't just do that in your mind, put it on paper (or a document on your computer).

If none of that helps you immediately, try not to think about the problem for a while. Have a good night's rest. Still no solution? Try googling your problem, or searching SO for a solution.

If all else fails, ask a question on SO (or SE Programmers if it's more appropriate for your particular question). Be sure to actually include your "report" (or the important parts of it) when asking the question.

When you get an answer, ask yourself why your approach didn't work and what could have helped you to come to the solution by yourself. It might help you find a solution for some problem you come across in the future which requires a similar approach.


答:
Some of the principles of test-driven development help a lot here.

One of the best ways to solve complex problems is to solve it for specific use cases and then discover a generalization.  Using TDD promotes exactly that.  You create a simple test case and get that working, then create another test case and get that working.  Finally you see if there is some generalization you can make that allows you to handle both test cases with the same logic.  If you can, then it will probably handle a lot of other test cases as well.  Since you can run all your test cases at any time, you can feel free to improve your logic without worrying about breaking something.  This way, a hacky solution doesn't have to stay hacky.

Test-driven development also promotes

breaking up large problems into smaller ones, so that it is easier to get good test coverage.

thinking up front about what you really want to achieve before you get bogged down into the details of the implementation.

avoiding over-engineering by trying to make the tests pass in the simplest way possible, and simple solutions are usually the best ones.


问:
What are the advantages of the delegate pattern over the observer pattern?
In the delegate pattern, only one object can directly listen to another object's events. In the observer pattern, any number of objects can listen to a particular object's events. When designing a class that needs to notify other object(s) of events, why would you ever use the delegate pattern over the observer pattern? I see the observer pattern as more flexible. You may only have one observer now, but a future design may require multiple observers.

答:
The delegate pattern, as I understand you, is know as the event handler mechanism in other languages, for example Delphi. As such it simply is an implementation of the observer pattern with a major restriction: only one listener at a time.

The disadvantage of event handlers or delegates is obvious: only one observer.

The advantage is not so obvious: performance. With an observer pattern you can add many observers. When an event occurs that the observers need to be notified about, you will need to enumerate the observers and send a notification to each. This can quickly bog down any observed instance, especially when the number of events that require notification is significant as well.


问:
How should I host our scalable worker processes?
We are designing a new architecture for an enterprise business. The principles we've followed so far is not to develop what you can (possible buy and) deploy, ie, don't reinvent any wheels.

In this way we've decided on CQRS, RabbitMQ, Riak and a bunch of other things. We still need to write /some/ business code though and these will be in the form of worker processes, which will consume commands from a message queue and after any side-effects, produce events onto another message queue. The idea behind this is that via the competing-consumers design we will have a scalable design right out of the box.

One option is of writing a management infrastructure that will know how to:

deploy code

instantiate processes

kill processes

update configuration

etc

IE provide fault tolerance and scalability. Also, this is exactly what something like GAE and Heroku does for you, but in a public setting and in our organization, public is bad.

My question is, is there an out-of-the-box solution that we can use to host our consumers in? Like a private cloud or private platform-as-a-service. Private Heroku or GAE. Is there some kind of software or software product with which we can do all of these things and thereby get scalability and fault tolerance over our consumers?

答:
Cloud service providers have started to address this concern. In particular, check out:

Iron.io - They have a product called "IronWorker" which supports several languages

heroku - They offer "worker dynos"

Windows Azure - Their Cloud Services offering has web and worker processes


答:
There's actually a book which answers exactly that question:

How to Design Programs – An Introduction to Programming and Computing by Matthias Felleisen, Robert Bruce Findler, Matthew Flatt, and Shriram Krishnamurthi

They are currently working on a second edition, and after that, a second volume (How to Design Components).

The really cool thing about this book is that it gives you a set of recipes for designing programs. In other words, it gives you step-by-step instructions which you can (semi-)mindlessly follow in order to design a program.

Or, to put it yet another way: it contains a set of programs for writing programs, so that you don't have to figure out how to write a program: the authors figured it out for you!


问:
How does Google plus page loading work
On Google plus, when I click on a Google plus profile or any Google plus link the page gets redirected to that link without a full page load but the URL changed and a record added to browser history.

How this can be done? Is there any tutorial or document?

答:
I would guess this is done with the HTML5 History API. I don't really have anything to back that up, other than than Github works this way.

There's several topics adressing this here already. Look at the links provided or those topics for more information.

Title: How does Google plus page loading work


问:
how do early stage startups hire ninja programmers
I am programmer who just started working on a startup idea. At the moment I want to bring onboard at least one programmer. This programmer should be a ninja - a 10x engineer.

Since early days are probably the most risky for a startup, I want to make sure I approach this problem the best I can.

How do I find these people? and How do I convince them to come onboard?

I would love to hear from people who started their own companies and what their thoughts are about hiring

Update: I would like to get the ninja as a co-founder so besides being a ninja (ie. great programmer with computer science background) he/she has to have a healthy appetite for risk (for great programmers this is not a big deal because they can be hired anytime into mainstream jobs if the startup doesn't work)

答:
Offer to pay well. If you can't afford it, offer other incentives.

Network. You can't hire someone unless you know they exist. As mentioned, a developer conference may be worth attending.

Be careful, Facebook was (allegedly) a stolen idea. Make sure you hire someone who is honest, or at least willing to sign the proper legal documents. Get yourself a lawyer if needed.

Consider outsourcing outside of the US. It's cheap and you can get a product that's solid. (See odesk.com)

Recognize your needs. (Larry brings up some good points.)

(Listed in no particular order and borrowed from other answers.)

ContentLicense: CC BY-SA 2.5


问:
What language was "standard" for Apple development before Objective C?
I don't think Objective C was in use from the beginning of Apple hardware development.  What languages did app developers use for the earlier Apple computers, such as Apple II or Mac Classic?</p>

答:
In 1985 Larry Tesler developed a Pascal flavour for Apple, Object Pascal,  that became the standard language for System 6. It was based on Clascal, a 1983 Pascal variant for the Lisa, also developed at Apple.

Object Pascal was used in MacApp, Apple's primary application framework at the time. MacApp 3.0, released in 1991, was re-written in C++ and Apple subsequently dropped support for Object Pascal in favour of C++ when they moved from Motorola's 68K chips to PowerPC.

Borland's Object Pascal, that today lives on as Embarcadero Delphi, started out in 1986 as a set of extensions to Turbo Pascal, that were intended to be similar to Apple's Object Pascal. Niklaus Wirth, Pascal's originator, was consulted by both Apple and Borland for their respective variants.

Conversely, Objective C was NeXTSTEP's main language and was introduced at Apple only after they purchased NeXT in 1996.


答: You may want to explore http://code.google.com/p/appscale as the platform (as in PaaS), and some EC2 implementation (as in IaaS) such as Eucalyptus (http://www.eucalyptus.com/). </p>

Title: How should I host our scalable worker processes?

Body:
We are designing a new architecture for an enterprise business. The principles we've followed so far is not to develop what you can (possible buy and) deploy, ie, don't reinvent any wheels.

In this way we've decided on CQRS, RabbitMQ, Riak and a bunch of other things. We still need to write /some/ business code though and these will be in the form of worker processes, which will consume commands from a message queue and after any side-effects, produce events onto another message queue. The idea behind this is that via the competing-consumers design we will have a scalable design right out of the box.

One option is of writing a management infrastructure that will know how to:

deploy code

instantiate processes

kill processes

update configuration

etc

IE provide fault tolerance and scalability. Also, this is exactly what something like GAE and Heroku does for you, but in a public setting and in our organization, public is bad.

My question is, is there an out-of-the-box solution that we can use to host our consumers in? Like a private cloud or private platform-as-a-service. Private Heroku or GAE. Is there some kind of software or software product with which we can do all of these things and thereby get scalability and fault tolerance over our consumers?


问:
What alternatives are there to using HTML/CSS layouts for websites?
Is there any existing in-use, or even just conceptual attempts at creating a markup or programmatic expressions for designing the layouts of websites other than HTML/CSS?

If there are others out there and they do not appear to be in heavy use. Why is this?

答: HAML and  SASS are not alternatives to HTML. They are server-side languages that create  HTML output.  AXR is an alternative to HTML in the making. The AXR site says if you want to help out you can http://axr.vg. GRML is also an alternative to HTML, although I am not advocating to use it or not to use it. I am merely stating a fact. It hasn't been updated in 8 years and doesn't support any browsers but it's own. http://www.codeproject.com/Articles/3486/An-alternative-to-HTML-and-current-web-browsers</p>


答:
The standard language of Mac OS Classic was Pascal.  The OS's API documentation was all written for Pascal, and as much of the OS as was not written in hand-optimized ASM was written in Pascal.

After transitioning to the PowerPC architecture, they rewrote the OS in C++, accompanied by a very noticeable decrease in system stability, which will not be surprising to anyone familiar with Pascal and C++.  API documentation continued to be written primarily for Pascal, though, until Steve Jobs came back and started trying to force Objective-C down everyone's throats.

Title: What language was "standard" for Apple development before Objective C?

Body: I don't think Objective C was in use from the beginning of Apple hardware development.  What languages did app developers use for the earlier Apple computers, such as Apple II or Mac Classic?</p>


答:
That's a question of several trade-offs.

Trade-offs:

flexibility (in terms of having n > 1 delegates/observers)

cost of sending a message

resilience (ability to sustain unavailability of delegate/observers)

ease of use

Delegate pattern:

not very flexible - adding more than 1 delegate is not possible (implies some form of "multi-delegate" i.e. observer pattern)

sending a message is cheap, O(1) - same cost as calling any other function or method (no look-up, message queue or other infrastructure required)

usually not resilient - delegates are expected to be present and do their part of the work, i.e. the sender tends to fail if not delegate is known

easy to grasp, easy to implement

Observer pattern:

very flexible - adding n > 1 observers is expected by design

sending a message has a cost implied by number of observers, O(n), i.e. n observers take n time and messages (at least in a naive implementation)

usually resilient - observers are not generally expected to do any work on part of the sender. That is even if there is no observer the sender is unaffected

can become rather complex to grasp, in particular of observers are expected to react to messages (does the order matter?, which observer responds in which way?)

Title: What are the advantages of the delegate pattern over the observer pattern?

Body: In the delegate pattern, only one object can directly listen to another object's events. In the observer pattern, any number of objects can listen to a particular object's events. When designing a class that needs to notify other object(s) of events, why would you ever use the delegate pattern over the observer pattern? I see the observer pattern as more flexible. You may only have one observer now, but a future design may require multiple observers.


问:
Is "Interface inheritance" always safe?
I'm reading "Effective Java" by Josh Bloch and in there is Item 16 where he tells how to use inheritance in a correct way and by inheritance he means only class inheritance, not implementing interfaces or extend interfaces by other interfaces. I didn't find any mention of interface inheritance in the entire book.

Does this mean that interface inheritance is always safe? Or there are guidlines for interface inheritance?

答:
Does this mean that interface inheritance is always safe? Or there are guidlines for interface inheritance?

No; you should always be careful of how you design the interface and what contracts does it enforce on the implementing classes. In Java you are obliged to implement all of the interface's methods and maybe you really don't need all of them in your class and you cannot change the interface either.

For example you have a large interface with numerous methods that clearly does not respect Interface Segregation Principle. If you choose to implement this interface but in your class you only need less than half of the interface's methods, then using interface inheritance is not a good idea.

Title: Is "Interface inheritance" always safe?


答:
Interfaces should be quite sparse and limited to the methods required.  As long as the Interface is well designed is it safe to inherit from it.

That being said it is possible to create huge interfaces with lots of methods which are not required for the interface.  While it is safe to inherit from them, it it not recommended.

Designing an Interface requires careful thought as once it is being used it can be costly to modify.  Changing the interface is difficult once it has been used.  Adding methods or changing their signature requires doing the same to all inheritors.  Removing methods is more difficult as the methods may include functionality of the inheritor, in which case they must be retrained or reworked, otherwise they should removed.

Title: Is "Interface inheritance" always safe?

Body:
I'm reading "Effective Java" by Josh Bloch and in there is Item 16 where he tells how to use inheritance in a correct way and by inheritance he means only class inheritance, not implementing interfaces or extend interfaces by other interfaces. I didn't find any mention of interface inheritance in the entire book.

Does this mean that interface inheritance is always safe? Or there are guidlines for interface inheritance?


问:
Concurrency checking with Last Change Time
I have an app with the following three tables

Email (emailNumber,  Address)

Recipients (reportNumber, emailNumber, lastChangeTime, status)

Report (reportNumber, reportName)

I have a C# application that uses inline queries for data selection.

I have a select query that selects all reports and their Recipients. Recipients are selected as comma separacted string.

During updating, I need to check concurrency. Currently I am using MAX(lastChangeTime) for each reportNumber. This is selected as maxTime.  Before update, it checks that the

```<code>lastChangeTime <= maxTime. --//It works fine
</code>```

One of my co-developers asked why not use GETDATE() as “maxTime” rather than using a MAX operation. That is also working. Here what we are checking is the records are not updated after the record selection time.

Is there any pitfalls in using GETDATE() for this purpose?

答:
If you get the data at the start of your process, it is a good solution.  This is especially the case if you have multiple tables involved as you only need to track one timestamp.  If you are tracking multiple timestamps, it is possible to use the wrong timestamp in a comparison.

The one shortfall, which applies in both cases, is if records are inserted at the timestamp but not included in the result set.  (It is possible that the MAX value will return the same value as GetDate.)  Long running insert transaction can also be a problem if the timestamp, and time of commit vary significantly.

The other issue is clock synchronization between the database server (which should be setting the timestamp in a trigger) and the host on which you issue GetDate.  Use of NTP to synchronize clocks is advisable.  I have seen cases where new users could not log-in for a couple of minutes due to unsynchronized clocks.  It may be safer to get the date from the database in a single call.


问:
css - use universal '*' selector vs. html or body selector?
Applying styles to the body tag will be applied to the whole page, so

```<code>body { font-family: Verdana }
</code>```

will be applied to the whole page.  This could also be done with

```<code>* {font-family: Verdana}
</code>```

which would apply to all elements and so would seem to have the same effect.

I understand the principle that in the first instance the style is being applied to one tag, body for the whole page whereas in the second example the font is being applied against each individual html elements.  What I am asking is what is the practical difference in doing that, what are the implications and what is a reason, situation or best practice that leads to using one over another.

One side-effect is certainly speed (+1 Rob).  I am most interested in the actual reason to choose one over the other in terms of functionality.

答:
I've forgotten the complete details but, with the * selector, performance is slowed down as each and every element gets evaluated as the browser parses the CSS and applies the style. iirc, setting the font, in this case, to just the parent makes one reference for each element and additional work is not needed.

There are some other issues, too, but, again, I don't recall them all and have not used * in years.


答:
Try something like this

```<code>body { font-family: Verdana }
table { font-family: Arial }
</code>```

against

```<code>* { font-family: Verdana }
table { font-family: Arial }
</code>```

And see which styles are applied to the cells of the table.

There is a difference between "applied to the whole document" and "applied to every element of the document" when you're dealing with cascading stylesheets.

Applying a cascading style to the body applies it to all tags within body until a tag overwrites it. Then the overwritten style is applied to all tags within that one.

However, there are some styles that don't cascade, such as margin and padding (usually where it makes no sense to). Those can only be applied to specific tags and that's where a wildcard can come in useful (albeit rarely).

Most non-cascading styles also have a value of inherit (eg. margin: inherit), which means "take the parent tag's values".

Title: css - use universal '*' selector vs. html or body selector?

Body:
Applying styles to the body tag will be applied to the whole page, so

```<code>body { font-family: Verdana }
</code>```

will be applied to the whole page.  This could also be done with

```<code>* {font-family: Verdana}
</code>```

which would apply to all elements and so would seem to have the same effect.

I understand the principle that in the first instance the style is being applied to one tag, body for the whole page whereas in the second example the font is being applied against each individual html elements.  What I am asking is what is the practical difference in doing that, what are the implications and what is a reason, situation or best practice that leads to using one over another.

One side-effect is certainly speed (+1 Rob).  I am most interested in the actual reason to choose one over the other in terms of functionality.

Body:
Try something like this

body { font-family: Verdana }
table { font-family: Arial }

against

* { font-family: Verdana }
table { font-family: Arial }

And see which styles are applied to the cells of the table.

There is a difference between "applied to the whole document" and "applied to every element of the document" when you're dealing with cascading stylesheets.

Applying a cascading style to the body applies it to all tags within body until a tag overwrites it. Then the overwritten style is applied to all tags within that one.

However, there are some styles that don't cascade, such as margin and padding (usually where it makes no sense to). Those can only be applied to specific tags and that's where a wildcard can come in useful (albeit rarely).

Most non-cascading styles also have a value of inherit (eg. margin: inherit), which means "take the parent tag's values".


答:
... and prior to the Mac (Apple II), most programming was in BASIC.  (For all variants of Apple II to the IIgs)

I also recall doing C++ development on System 7 using Metroworks CodeWarrior - this was (of course) post PowerPC.


答:
Generally, yes. However, you must be aware of surprises, some of which I mention next.

Disclaimer: none of these lists is exhaustive.

Badly designed interfaces:

with lots of methods;

with methods that don't throw sensible exception types, or methods that don't throw at all (a problem in checked exception languages like Java: when not given a second thought, most people usually throw Exception or nothing);

with methods that may not be implemented, in the sense that they can throw UnsupportedOperationException (an unchecked exception) or a subclass of it (in .NET, there's already a more explicit NotImplementedException); usually seen together with huge interfaces.

What can be done:

Split the huge interfaces;

Provide at least one subclass of Exception in the same namespace as the interface;

If you cannot split an interface for some good reason, state clearly which methods may throw a UnsupportedOperationException (or NotImplementedException in .NET). It may be all methods, but state it clearly, such as at the head of the interface's documentation or in a separate small paragraph near the top, and also in each method's description.

If you must use a huge interface which describes what methods may throw unchecked exceptions such as UnsupportedOperationException (I'm assuming it's an interface out of your control), be ready to catch them or document that your methods may throw them.

An interface should be as small as possible and its implementation should mean it's totally implemented. In the real world, however, it's not always the case, and sometimes one has to go through hoops.

A bad class implementation:

that implements an interface on the interest of supporting only part of its contract, like one or two of its methods, usually doing nothing or returning non-sense for all other methods (unless it's actually implementing an observer);

that throws UnsupportedOperationException (or NotImplementedException in .NET) in methods where the interface doesn't clearly state that it may be thrown;

What can be done:

Have an abstract class that implements most boilerplate, and either inherit from it directly, or create a subclass of it and use this new class to instantiate delegation objects. In fact, many Java observer objects already come with this facility, even though the default implementation of all its methods is to do absolutely nothing.

Correct it, follow the contract. If the code is not yours, try to wrap such misbehaviour.

Title: Is "Interface inheritance" always safe?


问:
Override methods should call base method?
I'm just running NDepend against some code that I have written and one of the warnings is Overrides of Method() should call base.Method().

The places this occurs are where I have a base class which has virtual properties and methods with default behaviour but which can be overridden by a class which inherits from the base class and doesn't call the overridden method.

For example, in the base class I have a property defined like this:

```<code>protected virtual char CloseQuote
{
    get
    {
        return '"';
    }
}
</code>```

And then in an inheriting class which uses a different close quote:

```<code>protected override char CloseQuote
{
    get
    {
        return ']';
    }
}
</code>```

Not all classes which inherit from the base class use different quote characters hence my initial design.

The alternatives I thought of were have get/set properties in the base class with the defaults set in the constructor:

```<code>protected BaseClass()
{
    this.CloseQuote = '"';
}

protected char CloseQuote { get; set; }

public InheritingClass()
{
    this.CloseQuote = ']';
}
</code>```

Or make the base class require the values as constructor args:

```<code>protected BaseClass(char closeQuote, ...)
{
    this.CloseQuote = '"';
}

protected char CloseQuote { get; private set; }

public InheritingClass()
    base (closeQuote: ']', ...)
{
}
</code>```

Should I use virtual in a scenario where the base implementation may be replaced instead of extended or should I opt for one of the alternatives I thought of? If so, which would be preferable and why?

答:
It's a strange warning NDepend gives you. Surely not all overridden methods have a need to call the base method, so I think the text Method() should call base.Method() is too strong. It does make it look like you may be doing something wrong, which you clearly are not.

This has nothing to do with using virtual though. Was that supposed to be a different question?

OwnerDisplayName: Trevor Pilley


答: addition to the answers above, sometimes is not about knowing logic itself but to know the framework and language that you working with. Every framework or language has its own characteristic and it is great help get familiar with that. </p>


答:
It is a valid design decision to have a default implementation of a method in a base-class that should be completely replaced when the method is overridden in a derived class.

Thus, you could regard the warnings from NDepend as a false-positive for your code. I would check the NDepend documentation to see if there is an option or source-code annotation that tells NDepend that not calling the base-class implementation is correct here to get rid of the clutter.

If there is no such option (or it does not work for properties), my preference would be the first alternative (overriding the value of CloseQuote in the derived-class' constructor).

Title: Override methods should call base method?

Body:
I'm just running NDepend against some code that I have written and one of the warnings is Overrides of Method() should call base.Method().

The places this occurs are where I have a base class which has virtual properties and methods with default behaviour but which can be overridden by a class which inherits from the base class and doesn't call the overridden method.

For example, in the base class I have a property defined like this:

```<code>protected virtual char CloseQuote
{
    get
    {
        return '"';
    }
}
</code>```

And then in an inheriting class which uses a different close quote:

```<code>protected override char CloseQuote
{
    get
    {
        return ']';
    }
}
</code>```

Not all classes which inherit from the base class use different quote characters hence my initial design.

The alternatives I thought of were have get/set properties in the base class with the defaults set in the constructor:

```<code>protected BaseClass()
{
    this.CloseQuote = '"';
}

protected char CloseQuote { get; set; }

public InheritingClass()
{
    this.CloseQuote = ']';
}
</code>```

Or make the base class require the values as constructor args:

```<code>protected BaseClass(char closeQuote, ...)
{
    this.CloseQuote = '"';
}

protected char CloseQuote { get; private set; }

public InheritingClass()
    base (closeQuote: ']', ...)
{
}
</code>```

Should I use virtual in a scenario where the base implementation may be replaced instead of extended or should I opt for one of the alternatives I thought of? If so, which would be preferable and why?


问:
What are some things to be aware of when getting ready to hand a project off?
I'm current the sole developer/architect of a fairly large web application (ASP.NET MVC stack, roughly 150K+ lines of code) and the end of development is on the horizon. As such, I'm starting to think about what needs to be done for the hand off of the project and I want to make sure I do the right thing for anyone that has to maintain the project in the future.

What are some things to be aware of when getting ready to hand a project off to another developer or team of developers of maintenance?

答:
This is exactly why comments are not code smell. This is also why we should document our code.

You should make sure that you have solid documentation. There are programs that can generate documentation from comments depending on the format of the comments and the programming language.

Consider what information you would want about a library or codebase when taking it over. Ask a friend who is a programmer to give a quick look and see if they spot any obvious questions.

Good luck!


答:
The warning is trying to tell you that, since you've defined an is-a relationship with the super class, all protected and public behavior of the super class should be reachable from the subclass.

Most often the real reason you want to override a method to replace its behavior completely is a demand for composition. E.g. instead of overriding the method closeQuote, you might want to create an interface 'QuoteDefinitionProvider' (or such like) and feed it to the superclass.

Other reasons might be:

super class should be abstract, but isn't, so a 'default' implementation is given. Solution: make super class abstract.

subclass implementation can be optimized for the special case. This seems to be a sound reason to completely override the method and not call super.

So, before ignoring this warning, check whether your situation demands composition instead of inheritance. In my professional experience, I've seldom found a true need for class inheritance.


答: history.pushState() should do what you want.  The Mozilla Developer Network provides more information: https://developer.mozilla.org/en-US/docs/DOM/Manipulating_the_browser_history.  Keep in mind there may be browser support issues depending on what browsers you want to your website to work in.

Title: How does Google plus page loading work

Body:
On Google plus, when I click on a Google plus profile or any Google plus link the page gets redirected to that link without a full page load but the URL changed and a record added to browser history.

How this can be done? Is there any tutorial or document?


问:
Asking for a code sample of the company at an interview
Asking a job seeker to show some code is a fairly common practice for a software company. However, would it be acceptable for the candidate to ask the interviewer to show him a small piece of code that he thinks is well written?</p>

答:
I tend to work for companies where at least part of their work is open source, so it's trivial to find code samples. I figure out who works at the company, then figure out their online handles. Since people tend to use the same screen name, over and over, it's easy to find where they've committed code, whether they were on Github, Bitbucket, or somewhere else completely.

My current company has a ton of code hosted on Github, so it was easy to see what they work with, how big their code base is, and what seems to be no longer of interest.

I would never ask for a sample, simply because they're going to show you the best code they have. This is not the code you'll be working with. It's probably housed in a bell jar in a locked room. You'll be working with the messy code that many people have had to mess with.


答:
Functional differences between these two choices of CSS selector...(my take)

body

Applies style properties to body element.

Elements within body may inherit the property values. Some properties default to 'inherit'.

Style declarations that match an element within body can override the inherited style.

The Universal Selector * (all elements)

Applies style properties to all individual elements.

Replaces inherited style properties, and default 'initial values'. Blocks inheritance.

Other, more specific css selectors that match an element will replace the style properties applied by *.

Suggestions

Use body for style properties that default to inherit, such as font, color, in order to provide a sensible default value for elements, reducing the need to explicitly code for every case, and preserving the ability for elements contained at lower levels below body to inherit from their parents.

Probably better not to use the Universal Selector * in this case. It interrupts inheritance between other elements within body, and may force you to write more css rules to compensate. It can be a factor in slowing rendering of pages. This depends on the size and content of the page and how many css rules there are.


答:
The general guideline for good CSS design is to be as specific as possible, but not more.

So, in your example, applying the style to the body element would be as specific as possible and certainly more specific than the '*' selector.


答:
I have asked this question at my two interviews where they claimed they had senior devs migrating to asp.net mvc3 or 4 or when they said they want heavily commented code.
I have rejected at both occassion due to lack of their knowlege on actual code standard. The only standard i found was if it works copy and paste it and it will work.
I wont ask this question if i am doing a new project or have to write piece of code independent from others in the team.
I will definitely see the code if i am being hired to fix an existing software or function and i wont say yes unless i know the answer.
Assume you dont ask and they say can you please fix the datepicker to start from todays date. When you look at legacy code you see no jquery or jquery ui but a custom made date picker that has all dates stored in xml file and every night a cron job runs to update future months on it. That would start the headache as code to achieve this is less than the words in this example.
If you are going to work on their code ask to see it.
Not asking is like quoting for a job on belief that customer said its small. He might own 20 acre land and gardening on his 1 acre is small for him but gardner cant charge 50 quid just because all his small jobs start from 50.</p>

Title: Asking for a code sample of the company at an interview

Body: Asking a job seeker to show some code is a fairly common practice for a software company. However, would it be acceptable for the candidate to ask the interviewer to show him a small piece of code that he thinks is well written?</p>


问:
How to avoid jumping to a solution when under pressure?
When under a particularly strict programming deadline (like an hour), if I panic at all, my tendency is to jump into coding without a real plan and hope I figure it out as I go along.  Given enough time, this can work, but in an interview it's been pretty unsuccessful, if not downright counter-productive.  I'm not always comfortable sitting there thinking while the clock ticks away.

Is there a checklist or are there techniques to recognize when you understand the problem well enough to start coding?  When is it most productive to think and design more vs. code some experiments and figure out the over-all design later?

Here is a list of techniques for taking a math test and another for taking an oral exam.  Is there is a similar list of techniques for handling a programming problem under pressure?

ANSWERS: I think this is a valid answer: How To Solve It.  I found that link as an answer to Steps to solve or approach towards a solution.  There were also some really good tips at Is thinking out loud during an interview really the best strategy?.  A great and concise argument for TDD is the first answer to TDD Writing code vs Figuring out the answer to a problem?.

答:
I recall reading a study on how fire marshalls form a plan of action on arrival at the scene of a fire; the study observed (and condemned) them for coming up with an idea, then pursuing that first idea immediately.  Due to the pressure of time, it was pretty much "this might work" followed by "ok, let's do that".  The study noted that better, quicker, safer options were available, but they were not followed simply because the marshalls didn't think of them first.

If you want a structured approach to dealing with "fires" perhaps take a leaf out of their (new) book which prescribes several phases:

R.R.A.P.I.D.

Reaction - Mobilize resources to incident

Reconnaissance - Collect data about the situation

Appreciation - Choose a course of action based on best and worst case scenarios

Plan - develop a plan based on the course of action

Issue of Orders - Use the standard briefing format

Deployment - Execute and monitor

or in more general terms:

Wake everyone up and get them moving

Work out what's going on

Brainstorm solutions

Pick one and plan it

Tell everyone what their job is

Execute and monitor


答:
My default handoff checklist:

Check out clean copy from VCS

Test build, test deploy

Rename the maven repo to repo-back-up

Test build again

Install fresh copy of app server from zip

Verify server set up notes

Test deploy again

Verify that no unit tests are disabled

Scan comments for four letter words, delete them

If anything is broken, I'd fix it before hand over. Nothing gets someone off to a running start then getting the project checked-out, built and running the day you get the project.

Title: What are some things to be aware of when getting ready to hand a project off?

Body:
I'm current the sole developer/architect of a fairly large web application (ASP.NET MVC stack, roughly 150K+ lines of code) and the end of development is on the horizon. As such, I'm starting to think about what needs to be done for the hand off of the project and I want to make sure I do the right thing for anyone that has to maintain the project in the future.

What are some things to be aware of when getting ready to hand a project off to another developer or team of developers of maintenance?


问:
Test driven vs Business requirements constant changing
One of the new requirement of our dev team set by the CTO/CIO is to become test driven development, however I don't think the rest of the business is going to help because they have no sense of development life cycles, and requirements get changed all the time within a single sprint. Which gets me frustrated about wasting time writing 10 test cases and will become useless tomorrow.

We have suggested setting up processes to dodge those requirement changes and educate the business about development life cycles. What if the business fails to get the idea? What would you do?

答:
Your question seems to suggest that TDD is bound by development life cycles.  I'm not sure I agree.

The answer to flexible, changing requirements is iterative development.  TDD has nothing to say about this, or about software schedules; it is a tool for developing software within whatever requirements and schedule you do have.  If the requirements change, so does the software.  This goes for the unit tests as well.

TDD does not develop requirements, even though some proponents suggest that it does.  Rather, the requirements drive the units tests, which in turn drives the code that is written.  You don't grow an architecture from tests, nor do you develop requirements with tests.  Instead, the tests are an outcome of the designated architecture and requirements.

If requirements are changing at the atomic (method/unit test) level of software development, then I would suggest that your requirements are too granular.  Requirements should specify what the software does, not how it does it.  How the software meets the requirements is the domain and responsibility of the software developers, not the principal stakeholders.

To put it another way, I don't tell the customer or business owner how to run his company, and he doesn't tell me how to design my classes.


答:
Changing requirements are a normal thing, but when they are changing on a daily basis and changing the requirements in the middle of a sprint then this is not an environment conducive to software being developed in any meaningful and qualitative way.  In other words, TDD is the least of your problems here, they are more fundamental.

You mention sprints, meaning that you are performing some kind of Agile development, which is a good thing.  Handling development in short quick sprints works well on projects for when priorities and requirements are volatile and could change in the middle of the project.  The serious issue is that you have requirements drastically changing on your development and test teams in the middle of a sprint.

The sprint priorities should not change once the sprint has started.  The sprint is supposed to be an agreement between the stakeholders and the development team that the following agreed upon features and user stories will be delivered and tested by a specific date.  The stakeholders do not uphold their end of the agreement when they start changing their expectations for the sprint after development has begun.

So the stakeholders weren't being careful or thoughtful of what they were asking for, so they will change their expectations immediately.  Do the developers then have the luxury of pushing the delivery date for the features?  Often not.  At best the stakeholders were being negligent or incompetent and the developers pay the price in overtime to meet the date anyway.  Sometimes even the stakeholders do this purposely knowing that they can get more work out of their salaried developers.

What should honestly happen when the core requirements change to the point where the current work for the sprint would be useless is to immediately halt sprint development until a new sprint can be planned based on the new requirements.  There is certainly no reason to continue on for the next week and a half developing software that the business has already told you that would not in anyway be useful to them at all.

What is happening really is that the business stakeholders are failing the development team by not maintaining or meeting the sprint commitment.  They demonstrate either complete lack of competence in determining what they want in software or they have a complete lack of respect for the development team and how quality software is produced.

The only way that business groups like this earn a respect for how software development really works is to hire an outside consultant company or software vendor to develop software for them and pay by sprint.  Once they lose money on a few sprints worth of development that they cannot use then they will start to gain an appreciation with how important it is to maintain their commitment as stakeholders and be very careful and specific with their features and requirements.

Title: Test driven vs Business requirements constant changing

Body:
One of the new requirement of our dev team set by the CTO/CIO is to become test driven development, however I don't think the rest of the business is going to help because they have no sense of development life cycles, and requirements get changed all the time within a single sprint. Which gets me frustrated about wasting time writing 10 test cases and will become useless tomorrow.

We have suggested setting up processes to dodge those requirement changes and educate the business about development life cycles. What if the business fails to get the idea? What would you do?


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

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

答:
"For a successful technology, reality
  must take precedence over public
  relations, for nature cannot be
  fooled."

-Richard Feynman
(Rogers' Commission Report into the Challenger Crash, Appendix F - Personal Observations on Reliability of Shuttle)

More succinctly:

"You can't lie to the compiler."

-Andrew Stevenson

LastEditorDisplayName: Roger Pate


问:
How old is "too old"?
I've been told that to be taken seriously as a job applicant, I should drop years of relevant experience off my résumé, remove the year I got my degree, or both. Or not even bother applying, because no one wants to hire programmers older than them.1

Or that I should found a company, not because I want to, or because I have a product I care about, but because that way I can get a job if/when my company is acquired.

Or that I should focus more on management jobs (which I've successfully done in the past) because… well, they couldn't really explain this one, except the implication was that over a certain age you're a loser if you're still writing code. But I like writing code.

Have you seen this? Is this only a local (Northern California) issue?

If you've ever hired programmers:2

Of the résumés you've received, how old was the eldest applicant?

What was the age of the oldest person you've interviewed?

How old (when hired) was the oldest person you hired?

How old is "too old" to employed as a programmer?

1 I'm assuming all applicants have equivalent applicable experience. This isn't about someone with three decades of COBOL applying for a Java guru job.

2 Yes, I know that (at least in the US) you aren't supposed to ask how old an applicant is. In my experience, though, you can get a general idea from a résumé.

答: I'm 46.  I started programming back in the mid-1990's.  These days most employers value certifications more than resume content, which is sad, but that's what I see along the East coast at least.  Keep your skills current.  It's a pain. But that's what you have to do if you want to remain in the "hands-on" part of this industry.  Otherwise, like you said, pursue management positions.  Not as fun or interesting but these days a job is good to have.</p>

Title: How old is "too old"?


答:
The Apple ][ was generally programmed in either BASIC or 6502 machine code.

The Lisa was generally programmed in Pascal.

Early Macintosh apps were written in Pascal, first on the Lisa and later on the Mac itself.

Think Pascal was the most popular development environment for a time and then Think C. Think C had lightweight objects, sometimes referred to as C+-, and later C++. It also had its own class library called, appropriately enough, the Think Class Library.

MPW from Apple was also popular since it allowed you to mix languages (generally Pascal, C, C++, and assembler) and script builds similar to a unix environment, though the syntax was very different.

MacApp was written in Object Pascal, and as someone said, later moved to C++. With the move to PowerPC systems, many programmers switched to Metrowerks CodeWarrior as a development environment and its C++ class library, PowerPlant.

Objective-C was used at NeXT and then for Mac OS X, although Mac OS X applications could also be written in C/C++ via Apple's "Carbon" API. These days most Mac and iOS apps are written in Cocoa/Obj-C, although many have C or C++ libraries underneath.


问:
Understanding HTTP Cookies in Indy 10 for Delphi XE2
I have been working with Indy 10 HTTP Servers / Clients lately in Delphi XE2, and I need to make sure I'm understanding session management correctly. In the server, I have a "bucket" of sessions, which is a list of objects which each represent a unique session. I don't use username and password to authenticate users, but I rather use a unique API key which is issued to a client, and has an expiration.

When a client wishes to connect to the server, it first logs in by calling the "login" command, which is a path like this: http://localhost:1234/login?APIKey=abcdefghij. The server checks this API Key against the database, and if it's valid, it creates a new session in the bucket, issues a new cookie (unique string), and sets the response cookies with Success=Y and Cookie=abcdefghij.

This is where I have the question. Assuming the client end has its own method of cookie management, the client will receive this login response back from the server and automatically save the cookies as necessary. Any future request from the client to the server shall automatically send along these cookies, and the client side doesn't have to necessarily worry about setting these cookies when sending requests to the server. Right?

PS - I'm asking this question here on programmers.stackexchange.com because I didn't see it fit to ask on stackoverflow.com. If anyone thinks this is appropriate enough for stackoverflow.com, please let me know.

答:
Yes, the client - assuming a web browser - would send the cookie for that domain.  You dont need to send it each time.  Though a lot of applications do send the cookie back with each page so as to extend the expiration of the cookie.

You probably dont need the 'success' field - either the session id stored in the cookie is going to be valid, or it isnt.  If you are actually trying to return success or failure to the client, send back a bit of JSON instead as part of the response body.  That will be easier to handle on the client side in javascript.


问:
Event driven language for Robotics
There are several options that are available like C, C++, Matlab and some more. But is there a language that naturally feels like Event programming?

For example: If I see a red ball (Event) ---> Do this (Action)

答:
.NET Micro Framework can be an option for you. It has very little run-time, about 300Kb. You can program your MCU (ARM[7/9/CMx..]) with VB or C# using Visual Studio. While talking about robotics, hardware interrupts are also important. There is an option to use native code RPL, but I'm not sure it's possible to implement hardware interrupts like timer and edge triggering.. There are events for them, but they may do pooling behind the scenes.. Which means it's not real-time.
And MS Robotic Studio is a free tool that also serves event driven programming, and even Visual Programming (diagram based like Simulink).</p>

Title: Event driven language for Robotics


问:
UML - Class Diagrams Order -> Products
I have a class diagram that is like this:

```<code>< Order > (1) CAN HAVE (M) < products >
</code>```

But therefore Order has the following:

```<code>Order_Id
Customer_Id
Order_date_day
Order_date_month
Order_date_yeah
</code>```

But I do not know how it would handle the Products? Because, I couldn't have ProductID because that would mean that each item in this class would have to have a separate instance for each product (E.g. someone ordered 100 products, but only placed 1 order).

Could I have an Product object in class Order? If so, how do I represent that in UML?

答:
Normally, you have two classes in your diagram: Order and Product.

As an order usually means that the customer has ordered 1 or more (1..*) products, you model this by creating an association from the class Order to the class Product.

This coincides with adding a collection of Product instances to your Order instances, i.e. most code generators will give you a Order.getProducts() method or something similar. In fact, you can add such an association explictly as an attribute to the Order class. Some tools hide this fact, others allow you to see this distinction clearly (f.ex. Papyrus).

Title: UML - Class Diagrams Order -> Products


答:
Without getting into specific agile terminology, it looks like the fundamental problem is a lack of understanding and/or commitment to the client's responsibility during an iteration: once the set of implementable items is chosen (by the client, agreed to by devs) for an iteration, the client agrees not to change their mind until the end of the iteration.

This gives the devs a stationary target for a short time.

If the requirements are so unstable that they cannot survive a day alone, the project has problems far beyond the methodology... In that case, step back to the goals of the project, and reconsider the proposed features.


问:
Should I use C style in C++?
As I've been developing my position on how software should be developed at the company I work for, I've come to a certain conclusion that I'm not entirely sure of.

It seems to me that if you are programming in C++, you should not use C style anything if it can be helped and you don't absolutely need the performance improvement. This way people are kept from doing things like pointer arithmetic or creating resources with new without any RAII, etc. If this idea was enforced, seeing a char* would possibly be a thing of the past.

I'm wondering if this is a conclusion others have made? Or am I being too puritanical about this?

答:
There is one case where you definitely should write in C style, and this is hardware-related programming. The main reason why the "raw C" is preserved in the C++ language is not just backwards compatibility, but the "raw C" also enables C++ to be used in bare bone hardware applications: when you are accessing hardware directly, when there is no OS present, or when you are writing the OS itself.

There is also the performance argument. Idealists will tell you that you shouldn't use raw arrays, you should only use std::vector, and it should be equally fast as a plain array - if not then the compiler is bad. This is utopia, we have yet to see it. So far, STL and templates remain slower than "bare bone" code. However, the more C++ programmers that use templates, STL abstraction etc, the more pressure there will be on the compilers to produce faster code for it.

If the C features were removed from C++, then it wouldn't be as much of a general-purpose language as it is today. It wouldn't be used as much in embedded systems or performance-critical applications, it would become yet another desktop-only language like Java or C#.

Title: Should I use C style in C++?


问:
Is it conceivable to have millions of lists of data in memory in Python?
I have over the last 30 days been developing a Python application that utilizes a MySQL database of information (specifically about Norwegian addresses) to perform address validation and correction. The database contains approximately 2.1 million rows (43 columns) of data and occupies 640MB of disk space.

I'm thinking about speed optimizations, and I've got to assume that when validating 10,000+ addresses, each validation running up to 20 queries to the database, networking is a speed bottleneck.

I haven't done any measuring or timing yet, and I'm sure there are simpler ways of speed optimizing the application at the moment, but I just want to get the experts' opinions on how realistic it is to load this amount of data into a row-of-rows structure in Python. Also, would it even be any faster? Surely MySQL is optimized for looking up records among vast amounts of data, so how much help would it even be to remove the networking step? Can you imagine any other viable methods of removing the networking step?

The location of the MySQL server will vary, as the application might well be run from a laptop at home or at the office, where the server would be local.

答:
You will run into troubles if you try to use python lists for this kind of job. You will have a big memory overhead which is likely to prevent you to do anything useful with your data.

You should check Arrays (http://docs.python.org/2/library/array.html) or if you can numpy (http://numpy.scipy.org/).

If you still can't load all your data into memory, you can try to process it by chunks to limit the number of queries.

ContentLicense: CC BY-SA 4.0


问:
What do you optimize for?
Generally speaking, what type of optimizations do you typically slant yourself towards when designing software?

Are you the type that prefers to optimize your design for

Development time (i.e., quick to write and/or easier to maintain)?

Processing time

Storage (either RAM, DB, Disc, etc) space

Of course this is highly subjective to the type of problems being solved, and the deadlines involved, so I'd like to hear about the reasons that would make you choose one form of optimization over another.

答:
All of them

Processing time

Today's computers are fast, but far from what's enough. There're many many situations where performance is critical - if you do streaming media servers.

Storage

You customer might have a big disk, let's say, 1Tb. Which can be taken up by 1000 HD movies, if you want to make it a service it's far from enough, isn't it?

Development time

Well I'm not sure if this count as “optimization", what I do is I use Java instead of C++, and the development get 10 times faster. I feel like I'm telling what I think directly to the computer, very straight forward and totally rocks!

BTW I believe to speed up development your development process you should choose java, never try rubbishes like python... which claims they can shorten you DEV time.

Title: What do you optimize for?


问:
Structure of a Git repository
Sorry if this is a duplicate, I looked.

We're moving to Git. In Subversion, I'm used to having \trunk, \branches and \tags folders.

With Git, switching between branches will replace the contents of the working directory, so am I right to assume that the way we used to work just doesn't apply with Git?

My guess is that I'd have a repo folder with maybe a gitignore and readme.txt, then the folders for the projects that make up the repo, and that's it.

答:
You will have "trunk", now called "master", you will have "branches" now called "heads" and you will have "tags", still called "tags", but they won't be folders, they will be "refs", labels to revisions that live in separate namespace inside the repository.

Subversion and Git have different ways to do branching. The basic subversion model is to have a directory tree with single global timeline and if you want to branch, you copy a subtree in another directory.

On the other hand Git has a directory tree with revisions that each defines it's parents, but each revision can have multiple parents (a merge) and multiple children (branches). So instead of having directories for branches, you get independently created revisions. The "refs" are just names associated with latest revision for given "branch".

This difference is fundamental to distributed version control. Git (and other distributed systems) does not have any central authority to keep the history linear, so revisions can be created independently on multiple repositories without knowing about each other and the system has to accommodate them. It turns out the generalization makes branching and merging a lot easier in general.

Note, that in Git, revisions are not on any branch. They just are and branches contain them. But once branch is merged, or proves to be dead alley, you can just delete the "ref" pointing to it and forget about it altogether (if you discard old trials, they will be garbage-collected eventually with git gc). This helps you avoid getting swamped in old experiments nobody remembers what they were about anymore.

Title: Structure of a Git repository


问:
Why aren't Object Oriented databases used as much as Relational Databases?
I have come across many relational database management systems (RDBMS). But recently I used hibernate which made me start wondering why Object Oriented databases aren't more popular.

If object oriented languages like Java or C# are so popular, then why aren't object-oriented database management systems (OODBMS) more popular too?

答: OODBMS are good at storing complex data. However, most of the time, even when using OO languages, the needed data is relatively simple. So traditional RDBMS are more suited.</p>


答:
There are multiple reasons.

Many developers are only experienced in relational data modeling. To use OO databases, they would need to learn completely different way to model and think about data. This is either really hard or quite time consuming.

Relational DBs had lot of time to mature. Even free relational DBs have advanced optimization and indexing techniques. Also, relational data is easy to store and index. Same thing cannot be said about OO databases.

When relational and OO models started to emerge. Relational had huge edge that it was mathematically "correct" and it had it's standard for saving and querying data. OO had nothing of sort.

[speculation]Many big players put lots of resources into making their relational DBs. It would be counterproductive to support OO DBs instead. So many of them instead invested into integrating OO principles into relational model, making most current DBs so-called object-relational. IMO these models are worst than pure relational or pure OO.[/speculation]

[rant]Last thing to note is that many developers don't really understand OO way to model data. This usually results in suboptimal, anemic models. So many development companies, that rely on cheap and inexperienced developers would rather choose simple, relational model, that is taught in all CS colleges than pick hard and unproven OO aproach.[/rant]

Title: Why aren't Object Oriented databases used as much as Relational Databases?

Body:
I have come across many relational database management systems (RDBMS). But recently I used hibernate which made me start wondering why Object Oriented databases aren't more popular.

If object oriented languages like Java or C# are so popular, then why aren't object-oriented database management systems (OODBMS) more popular too?


答:
When databases first appeared, OOP still wasn't the way to program. Relational databases, on the other hand, gained a lot of traction. And SQL introduced in the 80's by IBM quickly became lingua franca of all databases.

When OOP become popular there were some attempts, but there are some problems. First, true OODBMS is really hard to implement. In case of a relational database, a table and related indexes are fairly simple structures (eg. B-trees).
Another reason is that there is a lot of theory behind relational model, it's directly derived from mathematical set theory. There are known ways to correctly design a relational database (think normalization etc). And last but not least, people already got used to SQL a lot.

Modern-day NoSQL solutions in most cases aren't really a step towards OODBMS. Many of them are still relational, only stripped of JOINs. Few of them are in fact object stores but are not truly OODBMS, as they are not aware of relations between the objects.

Yet another reason why there is not such a strong push for OODBMS is that there is "poor man's OODBMS" solution — ORMs. This has gained huge popularity, as they are backed by well known, stable and tested DB engines, yet they provide the mapping to objects. Of course, these are not true OODBs.


问:
What is abstraction?
Is there a generally agreed upon definition for what a programming abstraction is, as used by programmers? [Note, programming abstraction is not to be confused with dictionary definitions for the word "abstraction."] Is there an unambiguous, or even mathematical definition? What are some clear examples of abstractions?

答:
I think you might find a blog post of mine on leaky abstractions useful. Here is the relevant background:

Abstraction is a mechanism to help take what is common among a set of related program fragments, remove their differences, and enable programmers to work directly with a construct representing that abstract concept. This new construct (virtually) always has parameterizations: a means to customize the use of the construct to fit your specific needs.

For example, a List class can abstract away the details of a linked-list implementation-- where instead of thinking in terms of manipulating next and previous pointers, you can think on the level of adding or removing values to a sequence. Abstraction is an essential tool for creating useful, rich, and sometimes complex features out of a much smaller set of more primitive concepts.

Abstraction is related to encapsulation and modularity, and these concepts are often misunderstood.

In the List example, encapsulation can be used to hide the implementation details of a linked-list; in an object-oriented language, for instance, you can make the next and previous pointers private, where only the List implementation is allowed access to these fields.

Encapsulation is not enough for abstraction, because it does not necessarily imply you have a new or different conception of the constructs. If all a List class did was give you 'getNext'/'setNext' style accessor methods, it would encapsulate from you from the implementation details (e.g., did you name the field 'prev' or 'previous'? what was its static type?), but it would have a very low degree of abstraction.

Modularity is concerned with information hiding: Stable properties are specified in an interface, and a module implements that interface, keeping all implementation details within the module. Modularity helps programmers cope with change, because other modules depend only on the stable interface.

Information hiding is aided by encapsulation (so that your code does not depend on unstable implementation details), but encapsulation is not necessary for modularity. For example, you can implement a List structure in C, exposing the 'next' and 'prev' pointers to the world, but also provide an interface, containing initList(), addToList(), and removeFromList() functions. Provided that the rules of the interface are followed, you can make guarantees that certain properties will always hold, such as ensuring the data-structure is always in a valid state. [Parnas's classic paper on modularity, for example, was written with an example in assembly. The interface is a contract and a form of communication about the design, it does not necessarily have to be mechanically checked, although that's what we rely on today.]

Although terms like abstract, modular, and encapsulated are used as positive design descriptions, it's important to realize that the presence of any of these qualities does not automatically give you good design:

If an n^3 algorithm is "nicely encapsulated" it will still perform worse than an improved n log n algorithm.

If an interface commits to a specific operating system, none of the benefits of a modular design will be realized when, say, a video game needs to be ported from Windows to the iPad.

If the abstraction created exposes too many inessential details, it will fail to create a new construct with its own operations: It will simply be another name for the same thing.

Title: What is abstraction?


答:
I do not know how it would handle the Products

Assuming that you are modeling this to generate RDBMS tables, you would generally use 2 separate classes. The 'child' class would have the Product attributes plus the Product_Id  acting as a 'foreign key'. The other class is your Order class.

The diagram in the answer of @Esther Fan - MSFT in UML-arrows-pointers-explanation shows more than what you want in fact, however, on a class level its what you want. Just replace the word "Order_Item" by the word "Product" in the class diagram and ignore the other classes not related to your case.

The MSDN link provided within that answer may also be useful for you.

An important business rule you need to consider is whether an Order occurence is meaningful without Products or not. The diagram in the link above assumes a composition association between Order and Product (Black diamond), this may or may not be your case, so please check.

It is also common to have a class for a requesting entity and a product reference entity shown but you did not ask for those. As an example, have a look at: Simple Class Diagram.

I couldn't have ProductID because that would mean that each item in this class would have to have a separate instance for each product (E.g. someone ordered 100 products, but only placed 1 order).

The above situation is not a problem. Each of the products would use the FK column (Order_Id). The value in that column would be the same for the 100 products.

Could I have an Product object in class Order?

Yes, but this will not replace the 1-M pattern existing here. See a UML representation sample here: Inner-Internal Class.

Note that in cases, you need programming data structures for representing collections of data in your code that is different from the data structure you use to represent the same information in the database if you use RDBMS from an OO application.

Title: UML - Class Diagrams Order -> Products

Body:
I have a class diagram that is like this:

```<code>< Order > (1) CAN HAVE (M) < products >
</code>```

But therefore Order has the following:

```<code>Order_Id
Customer_Id
Order_date_day
Order_date_month
Order_date_yeah
</code>```

But I do not know how it would handle the Products? Because, I couldn't have ProductID because that would mean that each item in this class would have to have a separate instance for each product (E.g. someone ordered 100 products, but only placed 1 order).

Could I have an Product object in class Order? If so, how do I represent that in UML?


答:
I would avoid to load all the 2.1 million rows into memory (at least, it would not be my first choice to do so). Even if you can do this with one query, and even if you get around the memory issues, it will still take a while to get all that data to the client. Lookups in that data may be probably faster than by a lot of SQL queries over the network, but if that really pays in comparison to the initial loading is questionable (of course, you will have to measure to be sure).

If I got you right, you don't need the all that data to perform the validation - you need only data for ~10.000 addresses, and a number of records from the database of comparable size. What I would probably try to is to reduce the number of queries to get exactly that data. Perhaps you don't need 20 queries per address and can reduce it to 10? This would be a start. Perhaps you can get the data for multiple addresses in one query instead of many, using the IN or OR operators in the WHERE clauses of your statements? That would probably help, too, since for small amount of data, often only the number of queries is the key factor, not if you get 10, 100 or 1000 bytes result set.

If you want more specific advice, you have to provide more details about the data model and the queries you are using.

EDIT: assumed your address database is frozen for several months, that would qualify to use a local copy of the whole database as a cache. Something like SqlLite should be the logical choice here: a very fast, server-less, in-process (and optionally in-memory) database, where the whole data can be stored in one file. You can still use SQL for all queries you need, and the transition from MySQL tables to SqlLite tables should be straightforward (as long as you did not use any too-MySQL-specific things in your current database so far).

Consider, if you are trying to keep the local copy of your db tables completely in Python row-of-rows, depending on the complexity of the data model, you would probably end up building something like your own "poor-mans" in-memory database on your own. So why reinvent the wheel?

Information about the SqlLite Python interface: http://docs.python.org/2/library/sqlite3.html. Another advantage: if the address data is updated on the server, this approach will more or less easily allow to create the database copy once on the server and send the data in one file over the network to the client.

Title: Is it conceivable to have millions of lists of data in memory in Python?

Body:
I have over the last 30 days been developing a Python application that utilizes a MySQL database of information (specifically about Norwegian addresses) to perform address validation and correction. The database contains approximately 2.1 million rows (43 columns) of data and occupies 640MB of disk space.

I'm thinking about speed optimizations, and I've got to assume that when validating 10,000+ addresses, each validation running up to 20 queries to the database, networking is a speed bottleneck.

I haven't done any measuring or timing yet, and I'm sure there are simpler ways of speed optimizing the application at the moment, but I just want to get the experts' opinions on how realistic it is to load this amount of data into a row-of-rows structure in Python. Also, would it even be any faster? Surely MySQL is optimized for looking up records among vast amounts of data, so how much help would it even be to remove the networking step? Can you imagine any other viable methods of removing the networking step?

The location of the MySQL server will vary, as the application might well be run from a laptop at home or at the office, where the server would be local.


问:
how do early stage startups hire ninja programmers
I am programmer who just started working on a startup idea. At the moment I want to bring onboard at least one programmer. This programmer should be a ninja - a 10x engineer.

Since early days are probably the most risky for a startup, I want to make sure I approach this problem the best I can.

How do I find these people? and How do I convince them to come onboard?

I would love to hear from people who started their own companies and what their thoughts are about hiring

Update: I would like to get the ninja as a co-founder so besides being a ninja (ie. great programmer with computer science background) he/she has to have a healthy appetite for risk (for great programmers this is not a big deal because they can be hired anytime into mainstream jobs if the startup doesn't work)

答:
Successful startups? It's about who you know. In fact, it's a fairly bad sign for a start-up if they need to post ads looking for programmers. That means that the founders couldn't convince any of their hundreds of programming acquaintances to get on board with the idea.

Unsuccessful startups? They tend to have too many "original founders" and managers, and not enough programmers willing to sacrifice major parts of their lives on a risky idea.

Quite simply, think of the ninja programmers you already know, your friends, and ask them. If not one of them is interested, or wants to let their other ninja friends know about it, then you may want to reconsider your strategy, service, or product until they do. Think about all of the successful startup stories. It's always a group of friends or people who already knew and worked with each other.


问:
Should the analyst define the programmers and their seniority needed by the project?
It might be obvious, but I am not sure.

Should the analyst who interview the client, gather and analyse requirements then give an estimate, also specifies how many and with how much experience developers should be required to develop it?

Maybe I'am not so sure on how I go about this allocation thing, maybe this is just not my work.

答:
If your organization isn't very big, then you won't have enough programmers to choose from and you should give the work to the programmer who is least busy.  They can tell you if an assignment is beyond their technical abilities or their ability to meet the artificial deadline you have probably set for them.

If your organization is big enough that you have lots of programmers to choose from, then the programmers probably have a more or less formal management structure and you should leave the decision of who does what work to that management.  The team leads and seniors know who can do what and who is busy and who isn't.

As for giving estimates, I think the days of analysts sitting between users and programmers and making all of the design and project management decisions have passed.  If you want the people doing the work and the people paying for the work to own the decisions you need to put them face to face and let them work together.  This is what Agile is supposed to be about.