问:
What type of encoding can I use to make a string shorter?
I am interested in encoding a string I have and I am curious if there is a type of encoding that can be used that will only include alpha and numeric characters and would preferably shorten the number of characters needed to represent the string.

So far I have looked at using Base64 encoding to do this but it appears to make my string longer and sometimes includes == which I would like to avoid.  Example:

test name|120101

becomes

dGVzdCBuYW1lfDEyMDEwMQ==

which goes from 16 to 24 characters and includes non-alphanumeric.

Does anyone know of a different type of encoding that I could use that will achieve my requirements?  Bonus points if it's either built into the .NET framework or there exists a third party library that will do the encoding.

答: You can compress the data with e.g. gzip, bzip2 or lzma and then run through base64 to limit the used character set. This is beneficial only on larger strings of hundreds of bytes or more.</p>


问:
Is there a quasi-standard set of attributes to annotate thread safety, immutability etc.?
Except for a blog post here and there, describing the custom attributes someone created, but that do not seem to get any traction - like one describing how to enforce immutability, another one on Documenting Thread Safety, modeling the attributes after JCIP annotations - is there any standard emerging? Anything MS might be planning for the future?

This is something that should be standard, if there's to be any chance of interoperability between libraries concurrency-wise. Both for documentation purposes, and also to feed static / dynamic test tools.

If MS isn't doing anything in that direction, it could be done on CodePlex - but I couldn't find anything there, either.

<opinion>Concurrency and thread safety are really hard in imperative and object-languages like C# and Java, we should try to tame it, until we hopefully switch to more appropriate languages.</opinion>

答: I don't think there's a set of standards (even quasi) right now. Isolated projects do some of this in their own way. In a thread post they talk about immutability via code contracts and even baking directly into the type system. I've seen even less about thread safety.</p>

OwnerDisplayName: Eugene Beresovksy

ContentLicense: CC BY-SA 4.0

OwnerDisplayName: Kit

ContentLicense: CC BY-SA 3.0


答:
The problem with both immutability and thread safety are that they are not black and white concepts, but there are a number of possible guarantees in that regard. Reducing that to simple attributes might be hard. IMO a simple ThreadSafe and Immutable attribute isn't enough. Still working out a set of attributes capturing at least the most important semantics sounds promising to me.

For example take an AddRange method. It might be thread safe enough to never corrupt the state of the underlying collection, but might not be atomic. A common implementation with these properties might be just calling an atomic Add method for each element.

On the immutability side we have different aspects too:

Offering only readonly accessors or truly never changing

Depth of immutability i.e. are sub-objects immutable too

Physical vs. logical immutability. For example lazy initialization does not change the visible state, but changes the internal state.

One annotation is this context already exists: Pure for side effect free methods.

Title: Is there a quasi-standard set of attributes to annotate thread safety, immutability etc.?

Body:
Except for a blog post here and there, describing the custom attributes someone created, but that do not seem to get any traction - like one describing how to enforce immutability, another one on Documenting Thread Safety, modeling the attributes after JCIP annotations - is there any standard emerging? Anything MS might be planning for the future?

This is something that should be standard, if there's to be any chance of interoperability between libraries concurrency-wise. Both for documentation purposes, and also to feed static / dynamic test tools.

If MS isn't doing anything in that direction, it could be done on CodePlex - but I couldn't find anything there, either.

<opinion>Concurrency and thread safety are really hard in imperative and object-languages like C# and Java, we should try to tame it, until we hopefully switch to more appropriate languages.</opinion>

OwnerDisplayName: CodeInChaos


问:
What is the market share of programs written in .NET nowadays?
We are currently migrating our Visual Basic 6.0 program to .NET. The target audience are just normal desktop users at home. Discussing this, we realized that we cannot come up with mainstream programs that seem to be written in .NET. Are we mistaken? Is there a good reason for this?</p>

答:
VB6 is no longer supported by MS any more (ref: http://blogs.technet.com/b/lifecycle/archive/2008/04/16/end-of-support-for-visual-basic-6-0.aspx).  So if you have issues from a development standpoint, you will not get support from the source.

VB.NET, on the other hand, is still actively developed and supported.

The similarity between the .NET Framework and the Java JRE as well as the similarities between C# and Java itself has grown the C#/.NET developer community extremely quickly.

The supply of VB6 developers is going to dwindle while the VB.NET/C# ones are likely to increase and can keep your product moving forward.


问:
Is "White-Board-Coding" inappropriate during interviews?
This is a somewhat subjective quesiton but I'd love to hear feedback/opinions from either interviewers/interviewees on the topic.

We split our technical interview into 4 parts. Write Code, Read & Analyse Code, Design Session & Code on the white board.

For the last part what we ask interviewees to do is write a small code snippet (4-5 lines) on the whiteboard and explain as they go through it. Let me be clear the purpose is not to catch people out. We're not looking for perfect syntax. Hell it can even be pseudo-code. but the point is to give them a very simple problem and see if their brain can communicate the solution to us. By simple problems I mean "Reverse a string", "FizzBuzz" etc...

Note that we always ask for an explicit language first. We're a .NET C# house. we've only said "pseudo-code" where someone has been blanking/really struggling with the code.

My question is "Is it inappropriate / unreasonable to expect a programmer to write a code snippet on a whiteboard during an interview ?"

答:
No, but IMO a better approach would be to use the whiteboard for its intended purpose and use UML/sketches/notes for some fictitious project, rather than the old "write me a sql query to get all records" or "write a method that reverses a string".

One of the best interviews I had was spending like 20 minutes discussing with the lead developer the architecture (non-software) for a mad scientist's mansion (complete with secret hideout, death ray and dog kennel).  He got to see my approach at solving problems, and the problem was something fun not typical rote programming 101 stuff that's been solved by modern languages a thousand times over.  Incidentally I also did a piece of code like this before, but I felt much more "under pressure" than with the architecture part.


答:
Depending on the definition of "main stream programs", there don't seem to be many of them to be written in VB6 either.

Of course, C# and VB.NET now has taken almost the place where VB6 was ~10 years ago. At least 98% is individual software you cannot buy in your local software store. But that does not mean there are no .NET programs out there. There are a lot - but you will have to search for them at the right places.

Title: What is the market share of programs written in .NET nowadays?

Body: We are currently migrating our Visual Basic 6.0 program to .NET. The target audience are just normal desktop users at home. Discussing this, we realized that we cannot come up with mainstream programs that seem to be written in .NET. Are we mistaken? Is there a good reason for this?</p>


答:
why not use LZ compression? this can be a decent way of compressing a string, but would be more efficient in case of long strings.
How long is the target string you want to encode?</p>

OwnerDisplayName: Abe Miessler

Title: What type of encoding can I use to make a string shorter?

Body:
I am interested in encoding a string I have and I am curious if there is a type of encoding that can be used that will only include alpha and numeric characters and would preferably shorten the number of characters needed to represent the string.

So far I have looked at using Base64 encoding to do this but it appears to make my string longer and sometimes includes == which I would like to avoid.  Example:

test name|120101

becomes

dGVzdCBuYW1lfDEyMDEwMQ==

which goes from 16 to 24 characters and includes non-alphanumeric.

Does anyone know of a different type of encoding that I could use that will achieve my requirements?  Bonus points if it's either built into the .NET framework or there exists a third party library that will do the encoding.


问:
How Do I interview Front-End Web Developers?
For the first time I'm in the position where I'm helping interview potential front-end developers. The other interviewer is more business & PM-focused, although he is a former developer. I probe for knowledge and background in CSS, Javascript, and other related technologies, but those questions are really just testing for lingo.  I feel that it would be unfair to ask very specific questions about CSS when we're not in front of a computer.

I've also been given websites that these web developers have written. Is that enough to go on for interviewing front-ends?  We're also looking for general aptitude, rather than a databank of knowledge.

答: Give them a test page to build. Then the interview would be more about whether or not you would actually like to sit beside them in an office for 10 hours a day. </p>


问:
Where to go from here, how to improve / learn more

Possible Duplicate:

  I'm graduating with a Computer Science degree but I don't feel like I know how to program

I finished University around 4 years ago double degree in Software Eng/Comp Sci. Got my first job at a startup in my final year, was with them for 2.5 years then started my own business.

So far everything is going great, lots of clients and stead work etc, but coming right out of uni and into a start up I never had any form or senior software engineer guiding my work or suggesting improvements etc...

Whats the best way for me to improve & learn more? Books? MS Exams? Other?

I develop in C#, ASP.NET/MVC.

Update
The problem isn't really with releasing products, I've released quite a few which are up and running with customers happy. It's more with quality of code, best practices, how do I know something I am code is correct, it may work but there may be ways of coding it much more efficiently or by adhering to some kind of standard

Cheers for any responses!

Matt

答:
You are already doing things right.  You are coding, have steady work, and have happy customers.

I would suggest to continue with what you are doing right.

I would add in reviewing Open Source code. Currently what I've done is import the Spring Framework into my ide and I look at that for example.   I also do open source code searches with Koders http://www.koders.com/

I also would network with other developers at the local user groups for what you are coding in or would like to work with in the future.


问:
Why don't we store the syntax tree instead of the source code?
We have a lot of programming languages. Every language is parsed and syntax checked before being translated into code so an abstract syntax tree (AST) is built.

We have this abstract syntax tree, why don't we store this syntax tree instead of the source code (or next to the source code)?

By using an AST instead of the source code. Every programmer in a team can serialize this tree to any language they want (with the appropriate context free grammar) and parse back to AST when they are finished. So this would eliminate the debate about the coding style questions (where to put the { and }, where to put whitespace, indentation, etc.)

What are the pros and cons of this approach?

答:
Why don't we store this syntax tree instead of the source code? Every programmer in a team can serialize this tree to any language, they want and parse back to AST when they finished.

Indeed, that is a reasonable idea. Microsoft had a research project in the 1990s to do almost exactly that.

Several scenarios come to mind.

The first is rather trivial; as you say, you could have the AST rendered into different views depending on the preferences of different programmers for things like spacing and so on. But storing an AST is overkill for that scenario; just write yourself a pretty-printer. When you load a file into your editor, run the pretty-printer to put it into your preferred format, and back into the original format when you save it.

The second is more interesting. If you can store the abstract syntax tree then code-diffing a change becomes not textual but rather syntactic. Refactorings where code is moved around become much easier to understand. The down side is of course that writing the tree-diff algorithms is not exactly trivial and often has to be done on a per-language basis. Text diff works for almost any langauge.

The third is more like what Simonyi envisioned for Intentional Programming: that the fundamental concepts common to programming languages are what are serialized, and then you have different views of those concepts rendered in different languages. Though a beautiful idea, the ugly fact is that languages are sufficiently different in their details that a lowest-common-denominator approach doesn't really work.

So, in short, it's a lovely idea but it is an enormous amount of extra work for a comparatively small benefit. That's why hardly anyone does it.


问:
Stuff every programmer needs while working
I've been tasked with creating a fun and relaxing environment, one thing I know that I want is ergonomic mice and keyboards, others have suggested exercise balls and bands.

What is it that every programmer needs while working? What might not be necessary but would be nice to have anyway?

Note: this question was asked previously, but has been recommended to be posted here. See this link for the previous responses: https://stackoverflow.com/questions/3911911/stuff-every-programmer-needs-while-working-closed

答:
A Phone!

Why hasn't this been said yet? I need a phone to communicate with my colleagues, much easier than e-mailing them sometimes.

(Off course, my phone has a log-out/turn-off button on it so I don't get disturbed when I want to.)

ContentLicense: CC BY-SA 2.5


问:
Best design for a memory resident tool
I apologize if this tends more toward design that programming, but here goes.

What design would you recommend for a database that is

Memory resident

Must run on windows, linux and (at a stretch) the mac

Accept multiple queries simultaneously

Have minimum overhead, since a search is expected to take <0.25s

This program implements a domain-specific search. Think of it as a database, but one that takes advantage of domain specific information to outperform a convential database search (for example, with custom oracle indexing). We have a custom data structure for our data. Our protoype is a simple exe that constructs the database in memory each time it is run. We were thinking that perhaps this program would suffice, but augmented with sockets so it can listen for queries.

This database will be static. Its contents will change infrequently.

We expect queries, and the solution, to be delivered via a web service.

答:
All the usual questions about database design apply.  How many records, how big are the records, how do you search, will you be updating or deleting, or just displaying, ...

In "Oberon - The Overlooked Jewel", Franz tells a story.  The original Oberon (a PASCAL-like language) compiler at ETH-Zurich used a very elegant multiply-linked symbol table structure.  One day, Wirth tore it out and replaced it with an array and a linear search.  On their standard benchmark, which was the time the compiler took to recompile itself, the linear search was faster.

If a simple linear search through a straight array is Good Enough, you're done.

OwnerDisplayName: Andrew S.

Title: Best design for a memory resident tool


答: If you are expecting the designer to work with programmers, In addition to what have been listed before you need to check the personality of the person and how he/she views the programmer-designer relationship. Also, if the designer is expected to amend or maintain existing sites, then they should be comfortable in the tools and the code in those sites as well as the existing code and the used tools. It helps to ask them about their opinion in style of existing sites either internal or external and see how this view fits the culture of your organization.</p>

Title: How Do I interview Front-End Web Developers?

Body:
For the first time I'm in the position where I'm helping interview potential front-end developers. The other interviewer is more business & PM-focused, although he is a former developer. I probe for knowledge and background in CSS, Javascript, and other related technologies, but those questions are really just testing for lingo.  I feel that it would be unfair to ask very specific questions about CSS when we're not in front of a computer.

I've also been given websites that these web developers have written. Is that enough to go on for interviewing front-ends?  We're also looking for general aptitude, rather than a databank of knowledge.


问:
What is the actual problem with a prototype based design?
I feel like anything that can be developed using OO/functional languages can be generally made 'better' using a prototype based language, because they appaer to have the best of them all: high order functions, flexibility to simulate any OO structure, productivity (low verbosity) and scalability because of concurrency. But it seems like they are avoided for the creation of executable applications and of bigger projects in general. Why that?</p>

答:
I don't think there's anything fundamental, but in javascript specifically there are a few issues that can cause trouble in large scale software:

Encapsulation is weak: it very easy for any other code to inspect and modify any other code. This allows some powerful things, but it can also lead to problems in large projects. Hard to find bugs can happen if you accidentally step on some code that isn't yours.

convenience over security: js has features like arguments.callee which allows any function to call all the way up the stack and access the root (window in a browser) object. This means that you really need to trust any third party code you call. This isn't an issue for every application, but it does constrain what you can do (strict mode fixes this, but can't be relied upon in a browser context)

anything numeric is extremely awkward: every number is a float, which is probably the right choice if you're only going to have one number type, but makes dealing with binary data and integer arithmetic awkward.

boilerplate required for typical oo style: it's awesome that you can make a library that implements classes in javascript, but on the downside you're going to need one, and everyone new is going to need to learn the particular library you use.

None of these kill javascript for large projects, and all languages have their own drawbacks -- these are just thigns to be aware of while using js. Using new js features and only targeting modern js engines (v8 for example), which you can do for a standalone app, allows you to avoid some of these issues. External tools can also provide some help (for example the closure compiler from google does various forms of static checking).


答:
There are actually several products, generally known as "language workbenches" that store ASTs and present, in their editors, a "projection" of the AST back into a particular language. As @sk-logic said, JetBrains' MPS is one such system. Another is Intentional Software's Intentional Workbench.

The potential for language workbenches seems very high, particularly in the area of domain-specific languages, since you can create a domain-specific projection. For instance, Intentional demos a DSL relating to electricity that projects as a circuit diagram -- much easier and more accurate for a domain expert to discuss and criticize than a circuit described in a text-based programming language.

In practice, language workbenches have been slow to catch on because, aside from DSL work, developers would probably prefer to work in a familiar, general programming language. When compared head-to-head with a text editor or programming IDE, the language workbenches have tons of overhead and their advantages are not nearly as clear. None of the language workbenches that I've seen have boot-strapped themselves to the point where they can easily extend their own IDEs, either -- that is, if language workbenches are great for productivity, why have not the language workbench tools become better-and-better at faster-and-faster rates?

Title: Why don't we store the syntax tree instead of the source code?

Body:
We have a lot of programming languages. Every language is parsed and syntax checked before being translated into code so an abstract syntax tree (AST) is built.

We have this abstract syntax tree, why don't we store this syntax tree instead of the source code (or next to the source code)?

By using an AST instead of the source code. Every programmer in a team can serialize this tree to any language they want (with the appropriate context free grammar) and parse back to AST when they are finished. So this would eliminate the debate about the coding style questions (where to put the { and }, where to put whitespace, indentation, etc.)

What are the pros and cons of this approach?


问:
Guidance for a C# developer to become better UI developer
I am a C# developer and had developed simple websites in regular asp.net(with asp.net controls) and a wpf application.

Nowadays, I am trying to learn Asp.net MVC3 and I have been exposed to HTML with the Razor view Engine. To be honest, my knowledge of HTML and CSS is limited. Therefore, I keep posting questions now and then on SO for very simple tasks.

This has made me very tired of the this Q&A development process. So, now i am thinking of learning the basics of HTML, CSS and maybe some Javascript. Therefore i would request you to guide me to become an efficient enough developer for these technologies. Something that won't take much time and get me up and running fast.

答:
I am not going to bother posting links to HTML and CSS tutorials because a quick Google search should turn up hundreds of good resources for this.

I will share with you a tool that was invaluable to myself for learning and debugging CSS in my browser.  If you have Firefox, download an Add-On called Firebug.  It is a neat console that provides amazing features for viewing and real-time editing of HTML, CSS, and JavaScript in ANY web page that you visit.  Using this tool I can tinker with stylesheets and styles on specific DOM elements and immediately see the results in my browser.

It also has a built in JavaScript debugger that allows you to write JavaScript expressions as well.  Furthermore I can traverse the elements and attributes of the DOM tree to find neat information that may be hidden.  All of these features are invaluable when doing development in ASP.NET or JSF and you need to debug complicated problems with third-party server controls.  They also help me find neat workarounds.

On top of that, there is a tab for viewing all HTTP requests and responses, allowing you to view the content of any individual request and response as well as headers.


答: Try to work with a variety of developers on projects that you take seriously and attempt to learn from their strengths and recognize their weaknesses. It doesn't matter if they are better or worse than you, teaching is also a great way to learn.</p>

Title: Where to go from here, how to improve / learn more

Body:
Possible Duplicate:

  I'm graduating with a Computer Science degree but I don't feel like I know how to program

I finished University around 4 years ago double degree in Software Eng/Comp Sci. Got my first job at a startup in my final year, was with them for 2.5 years then started my own business.

So far everything is going great, lots of clients and stead work etc, but coming right out of uni and into a start up I never had any form or senior software engineer guiding my work or suggesting improvements etc...

Whats the best way for me to improve & learn more? Books? MS Exams? Other?

I develop in C#, ASP.NET/MVC.

Update
The problem isn't really with releasing products, I've released quite a few which are up and running with customers happy. It's more with quality of code, best practices, how do I know something I am code is correct, it may work but there may be ways of coding it much more efficiently or by adhering to some kind of standard

Cheers for any responses!

Matt


答:
UI is and is not a technical problem. It is inasmuch as you need to use technical tools to solve things on some levels and the art of the possbible is defined by the platform you are working in. But the biggest thing you can do to make yourself a better UI developer is really to learn how to think of user interfaces from the user's perspective. Remember, your user don't care about:

Your data model

Separation of concerns

Whatever cool toolkit you are using

Pretty much just about anything else that went into making the UI

Your UI is just a means to an end for them. They do care about doing what they want to do with a minimum of fuss or confusion but little else.

To wit, I'd advise reading up on great user interfaces. A great place to start is Steven Krug's Don't Make Me Think.

The other thing I really strongly believe in is that developers must use their own user interfaces. The dev team should enter the first 1000 or so records in a system. It is funny how many annoying low-hanging fruit get fixed when that happens. And it is surprising how much you learn from using the things you create that can get pushed into the next creation.

Title: Guidance for a C# developer to become better UI developer

Body:
I am a C# developer and had developed simple websites in regular asp.net(with asp.net controls) and a wpf application.

Nowadays, I am trying to learn Asp.net MVC3 and I have been exposed to HTML with the Razor view Engine. To be honest, my knowledge of HTML and CSS is limited. Therefore, I keep posting questions now and then on SO for very simple tasks.

This has made me very tired of the this Q&A development process. So, now i am thinking of learning the basics of HTML, CSS and maybe some Javascript. Therefore i would request you to guide me to become an efficient enough developer for these technologies. Something that won't take much time and get me up and running fast.


答:
Personally, I'd walk out on any interviewer asking me to do FizzBuzz. I don't know when this became the new industry standard, but it's really a waste of time. FizzBuzz is a filter that can be used ahead of an interview, although personally I think if I had to pick from N candidates of which enough have some open source code or a blog I can look at, I'd definitely prefer that as a filter.

Simply put, I think in an interview for a programming position (except maybe for juniors or internships), it should already have been established/determined that the interviewee can program.

But yes, whiteboard is perfect, although I think you should take a different set of problems. Throw them a real-world problem and have them draw a bunch of UML-ish squibbles to explain their overall strategy to solve that problem. Give them a computer with internet, so they can look for 3rd-party libraries they could use as black-boxes in their squibblescape.

Within a few minutes, you will really see how they tackle problems. You can actually make this a very interesting thing, by picking problems that you don't necessarily have a solution for in mind and attempt to "solve" them together, to see how well they communicate and how well they can incorporate input (however don't push them too hard - some people might just freeze if you do). And then add a few requirements on the fly. This is kind of like software development without implementation and -most importantly- without debugging, so 15 minutes is a lot of time.

Title: Is "White-Board-Coding" inappropriate during interviews?

Body:
This is a somewhat subjective quesiton but I'd love to hear feedback/opinions from either interviewers/interviewees on the topic.

We split our technical interview into 4 parts. Write Code, Read & Analyse Code, Design Session & Code on the white board.

For the last part what we ask interviewees to do is write a small code snippet (4-5 lines) on the whiteboard and explain as they go through it. Let me be clear the purpose is not to catch people out. We're not looking for perfect syntax. Hell it can even be pseudo-code. but the point is to give them a very simple problem and see if their brain can communicate the solution to us. By simple problems I mean "Reverse a string", "FizzBuzz" etc...

Note that we always ask for an explicit language first. We're a .NET C# house. we've only said "pseudo-code" where someone has been blanking/really struggling with the code.

My question is "Is it inappropriate / unreasonable to expect a programmer to write a code snippet on a whiteboard during an interview ?"


答:
Learning a technology from scratch using boards is definitly not an idea I would encourage for non-trivial tasks.

Web page design is significantly different from windows design.

Web design sometimes mean one or more of the following:

A - Web page layout

B - Graphics design

C - User interaction design

D - HTML and CSS coding

E - Java Scripting!

F - Using supporting tools of the above

Each of the above is a different aspect and require special skills. So, identify your role in the project and your objectives from learning first.

I suggest you try a formal design courses. Start with a video course and then move to an instructor lead course.

If you are a programmer focus on the programming of the frameworks and leave the artistic design to other professionals.

If you want to just know about it, then the courses should do it. If you can't do HTML, don't give up. Consider using Silverlight. It is very similar to WPF (at least for the XAML part).


答: No, it is a good thing to code for an interview, but you should allow code in any reasonable language as it is usually easier to train a coder competant in another language than to get a a so-so coder in the language you want, up to a competant level.</p>


问:
VB.Net vs C# debate
I've been in workplaces where, at the start of a project, the "Should we use VB.Net or C#" question has been raised.

Granted, it's probably less common to have to make that decision now than it was in the early days of .Net, particularly given the trend towards language convergence, but it can still be a heated debate.

So, between VB.Net and C#, Which language do you prefer and why?

答:
They are functionally the same, there is nothing you can do in one you can't do in the other, and for the future Microsoft have pledged that the language teams will develop both evenly so this is equivalence unlikely to change.

The differences now are purely cultural and personal. This article is interesting reading on the differences between the cultures of programmers using C# and VB.net

[Note: Although I'm a C# dev myself, the linked article's conclusion does not necessarily reflect my personal opinion, it's just an interesting alternative approach in the debate]

Title: VB.Net vs C# debate


问:
What's wrong with circular references?
I was involved in a programming discussion today where I made some statements that basically assumed axiomatically that circular references (between modules, classes, whatever) are generally bad.  Once I got through with my pitch, my coworker asked, "what's wrong with circular references?"

I've got strong feelings on this, but it's hard for me to verbalize concisely and concretely.  Any explanation that I may come up with tends to rely on other items that I too consider axioms ("can't use in isolation, so can't test", "unknown/undefined behavior as state mutates in the participating objects", etc.), but I'd love to hear a concise reason for why circular references are bad that don't take the kinds of leaps of faith that my own brain does, having spent many hours over the years untangling them to understand, fix, and extend various bits of code.

Edit: I am not asking about homogenous circular references, like those in a doubly-linked list or pointer-to-parent.  This question is really asking about "larger scope" circular references, like libA calling libB which calls back to libA.  Substitute 'module' for 'lib' if you like.  Thanks for all of the answers so far!

答: They may be bad not by themselves but as an indicator of a possible poor design. If Foo depends on Bar and Bar depends on Foo, it is justified to question why they are two instead of a unique FooBar.</p>

Title: What's wrong with circular references?


问:
What's the best way to learn image processing?
I'm a senior in college that hasn't done much image processing before (except for some basic image compression on smartphones). I'm starting a research project on machine learning next semester that would require some biomedical image processing. What's the best way to get up to speed with the basics of image processing in about two months? Or is this impractical?

It's my impression that once I'm good with the basics learning more from other resources would be easier.

答: You cannot learn image processing in two months. Go take a class in a local university's EE department on digital signal processing. That will provide the needed mathematical background and will perhaps touch on image processing as well.</p>


问:
How to protect a peer-to-peer network from inappropriate content?
I’m developing a simple peer-to-peer app in .Net which should enable users to share specific content (text and picture files). Inappropriate content can “relatively” easily be identified / controlled in a centralized environment. But what about a peer-to-peer network, what are the best methods to protect a decentralized system from unwanted (illegal) content?

At the moment I only see the following two methods:

A protocol (a set of rules) defines what kind of data (e.g. only .txt and jpg-files, not bigger than 20KB etc.) can be shared over the p2p-network and all clients (peers) must implement this protocol. If a peer doesn’t, it gets blocked by other peers. Pro: easy to implement. Con: It’s not possible to define the perfect protocol (I think eMail-Spam filters have the same problem)

Some kind of rating/reputation system must be implemented (similar to stackoverflow), so “bad guys” and inappropriate content can be identified / blocked by other users. Pro: Would be very accurate. Con: Would be slow and in my view technically very hard to implement.

Are there other/better solutions?

答:
peer-to-peer app

Apps are legal in the same sense that browsers are legal. Legal issues relate to trackers and distributing torrents. If you're only developing the app, not the tracker then you shouldn't be too concerned.

only .txt and jpg-files, not bigger than 20KB etc.

Why do you need p2p for 20KB files? If I need to upload an image then I use a site like imgur. If I need to upload a text file then I use something like pastebin. I don't see any benefit to this when .torrent files their self can be 20KB.

Anyway, I think the best solution is to have moderators and prohibit illegal file sharing. Pirates (and friends) will take note and move to a different site if they see their uploads being removed.


问:
Best Practices for Handing over Legacy Code
In a couple of months a colleague will be moving on to a new project and I will be inheriting one of his projects. To prepare, I have already ordered Michael Feathers' Working Effectively with Legacy Code.

But this books as well as most questions on legacy code I found so far are concerned with the case of inheriting code as-is. But in this case I actually have access to the original developer and we do have some time for an orderly hand-over.

Some background on the piece of code I will be inheriting:

It's functioning: There are no known bugs, but as performance requirements keep going up, some optimizations will become necessary in the not too distant future.

Undocumented: There is pretty much zero documentation at the method and class level. What the code is supposed to do at a higher level, though, is well-understood, because I have been writing against its API (as a black-box) for years.

Only higher-level integration tests: There are only integration tests testing proper interaction with other components via the API (again, black-box).

Very low-level, optimized for speed: Because this code is central to an entire system of applications, a lot of it has been optimized several times over the years and is extremely low-level (one part has its own memory manager for certain structs/records).

Concurrent and lock-free: While I am very familiar with concurrent and lock-free programming and have actually contributed a few pieces to this code, this adds another layer of complexity.

Large codebase: This particular project is more than ten thousand lines of code, so there is no way I will be able to have everything explained to me.

Written in Delphi: I'm just going to put this out there, although I don't believe the language to be germane to the question, as I believe this type of problem to be language-agnostic.

I was wondering how the time until his departure would best be spent. Here are a couple of ideas:

Get everything to build on my machine: Even though everything should be checked into source code control, who hasn't forgotten to check in a file once in a while, so this should probably be the first order of business.

More tests: While I would like more class-level unit tests so that when I will be making changes, any bugs I introduce can be caught early on, the code as it is now is not testable (huge classes, long methods, too many mutual dependencies).

What to document: I think for starters it would be best to focus documentation on those areas in the code that would otherwise be difficult to understand e.g. because of their low-level/highly optimized nature. I am afraid there are a couple of things in there that might look ugly and in need of refactoring/rewriting, but are actually optimizations that have been out in there for a good reason that I might miss (cf. Joel Spolsky, Things You Should Never Do, Part I)

How to document: I think some class diagrams of the architecture and sequence diagrams of critical functions accompanied by some prose would be best.

Who to document: I was wondering what would be better, to have him write the documentation or have him explain it to me, so I can write the documentation. I am afraid, that things that are obvious to him but not me would otherwise not be covered properly.

Refactoring using pair-programming: This might not be possible to do due to time constraints, but maybe I could refactor some of his code to make it more maintainable while he was still around to provide input on why things are the way they are.

Please comment on and add to this. Since there isn't enough time to do all of this, I am particularly interested in how you would prioritize.

Update: As the hand-over project is over I have expanded this list with my own experiences in this answer below.

答:
I suggest the following (in addition to what is already identified) - First, ask your manager to give you time to work with this guy as much as possible and try to sit with him whenever he is tasked of doing a change. You don't have to know everything he is doing but try to catch as much as you can. Most important be friends with him.

Treat the hand-over as a project and put a plan in place and involve the management.

0 - Make sure you know how to use the system.

1 - Make a clear inventory of the solution components, the source of each and where it lies (in diff. repositories)

2 - Get and if possible, manage, the passwords for the different servers starting now. Make sure you have all the admin account information

3 - Get the licenses of each external component unless its outside your scope (e.g. special dlls, database, etc.)

4 - Get a written report about the current status of the system from the developer and your customers (if they are local to your company)

5 - Get the documentation for the business rules, calculation formulas, etc. You can do this with him. Ask him for emails, meetings information, user requirement documents, design documents and the like to be given to you.

6 - Get a list of scheduled events (monthly runs of jobs, weekly runs of jobs) that the software has to respond to

7 - Learn the backup/restore procedures

8 - Understand the framework(s) used in building the application

9 - Get to the know the requested/expected/planned modifications and the status of any pending user requests. Begin trying to identify how to do those on your own.

10 - Make sure your test and development environments are very similar.

11 - Try to identify major dependencies (on other systems or between components) that can't be easily spotted.

12 - Identify and document the required versions of each software use and its vendor contact (if necessary)

13 - Identify any special tools he was using that you don't have, in case it could help you.

14 - Get a high level system flow. and start building your documentation library

15 - Understand how to manage user security for the application

16 - Get the bug log and try to understand the actions and how the action affected older data (if applicable)

17 - Know processes that takes too long and what do you need to watch for (e.g. unusual file sizes, ftp of duplicate files, etc.) where applicable.

18 - Check the production server clock

19 - Identify where the configurations are and compare each environment configuration with the production to know what parameters are different and why

20 - Get this guy's contact information

21 - If the system is internal, schedule a a meeting with the system users (you need to know who they are and what the role each plays) and be introduced to them. Listen to what they have to say about the system and about their current problems if any. Make sure you are included in emails as early as possible (after your manager's approval)

22 - Assess your understanding 1 week before he leaves and report any problems you see as a risk

Since you mentioned you don't have a database, this list got shorter.

Good luck.

OwnerDisplayName: PersonalNexus


答:
Is like the Chicken or the Egg problem.

There are many cases in which circular reference are inevitable and are useful but, for example, in the following case it doesn't work:

Project A depends on project B and B depends on A. A needs to be compiled to be used in B which requires B to be compiled before A which requires B to be compiled before A which ...

Title: What's wrong with circular references?

Body:
I was involved in a programming discussion today where I made some statements that basically assumed axiomatically that circular references (between modules, classes, whatever) are generally bad.  Once I got through with my pitch, my coworker asked, "what's wrong with circular references?"

I've got strong feelings on this, but it's hard for me to verbalize concisely and concretely.  Any explanation that I may come up with tends to rely on other items that I too consider axioms ("can't use in isolation, so can't test", "unknown/undefined behavior as state mutates in the participating objects", etc.), but I'd love to hear a concise reason for why circular references are bad that don't take the kinds of leaps of faith that my own brain does, having spent many hours over the years untangling them to understand, fix, and extend various bits of code.

Edit: I am not asking about homogenous circular references, like those in a doubly-linked list or pointer-to-parent.  This question is really asking about "larger scope" circular references, like libA calling libB which calls back to libA.  Substitute 'module' for 'lib' if you like.  Thanks for all of the answers so far!


问:
Is the capability to overwrite functions in JavaScript strength or weakness?
I recently came across the following code (from liferay.js) when I was working with Liferay:

```<code>....
if (!Liferay._ajaxOld) {
    Liferay._ajaxOld = jQuery.ajax;
}

if (Liferay._ajaxOld) {
    jQuery.ajax = function(options) {
        if (Liferay.Util) {
            options.url = Liferay.Util.getURLWithSessionId(options.url);
        }
        return Liferay._ajaxOld(options);
    };
}
....
</code>```

As you can see, the code above overwrites the function "jQuery.ajax" to modify "options.url". One may say this is a strength of the language since we can easily overwrite and customize existing functions.

However, I would imagine this capability can easily lead to a problem. For instance, my code can overwrite the same function "jQuery.ajax" to modify "options.url" differently from the code above. As a result, any code that expect the behavior defined by "liferay.js" may no longer function as expected.

I see this as a weakness of the language as it does not provide proper encapsulation.
What are the consensus about this feature/capability of the language in the field?

答:
I think it really depends on who you ask.  Javascript is by no means a perfect language, but just like abstraction of private variables, this may be a good or bad thing depending on the situtation.

If you're using a library and want to overwrite a function, then it's a good thing, if you're the author of a library or function, and someone uses your code in a way you do not intend, then it is not.

OwnerDisplayName: GrailsDev


答: Like many powerful language-features, it's a double edged sword. It both can be very useful (see aspect-oriented programming) and lead to subtle bugs.</p>

Title: Is the capability to overwrite functions in JavaScript strength or weakness?

Body:
I recently came across the following code (from liferay.js) when I was working with Liferay:

```<code>....
if (!Liferay._ajaxOld) {
    Liferay._ajaxOld = jQuery.ajax;
}

if (Liferay._ajaxOld) {
    jQuery.ajax = function(options) {
        if (Liferay.Util) {
            options.url = Liferay.Util.getURLWithSessionId(options.url);
        }
        return Liferay._ajaxOld(options);
    };
}
....
</code>```

As you can see, the code above overwrites the function "jQuery.ajax" to modify "options.url". One may say this is a strength of the language since we can easily overwrite and customize existing functions.

However, I would imagine this capability can easily lead to a problem. For instance, my code can overwrite the same function "jQuery.ajax" to modify "options.url" differently from the code above. As a result, any code that expect the behavior defined by "liferay.js" may no longer function as expected.

I see this as a weakness of the language as it does not provide proper encapsulation.
What are the consensus about this feature/capability of the language in the field?

OwnerDisplayName: outis


答:
It's a strength. If you are modifying an existing function then you know what that modified function does and you know to use it differently than the spec and not to follow with code that uses the old spec.

It's not like it overwrites the function in the interpreter itself so other web pages will use the modified spec.

One advantage to this is you can fix minor bugs in a library that exists on a CDN without needing to keep and serve an entire copy of the library local.

One place where this may be of benefit is with Content Security Policy (CSP) environments. Since jQuery animations often use the style attribute which may be forbidden in a CSP environment, you may want to rewrite some of jQueries functions to point to an external CSS3 sheet and assign class attributes instead. Thus you could keep using jQuery with the huge library hosted on the CDN, have a small js locally hosted that redefines the jQuery functions that violate your CSP in a way that does not violate your CSP, and use packaged widgets that call those functions without needing to modify the packaged widgets.

OwnerDisplayName: Alice Wonder


答:
If looking for the basics, I learned via the PBM/Netpbm programs.  It is a rudimentary way to very clearly define an arbitrary-depth image (in ASCII format) and process not just with provided libraries and utilities, but also you can very easily process with your favorite program or shell.

I even used this during several projects at Uni doing remote sensing and calibrating these raster images.  My code was not the fastest, but it did run correctly and programmed all in AWK ;)  Point is, once you understand your data, you can do almost anything.  Might be a good start there.

Title: What's the best way to learn image processing?

Body:
I'm a senior in college that hasn't done much image processing before (except for some basic image compression on smartphones). I'm starting a research project on machine learning next semester that would require some biomedical image processing. What's the best way to get up to speed with the basics of image processing in about two months? Or is this impractical?

It's my impression that once I'm good with the basics learning more from other resources would be easier.


问:
When following SRP, how should I deal with validating and saving entities?
I've been reading Clean Code and various online articles about SOLID lately, and the more I read about it, the more I feel like I don't know anything.

Let's say I'm building a web application using ASP.NET MVC 3. Let's say I have a UsersController with a Create action like this:

```<code>public class UsersController : Controller
{
    public ActionResult Create(CreateUserViewModel viewModel)
    {

    }
}
</code>```

In that action method I want to save a user to the database if the data that was entered is valid.

Now, according to the Single Responsibility Principle an object should have a single responsibility, and that responsibility should be entirely encapsulated by the class. All its services should be narrowly aligned with that responsibility. Since validation and saving to the database are two separate responsibilities, I guess I should create to separate class to handle them like this:

```<code>public class UsersController : Controller
{
    private ICreateUserValidator validator;
    private IUserService service;

    public UsersController(ICreateUserValidator validator, IUserService service)
    {
        this.validator = validator;
        this.service= service;
    }

    public ActionResult Create(CreateUserViewModel viewModel)
    {
        ValidationResult result = validator.IsValid(viewModel);

        if (result.IsValid)
        {
            service.CreateUser(viewModel);
            return RedirectToAction("Index");
        }
        else
        {
            foreach (var errorMessage in result.ErrorMessages)
            {
                ModelState.AddModelError(String.Empty, errorMessage);
            }
            return View(viewModel);
        }
    }
}
</code>```

That makes some sense to me, but I'm not at all sure that this is the right way to handle things like this. It is for example entirely possible to pass an invalid instance of CreateUserViewModel to the IUserService class. I know I could use the built in DataAnnotations, but what when they aren't enough? Image that my ICreateUserValidator checks the database to see if there already is another user with the same name...

Another option is to let the IUserService take care of the validation like this:

```<code>public class UserService : IUserService
{
    private ICreateUserValidator validator;

    public UserService(ICreateUserValidator validator)
    {
        this.validator = validator;
    }

    public ValidationResult CreateUser(CreateUserViewModel viewModel)
    {
        var result = validator.IsValid(viewModel);

        if (result.IsValid)
        {
            // Save the user
        }

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

But I feel I'm violating the Single Responsibility Principle here.

How should I deal with something like this?

答:
I really don't think you are violating Single-Responsibility-Principle in your second example.

The UserService class has only one reason to change: if there is a need to change the way you save a user.

The ICreateUserValidator class has only one reason to change: if there is a need to change the way you validate a user.

I must admit that your first implementation is more intuitive. However, the validation should be done by the entity that creates the user. The creator itself shouldn't be responsible for validation; it should rather delegate the responsibility to a validator class (as in your second implementation). So, I don't think the second design lacks SRP.


答: check out freenet. They deal with it another way: everything is encrypted, so you cannot know what's on you machine, even if you put it there yourself, since it may be stored elsewhere.</p>

Title: How to protect a peer-to-peer network from inappropriate content?

Body:
I’m developing a simple peer-to-peer app in .Net which should enable users to share specific content (text and picture files). Inappropriate content can “relatively” easily be identified / controlled in a centralized environment. But what about a peer-to-peer network, what are the best methods to protect a decentralized system from unwanted (illegal) content?

At the moment I only see the following two methods:

A protocol (a set of rules) defines what kind of data (e.g. only .txt and jpg-files, not bigger than 20KB etc.) can be shared over the p2p-network and all clients (peers) must implement this protocol. If a peer doesn’t, it gets blocked by other peers. Pro: easy to implement. Con: It’s not possible to define the perfect protocol (I think eMail-Spam filters have the same problem)

Some kind of rating/reputation system must be implemented (similar to stackoverflow), so “bad guys” and inappropriate content can be identified / blocked by other users. Pro: Would be very accurate. Con: Would be slow and in my view technically very hard to implement.

Are there other/better solutions?


问:
How do I do TDD on embedded devices?
I'm not new to programming and I've even worked with some low level C and ASM on AVR, but I really can't get my head around a larger-scale embedded C project.

Being degenerated by the Ruby's philosophy of TDD/BDD, I'm unable to understand how people write and test code like this. I'm not saying it's a bad code, I just don't understand how this can work.

I wanted to get more into some low level programming, but I really have no idea how to approach this, since it looks like a completely different mindset that I'm used to. I don't have trouble understanding pointer arithmetics, or how allocating memory works, but when I see how complex C/C++ code looks compared to Ruby, it just seems impossibly hard.

Since I already ordered myself an Arduino board, I'd love to get more into some low level C and really understand how to do things properly, but it seems like none of the rules of high level languages apply.

Is it even possible to do TDD on embedded devices or when developing drivers or things like custom bootloader, etc.?

答:
First off, you should know that trying to understand code you didn't write is 5x harder than writing it yourself. You can learn C by reading production code, but it's going to take a lot longer than learning by doing.

Being degenerated by the Ruby's philosophy of TDD/BDD, I'm unable to understand how people write and test code like this. I'm not saying it's a bad code, I just don't understand how this can work.

It's a skill; you get better at it. Most C programmers don't understand how people use Ruby, but that doesn't mean they can't.

Is it even possible to do TDD on embedded devices or when developing drivers or things like custom bootloader, etc.?

Well, there are books on the subject:

 If a bumblebee can do it, you can too!

Keep in mind that applying practices from other languages usually doesn't work. TDD is pretty universal though.

OwnerDisplayName: Darth

Title: How do I do TDD on embedded devices?


问:
I need a public cryptography system that works on small keys
I just need it to support signing and signature verification. I need it to have public and private keys that fit each in 16 bytes. The signature itself must fit 16 bytes.

I don't really care about cryptographic strength, as this is part of something bigger.

Is there such a thing?

答:
No more than 128 bits for the public key, the private key and the signature: that's hard requirements; the harder being on the signature size.

If you use ECDSA, you could work over a 128-bit curve. A public key can fit in about 129 bits; you can omit one bit (this just means that whoever verifies signatures must "guess" the missing bit, i.e. try two possible public keys; if one matches the signature, that's ok). The private key would use 128 bits, still on par with your requirements. Security would be up to 264 curve operation, something which is technologically feasible but not easily (a distributed computation for breaking a 128-bit curve has begun; it involves quite a lot of Universities and it is expected to take about 10 years -- that's what I mean by "not easy"). But the signature size would be 256 bits (two 128-bit integers), twice your requirement. So ECDSA does not work for you.

If you look at research papers, you may find the BLS scheme. To match the requirements, you would have to use a 128-bit curve with a supersingular curve (mathematically, you need both the public key and the signatures to be in the curve on the base field, not the field extension, so this implies use of a distortion map). To get at least some security (something no more than barely crackable), the embedding degree should be at least 6, and you want to avoid fields of characteristic 2, so you'll need to implement computations in a field of characteristic 3. There is no published standard, only shards of high mathematical knowledge scattered over dozens of article of only relative readability. If you understood any of that paragraph, then you have already lost your sanity, probably where I mislaid mine.

Summary: there is no known digital signature algorithm which both fits your requirements and is reasonable to use. There may be one in the future, when current research on pairings stabilizes. But it will not be easy to implement.


问:
Is a MSDN subsciption worthwhile for personal use?
I code primarily in .net at work, but was wondering if home MSDN subscriptions were available/worthwhile as a tool to stay in touch with the latest technology for Microsoft development?</p>

答: By the way, I seem to remember that MSDN subscriptions are personal, i.e. if they got one for you at work you can use it at home as well.</p>


问:
Headaches using distributed version control for traditional teams?
Though I use and like DVCS for my personal projects, and can totally see how it makes managing contributions to your project from others easier (e.g. your typical Github scenario), it seems like for a "traditional" team there could be some problems over the centralized approach employed by solutions like TFS, Perforce, etc. (By "traditional" I mean a team of developers in an office working on one project that no one person "owns", with potentially everyone touching the same code.)

A couple of these problems I've foreseen on my own, but please chime in with other considerations.

In a traditional system, when you try to check your change in to the server, if someone else has previously checked in a conflicting change then you are forced to merge before you can check yours in. In the DVCS model, each developer checks in their changes locally and at some point pushes to some other repo. That repo then has a branch of that file that 2 people changed. It seems that now someone must be put in charge of dealing with that situation. A designated person on the team might not have sufficient knowledge of the entire codebase to be able to handle merging all conflicts. So now an extra step has been added where someone has to approach one of those developers, tell him to pull and do the merge and then push again (or you have to build an infrastructure that automates that task).

Furthermore, since DVCS tends to make working locally so convenient, it is probable that developers could accumulate a few changes in their local repos before pushing, making such conflicts more common and more complicated.

Obviously if everyone on the team only works on different areas of the code, this isn't an issue. But I'm curious about the case where everyone is working on the same code. It seems like the centralized model forces conflicts to be dealt with quickly and frequently, minimizing the need to do large, painful merges or have anyone "police" the main repo.

So for those of you who do use a DVCS with your team in your office, how do you handle such cases? Do you find your daily (or more likely, weekly) workflow affected negatively? Are there any other considerations I should be aware of before recommending a DVCS at my workplace?

答:
We've been using Mercurial for about a year. While the headache you mention exists, by far, the biggest challenge to full adoption for us was getting into the DVCS mindset of local repositories (= commit often.) The old mindset of "Commit once you have polished code" can be hard to let go.

You said:

In the DVCS model, each developer checks in their changes locally and at some point pushes to some other repo. That repo then has a branch of that file that 2 people changed. It seems that now someone must be put in charge of dealing with that situation.

A default install of Mercurial blocks this behavior. It won't allow a push if more than one head will be created in the remote repo, without extra confirmation. For daily activities, we avoid that. (Git has named heads and each can only be updated if it fully merges the previous version, without extra confirmation, so again the situation cannot arise. The other DVCS have similar protection too.)

So at the end of each working day, some time needs to be set aside for the commit, which is really these activities:

Commit local changes.

Pull from central repo.

Merge (& commit merge.)

Push to central repo.

This keeps the merge activity on a person who was recently working on this code, and should be able to integrate their changes as quickly as anyone else.

As pointed out in the question, this really only adds effort when two people are working on the same area of code. If that's the case, then there are more benefits to using DVCS anyway, so the payoff is already evident to those developers. (Additional benefits include each developer being able to separately commit code and play with their own repo without another developer getting in the way. )

Another issue you mention:

Furthermore, since DVCS tends to make working locally so convenient, it is probable that developers could accumulate a few changes in their local repos before pushing, making such conflicts more common and more complicated.

This doesn't create a merge issue for us, but could create a different issue:

The flexibility of DVCS means that many different workflows are possible, but some of those are irresponsible. With DVCS, the need for clear process or procedures increases. The activity of keeping local changes may or may not be appropriate, depending on many things.

For example: can a developer work on a pet feature in spare time over a few weeks? In some environments this is encouraged, in some this would be inappropriate and all changes should be centralized soon. But if a dev is keeping changes locally, then they will certainly want to pull any related changes to make sure their work will continue to play nicely with the latest common rev.

When the rubber meets the road, the software releases or deployments usually come from a central repo, so developers need to get their changes there for testing and deployment.

That's my story, and I'm sticking to it, for at least a couple minutes...


问:
My university doesn't provide php courses because it is an "easy" programming language?
I've met a student from the computer science department and I discovered that they only teach java and aspx. I asked him why they didn't teach php since it is the top one programming language on the net. He says that it was a "easy" (or hobbyist's) programming language. I'm not sure what that means.

What's your opinion?

答:
Note: I’m ultra busy and so I haven’t read all the other responses, so I hope I am not repeating ideas.

I am almost tempted to say that I agree with the spirit of what was said, but I would not put my name to the characterization that your professor/teacher gave.

It’s incontestable that PHP is an extremely popular programming language. That said, I would still count it among “domain-specific” programming languages, and if I were trying to convey more transcendental (sorry!—background in philosophy here) concepts, I wouldn’t use PHP. PHP is among the so-called ”Turing-complete” programming languages (i.e., it’s not AppleScript—it’s suitable for any programming problem), but I think it has so much Web-specific design (just think of the PHP prolog and how XML-influenced it is) that it could distract from the core programming discipline.

PHP isn’t a hobbyist programming language: many professionals use it. In fact, I’d say Python 3 is more of a “hobbyist” language than PHP. That just sounds like a rather humbug cackle from the ivory tower rather than a statement about reality.

And as for the “easy” part. Boy, I am really beginning to dislike your teacher. Programming shouldn’t be needlessly byzantine or difficult. A good language is one that lets you present your ideas clearly, not cryptically. I don’t find PHP easy; in the sense that I do not find it easy to formulate even semi-difficult ideas with anything approximating clarity. I find it much easier to do this in, let’s say Python, or C with Literate Programming.

Summary: PHP is popular, but not exactly elegant for treating the core of computer science. Your teacher sounds like a dbag.


答:
Code that has a long history of incremental development and optimizations for multiple platforms, such as the examples you picked, is usually harder to read.

The thing about C is that it is actually capable of spanning platforms over a massive range of API richness and hardware performance (and lack thereof).  MacVim ran responsively on machines with over 1000X less memory and processor performance than a typical smartphone today.  Can your Ruby code?  That's one of the reasons it might look simpler than the mature C examples you picked.

Title: How do I do TDD on embedded devices?

Body:
I'm not new to programming and I've even worked with some low level C and ASM on AVR, but I really can't get my head around a larger-scale embedded C project.

Being degenerated by the Ruby's philosophy of TDD/BDD, I'm unable to understand how people write and test code like this. I'm not saying it's a bad code, I just don't understand how this can work.

I wanted to get more into some low level programming, but I really have no idea how to approach this, since it looks like a completely different mindset that I'm used to. I don't have trouble understanding pointer arithmetics, or how allocating memory works, but when I see how complex C/C++ code looks compared to Ruby, it just seems impossibly hard.

Since I already ordered myself an Arduino board, I'd love to get more into some low level C and really understand how to do things properly, but it seems like none of the rules of high level languages apply.

Is it even possible to do TDD on embedded devices or when developing drivers or things like custom bootloader, etc.?


问:
How was Git designed?
My workplace recently switched to Git and I've been loving (and hating!) it. I really do love it, and it is extremely powerful. The only part I hate is that sometimes it's too powerful (and maybe a bit terse/confusing).

My question is... How was Git designed? Just using it for a short amount of time, you get the feel that it can handle many obscure workflows that other version control systems could not. But it also feels elegant underneath. And fast!

This is no doubt in part to Linus's talent. But I'm wondering, was the overall design of git based off of something? I've read about BitKeeper but the accounts are scant on technical details. The compression, the graphs, getting rid of revision numbers, emphasizing branching, stashing, remotes... Where did it all come from?

Linus really knocked this one out of the park and on pretty much the first try! It's quite good to use once you're past the learning curve.

答:
I think the main point is simply that git was designed by the single most qualified person on the planet to do so. And I am not talking about talent, I am talking about experience: I doubt there is anyone else who's been in charge of a codebase with a comparable combination of size and number of contributors as the Linux kernel and still actually dealing with most of the integration work himself.

So Linus knew the requirements and use cases for a distributed version control system better than anyone else. And of course it helped that most of that coding he was dealing was in C, and much of it performance critical.

Basically it's the ultimate example of scratching one's own itch.

Title: How was Git designed?


答:
It was designed pretty much exactly as described in The Git Parable.

Imagine that you have a computer that has nothing on it but a text editor and a few file system commands. Now imagine that you have decided to write a large software program on this system. Because you’re a responsible software developer, you decide that you need to invent some sort of method for keeping track of versions of your software so that you can retrieve code that you previously changed or deleted. What follows is a story about how you might design one such version control system (VCS) and the reasoning behind those design choices.

Title: How was Git designed?

Body:
My workplace recently switched to Git and I've been loving (and hating!) it. I really do love it, and it is extremely powerful. The only part I hate is that sometimes it's too powerful (and maybe a bit terse/confusing).

My question is... How was Git designed? Just using it for a short amount of time, you get the feel that it can handle many obscure workflows that other version control systems could not. But it also feels elegant underneath. And fast!

This is no doubt in part to Linus's talent. But I'm wondering, was the overall design of git based off of something? I've read about BitKeeper but the accounts are scant on technical details. The compression, the graphs, getting rid of revision numbers, emphasizing branching, stashing, remotes... Where did it all come from?

Linus really knocked this one out of the park and on pretty much the first try! It's quite good to use once you're past the learning curve.


问:
Recommend Stanford Online Database Class?
I am taking the Stanford Online Machine Learning class which is outstanding. http://ml-class.org

Is anyone taking the Stanford Online Database class: http://www.db-class.org? Does it seem useful if you have a few years of fairly simple database experience, but no formal education in the area? Or is it mostly academic and not relevant to developing and maintaining databases in the "real world"?

答:
I can only speak to the usefulness of the Database class that I took (which is likely very similar to what Stanford offers).

My advice: TAKE IT.

Modern relational database management systems (RDBMS's) are based heavily on the relational database model. If you're not sure why those two are different, then that is reason #1 to take the class.

Reason #2 is based on the idea that not all experience is equal. I know people who have been working with databases for over 10 years who have no idea what "many-to-many" means and will create terrible table schemas, completely unaware that what they are creating is difficult to understand and maintain.

RDBMS's are unique in that they maintain a very close relationship to theory (unlike many other CS topics), and thus you will notice a huge gap between those who understand the theory and those who do not.

By taking the class, you will understand how databases work in theory, and will be MUCH better suited to apply those ideas in the real world.

Trust me--if you take the class, you will not be disappointed.


答:
I am taking the online ai-class from Standford, and totally recomend it. The professoers are really good, and the course gives you a good "broad" view of the whole topic.

Myself take a look at the db-class and intending to do it after I finish the ai one.

Title: Recommend Stanford Online Database Class?

Body:
I am taking the Stanford Online Machine Learning class which is outstanding. http://ml-class.org

Is anyone taking the Stanford Online Database class: http://www.db-class.org? Does it seem useful if you have a few years of fairly simple database experience, but no formal education in the area? Or is it mostly academic and not relevant to developing and maintaining databases in the "real world"?


问:
What is the market share of programs written in .NET nowadays?
We are currently migrating our Visual Basic 6.0 program to .NET. The target audience are just normal desktop users at home. Discussing this, we realized that we cannot come up with mainstream programs that seem to be written in .NET. Are we mistaken? Is there a good reason for this?</p>

答:
I suppose it doesn't matter - what might matter more is what will the majority of programs be written in, in the future. Now MS are focussing on Win8 apps, you'd possibly be better off worrying about the adoption of HTML5+js and WinRT rather than legacy .NET.

Last thing you want to do is port everything to .NET and then have to do a lot more rework to make it work well with Windows 8.


问:
Is it possible to effectively develop PHP applications on Windows that will be deployed on servers running Linux?
Is it fine to code PHP on Windows and host it later on a server running Linux? Can there be any problems in the migration of such a project?

I would think that there really can't be any problems, especially since I am a beginner in PHP and I won't use any of the advanced functions that may be OS-specific. However, I would like to make sure since I really don't like Linux at all.

答:
There won't be any problems running the code.
If you do edit the files saved on Windows in Linux you might notice that the end of line characters might be different but it won't hurt anything.
If it does bother you configure your windows IDE/editor to use Unix end of line.</p>


答:
I'm in the reverse position of having spent most of the last 9 years as a C programmer, and recently working on some Ruby on Rails front-ends.

The stuff I work on in C is mostly medium sized custom systems for controlling automated warehouses (typical cost of a few hundred thousand pounds, upto a couple of million).  Example functionality is a custom in-memory database, interfacing to machinery with some short response-time requirements and higher level management of warehouse workflow.

I can say first of all, we don't do any TDD.  I've tried on a number of occasions introducing unit tests, but in C it is more trouble than it's worth - at least when developing custom software.  But I would say TDD is far less needed in C than Ruby.  Mainly, that is just because C is compiled, and if it compiles without warnings, you've already done a fairly similar amount of testing to the rspec auto-generated scaffolding tests in Rails.  Ruby without unit tests is not feasible.

But what I would say is that C doesn't have to be as hard as some people make it.  Much of the C standard library is a mess of incomprehensible function names and lots of C programs follow this convention.  I'm glad to say we don't, and in fact have a lot of wrappers for standard library functionality (ST_Copy instead of strncpy, ST_PatternMatch instead of regcomp/regexec, CHARSET_Convert instead of iconv_open/iconv/iconv_close and so on).  Our in-house C code reads better to me than most other stuff I've read.

But when you say rules from other higher level languages don't seem to apply, I would disagree.  A lot of good C code 'feels' object oriented.  You often see a pattern of initialising a handle to a resource, calling some functions passing the handle as an argument, and eventually releasing the resource.  Indeed, the design principles of object oriented programming largely came from the good things people were doing in procedural languages.

The times when C gets really complicated are often when doing things like device drivers and OS kernels which are just fundamentally very low-level.  When you're writing a higher level system, you can also use the higher level features of C and avoid the low level complexity.

One very interesting thing you may want to have a look through is the C source-code for Ruby.  In the Ruby API docs (http://www.ruby-doc.org/core-1.9.3/) you can click and see the source code for the various methods.  The interesting thing is this code looks quite nice and elegant - it doesn't look as complex as you might imagine.

Title: How do I do TDD on embedded devices?


问:
Any experience with Mono on production servers?
I am curios to use .NET for some web applications (e.g. ASP.NET MVC 2). However my budget is limited so I would like to use Mono on Linux. I have never used Mono before, and I haven't read about any bigger sites that is using Mono+Linux on the server in production.

What's your experience using Mono on Linux in production? How is the performance and stability compared to .NET on Windows Server?

Is there any popular sites that is using it in production? Any articles available online were they share their experiences?

答:
I've been doing some mono mvc stuff on my mac (unix not linux) in the recent weeks and have found mono combined with monodevelop to be a pretty featured and useful environment.

So far in a few prototype sites I haven't yet ran into any deal breakers or major issues.

In the next few weeks I'll be deploying some sites to linux vps servers. So I'll comment on my experience.

[Update]

So this answer was a long time ago and it's taken me a while to get some stuff up and running.

So my experience: mono-2.10.1 or higher is feature complete for asp.net mvc2 (mono-2.8 had some bugs that required a source compile) and it's now being used by a few cloud providers.

Running on mono-2.8 http://srvd.in/

AppHarbor: http://unwind.apphb.com/

DeployFu: http://unwind.deployfu.com/

I've found it stable and easy to develop with, like I said there were 2 annoying bugs in the 2.8 version but they are fixed in 2.10.1.

I'm happy to elaborate based on comments.

[Update] I've blogged here about deploying mono + xsp4 + nginx: http://www.thomasvjames.com/2012/07/asp-net-4-on-mono-part-2-automating-deployment/


答:
Some pointers:

Filesystem case sensitivity

If your file is called HelloWorld.php this:

```<code>include "helloworld.php";
</code>```

is legit on Windows and will work. But Linux filenames are case sensitive, you can have files called HelloWorld.php, helloworld.php, hEllOwOrlD.php in the same directory. So you should develop on Windows as if you were developing on a case sensitive filesystem: use exactly the correct filenames, directory names, extension names - .php is also different from .PHP.

Directory and path separators

In Windows we say:

```<code>include 'classes\myClass.php';
</code>```

But in Linux we would say:

```<code>include 'classes/myClass.php';
</code>```

PHP is smart enough to not care, both separators work in both systems. But you should be consistent and go with the slash (/) everywhere as it's also the norm on most systems. There is a nifty predefined constant DIRECTORY_SEPARATOR that translates to the correct one, if you want to go that far:

```<code>include "classes" . DIRECTORY_SEPARATOR . "myClass.php";
</code>```

The same goes for the path separator, which is semicolon on Windows, colon otherwise. So to be safe you should do:

```<code>set_include_path(get_include_path() . PATH_SEPARATOR . $path);
</code>```

when in need of a path separator. Although most people think that since PHP doesn't mind which separator you use it's ok, but there is one important catch: The separators will be the system specific ones when you ask the system for directories or paths. So let's say you want to explode the include path into its parts:

```<code>$includePath = get_include_path();

$pathParts = explode(";", $includePath) // Will only work on Windows
$pathParts = explode(":", $includePath) // Will work on other systems but not Windows
$pathParts = explode(PATH_SEPARATOR, $includePath) // Will work everywhere!!!
</code>```

File encoding and delimiter

You should set your IDE to set file encoding for all your scripts to UTF-8 instead of Cp*, and the file line delimiter to Unix ("\n" instead of "\r\n"). In most cases it won't really matter but you should be consistent and the best way is the Unix way (which works fine on Windows but not vice versa).

Title: Is it possible to effectively develop PHP applications on Windows that will be deployed on servers running Linux?

Body:
Is it fine to code PHP on Windows and host it later on a server running Linux? Can there be any problems in the migration of such a project?

I would think that there really can't be any problems, especially since I am a beginner in PHP and I won't use any of the advanced functions that may be OS-specific. However, I would like to make sure since I really don't like Linux at all.

Body:
Some pointers:

Filesystem case sensitivity

If your file is called HelloWorld.php this:

include "helloworld.php";

is legit on Windows and will work. But Linux filenames are case sensitive, you can have files called HelloWorld.php, helloworld.php, hEllOwOrlD.php in the same directory. So you should develop on Windows as if you were developing on a case sensitive filesystem: use exactly the correct filenames, directory names, extension names - .php is also different from .PHP.

Directory and path separators

In Windows we say:

include 'classes\myClass.php';

But in Linux we would say:

include 'classes/myClass.php';

PHP is smart enough to not care, both separators work in both systems. But you should be consistent and go with the slash (/) everywhere as it's also the norm on most systems. There is a nifty predefined constant DIRECTORY_SEPARATOR that translates to the correct one, if you want to go that far:

include "classes" . DIRECTORY_SEPARATOR . "myClass.php";

The same goes for the path separator, which is semicolon on Windows, colon otherwise. So to be safe you should do:

set_include_path(get_include_path() . PATH_SEPARATOR . $path);

when in need of a path separator. Although most people think that since PHP doesn't mind which separator you use it's ok, but there is one important catch: The separators will be the system specific ones when you ask the system for directories or paths. So let's say you want to explode the include path into its parts:

$includePath = get_include_path();

$pathParts = explode(";", $includePath) // Will only work on Windows
$pathParts = explode(":", $includePath) // Will work on other systems but not Windows
$pathParts = explode(PATH_SEPARATOR, $includePath) // Will work everywhere!!!

File encoding and delimiter

You should set your IDE to set file encoding for all your scripts to UTF-8 instead of Cp*, and the file line delimiter to Unix ("\n" instead of "\r\n"). In most cases it won't really matter but you should be consistent and the best way is the Unix way (which works fine on Windows but not vice versa).


问:
Is "White-Board-Coding" inappropriate during interviews?
This is a somewhat subjective quesiton but I'd love to hear feedback/opinions from either interviewers/interviewees on the topic.

We split our technical interview into 4 parts. Write Code, Read & Analyse Code, Design Session & Code on the white board.

For the last part what we ask interviewees to do is write a small code snippet (4-5 lines) on the whiteboard and explain as they go through it. Let me be clear the purpose is not to catch people out. We're not looking for perfect syntax. Hell it can even be pseudo-code. but the point is to give them a very simple problem and see if their brain can communicate the solution to us. By simple problems I mean "Reverse a string", "FizzBuzz" etc...

Note that we always ask for an explicit language first. We're a .NET C# house. we've only said "pseudo-code" where someone has been blanking/really struggling with the code.

My question is "Is it inappropriate / unreasonable to expect a programmer to write a code snippet on a whiteboard during an interview ?"

答:
These days, a lot of programming is done in teams.  For teams to work, people have to be able to communicate.   A big part of this is being able to communicate in front of a whiteboard (brainstorming, mentoring, code reviews proposed fixes, etc.)

I would look for whether the candidate explained how to go about the solution to a programming problem using whiteboard code to assist.  If the explanation is good enough, the other good programmers in the room will mentally auto-correct any typos/mistakes on the board.

For most types of team positions, it would be unreasonable NOT to expect a candidate to be able to explain and scribble their attempt at a solution.


问:
How to work in localhost properly
I am using MAMP (just and example) to develop web applications without having to constantly upload and download via FTP.

I´m sure this is the correct way to test a project but I´m no sure if I´m doing it right.

After I´m satisfied with the project I have to change in every page the MySQL databases and most of the links etc.

Is there a workaround this? How should this be used?

Thanks in advance!

答:
It's always better to have a common class which contains your database connect, database disconnect and your most used paths like </p>

```<code>$config['base_url'] = 'http://'.$_SERVER['HTTP_HOST'];
$config['base_path']= $_SERVER['DOCUMENT_ROOT'].'/project/';
</code>```

<p>These are very help full. </p>

Title: How to work in localhost properly

Body:
It's always better to have a common class which contains your database connect, database disconnect and your most used paths like

$config['base_url'] = 'http://'.$_SERVER['HTTP_HOST'];
$config['base_path']= $_SERVER['DOCUMENT_ROOT'].'/project/';

These are very help full.


问:
Does the ActiveRecord pattern follow/encourage the SOLID design principles?
I'm interested in whether ActiveRecord pattern, made famous from Ruby on Rails, encourages or discourages the use of SOLID design principles.

For example, it seems to me that ActiveRecord objects both contain domain logic, and persistence logic, which is a violation of Single Responsibility.

答:
There's some valid criticism on ActiveRecord. As always, Uncle Bob sums it up perfectly:

The problem I have with Active Record is that it creates confusion about these two very different styles of programming. A database table is a data structure. It has exposed data and no behavior. But an Active Record appears to be an object. It has “hidden” data, and exposed behavior. I put the word “hidden” in quotes because the data is, in fact, not hidden. Almost all ActiveRecord derivatives export the database columns through accessors and mutators. Indeed, the Active Record is meant to be used like a data structure.

On the other hand, many people put business rule methods in their Active Record classes; which makes them appear to be objects. This leads to a dilemma. On which side of the line does the Active Record really fall? Is it an object? Or is it a data structure?

Wikipedia sums the criticism in a testability concern:

In OOP the concept of encapsulation is often at odds with the concept of separation of concerns. Generally speaking, patterns that favor separation of concerns are more suitable to isolated unit tests while patterns that favor encapsulation have easier to use APIs. Active Record heavily favors encapsulation to the point where testing without a database is quite difficult.

Specifically for the Ruby on Rails implementation, Gavin King writes (emphasis mine):

At this point, most developers are thinking um, ok, so how the hell am I supposed to know what attributes a Company has by looking at my code? And how can my IDE auto-complete them? Of course, the Rails folks have a quick answer to this question Oh, just fire up your database client and look in the database!. Then, assuming that you know ActiveRecord's automagic capitalization and pluralization rules /perfectly/, you will be able to guess the names of the attributes of your own Company class, and type them in manually.

Also on the Ruby on Rails implementation, John Januszczak writes (emphasis mine):

PROBLEM #1: STATIC METHODS

...

Some would say using Static methods simply amounts to procedural programming, and therefore is poor Object Oriented design. Others would say static methods are death to testability.

PROBLEM #2: GLOBAL CONFIGURATION SETTINGS

...

Therefore there is no dependency injection on the Account class in my example, and by extension, on the Account instances.  As we should all know by now, looking for things is very, very bad!

A few more resources on why ActiveRecord and ORM is generally considered to be an anti-pattern:

Rails Domain model decoupling of Activerecord on StackOverflow,

ORM is an anti-pattern

Dirty Associations with ActiveRecord

Issue #23: SOLID Design Principles on Practicing Ruby

ActiveRecord always felt like an extremely useful anti-pattern, but I do agree that it goes against SRP and additionaly that it goes against the dependency inversion principle.


问:
What do you do if you reach a design dead-end in evolutionary methods like Agile or XP?
As I was reading Martin Fowler's famous blog post Is Design Dead?, one of the striking impressions I got is that given the fact that in Agile Methodology and Extreme Programming, the design as well as programming is evolutionary, there are always points where things need to get refactored.

It may be possible that when a programmer's level is good, and they understand design implications and don't make critical mistakes, the code continues to evolve. However, in a normal context, what is the ground reality in this context?

In a normal day given some significant development goes into product, and when critical change occurs in requirement isn't it a constraint that how much ever we wish, fundamental design aspects cannot be modified? (without throwing away major part of the code). Is it not quite likely that one reaches dead-end on any further possible improvement on design and requirements?

I am not advocating any non-Agile practice here, but I want to know from people who practice agile or iterative or evolutionary development methods, as for their real experiences.

Have you ever reached such dead-ends? How have you managed to avoid it or escaped it? Or are there measures to ensure that design remains clean and flexible as it evolves?

答:
About a month or two ago, our current project got a bit stuck due to some bad design decisions (and lack of much design in one place), with the SCRUM development style.

Our solution (and what I believe is the standard one for SCRUM) was to devote an entire sprint (~2 weeks) to nothing but refactoring.  No new functionality was added during this time, but we were able to think about the current codebase, and design a much better system for what we were doing.

We are now past that hurdle, and have been adding in new features again.


答: The key to limiting the cost of design changes is keeping the code as DRY as possible.  This will drive most of the application code to a very high level, where most of the code directly expresses the intention, and relatively little specifies mechanism.  If you do this, then design decisions will have the smallest possible expression in the code, and design changes will have the least possible cost.</p>

Title: What do you do if you reach a design dead-end in evolutionary methods like Agile or XP?

Body:
As I was reading Martin Fowler's famous blog post Is Design Dead?, one of the striking impressions I got is that given the fact that in Agile Methodology and Extreme Programming, the design as well as programming is evolutionary, there are always points where things need to get refactored.

It may be possible that when a programmer's level is good, and they understand design implications and don't make critical mistakes, the code continues to evolve. However, in a normal context, what is the ground reality in this context?

In a normal day given some significant development goes into product, and when critical change occurs in requirement isn't it a constraint that how much ever we wish, fundamental design aspects cannot be modified? (without throwing away major part of the code). Is it not quite likely that one reaches dead-end on any further possible improvement on design and requirements?

I am not advocating any non-Agile practice here, but I want to know from people who practice agile or iterative or evolutionary development methods, as for their real experiences.

Have you ever reached such dead-ends? How have you managed to avoid it or escaped it? Or are there measures to ensure that design remains clean and flexible as it evolves?


答:
I would say the "design dead-end" phenomena is orthogonal to agile methods.  What I mean is that it is possible to do waterfall, spend a lot of time upfront on a (bad) design.  Then spend a lot of time implementing it only to find yourself at a dead end.

If anything, agile methods should help you discover earlier that you made bad design choices.  The reason for this is that your backlog should have the highest customer value items done first and you should focus on delivering useful increments of the software.  If your design allows you to deliver high value and usefulness it's already good for something :-)  In contrast, you could have a bad design in a waterfall-ish situation where you may not find out for many years that this design can't deliver any value and any usefulness - all you have is the illusion of it being a good design.  As they say, the proof is in the pudding.

The flip side is that even in agile methods it is important to have a viable vision for the system's design that drives decisions from iteration to iteration.  I think Ken Schwabber said something like if you have a team of terrible developers they will produce bad software consistently iteration by iteration.  Agile simply means don't spend a lot of time upfront because you are limited in what you can learn or imagine before you start implementing (and the requirements also change).  However, there are some situations where you have to do upfront work (e.g. research) and then you gotta do that.

How do you avoid dead-ends?

I would say mostly by anticipating future requirements.  This is something you get with experience and familiarity with similar projects/products.  This anticipation is partly what helps you put a good design in place because you ask yourself a lot of "what if" questions about your current system.  To me this is the critical component.  Techniques like OO are simply helping you when you already know what you're doing.

What do you do if you have a dead-end?

A "dead-end" is no different than any other technical block you will hit during the development of anything that is novel.  The first thing to realize is that there are really no true "dead-ends" that force you to completely backtrack.  At the very least your learning up to this point is what enables you to go forward so the effort has not been wasted.  When you hit a dead-end you have a problem.  The problem is what needs to change in order to meet some new (or old) requirement and how to optimize making this change.  All you have to do now is solve this problem.  Be thankful that this is software and not, e.g. an airplane design, because change is much easier.  Identify the issues, fix them == refactor == software engineering.  Sometimes a lot of work is involved...

If you use Scrum this change should naturally be driven from user stories (what does the user get from this change?). The process would start from one story which can't easily be accomodated by the current design (oops) and a discussion would happen with the product owner about how to break this story down.  You keep applying agile principles through this change.

A few famous big requirement changes from the OS world that come to my mind:

Apple moving from 68K to PowerPC.

Apple moving from PowerPC to Intel.

Windows needs to run on ARM.

Adding support for symmetric multi-processing to a single processor OS.

Whichever way you look at these they are a lot of work.  The original design almost certainly did not take into account the possibility of this happening (i.e. portaility was not a big requirement).  Whether the design was OO or not is probably not a huge factor either.  In a good design the platform specific portions would be somewhat isolated and the work would be easier.