问:
Plagued by indecision - how to choose technologies to use for projects?
I have always been fascinated with the newest and best technologies available.  I graduate from college this year, and over the course of the past few years, I have spent a lot of time learning new programming languages, web frameworks, Linux distributions, IDEs, etc., in an effort to find the best of each.

I have installed and played around with Ubuntu, Gentoo, Debian, Arch Linux, SUSE, VectorLinux, Puppy Linux, Slackware, and Fedora, I have spend a good amount of time in Vim and Emacs, and have played around with Visual Studio, Eclipse, NetBeans, gedit, and several more obscure ones.

I have played with all sorts of languages - I started with the common ones like C, Java, Visual Basic, but always heard that they were "bad" (for relative definitions of bad). I then discovered the scripting languages and have quite a bit of experience in PHP, Perl, Python, and Ruby. Then I heard that functional languages are where it's at, so I played around with Scheme, Lisp, Haskell, Erlang, and OCaml. I've played around with obscure languages like Forth and J. When I do web development, I go back and forth between frameworks and languages. Should I use plain PHP, Ruby on Rails, Django, CakePHP, CodeIgniter, Yii, Kohana, or make my own?

I have a very broad and shallow knowledge of computer science. As soon as I have learned a useful amount of one technology, I see something else shiny and go after it. My progression often goes like this: "Perl is better than PHP, but wait, Python is better than Perl. Oh, but now I see that Ruby has the power of Perl and it is cooler than Python. Well, now that I have seen a little of Ruby, it is too complicated. Python is cleaner. Oh, but it is too hard to deploy Python, so I should use PHP if I want to do real web development." And so on and so forth.

What  technology should I use for projects? Should I just pick one language/framework/IDE and sort of forget about the other things that are available for a while? I don't have all that much in the way of completed projects, because I never stay with something long enough to finish it.

答:
I tend to agree with Carson. I haven't exposed myself to as many technologies that you have. I did the play-around-with-CMS thing and also PHP vs Python (same reaction: too hard to get going). And the whole time, I get all these ideas bouncing around my head for websites, registering domains, etc.

And I finally realized over the past year that my problem is that none of the actual ideas for projects fully took hold in my "heart". I finally have one, and now I'm looking to nail down what I'm going to use. I think it will be a fairly quick process.

On the bright side, spending so much time dabbling around can only benefit you with a related and useful skillset... unlike careening from unrelated hobby to completely unrelated hobby. ;)

OwnerDisplayName: dingo


问:
Does C99 make the K&R book outdated? If so what to recomend in its place?
C99 has been with us for a while now. It introduces a lot of features that are not in K&Rs The C Programming Language. None of them are particularly radical. However, even small features like being able to intermingle declarations and code change how one organizes code.

While I still consider the K&R book an invaluable reference, and like its writing style, is there a better book that takes into account the C99 standard? I'd buy a third edition of K&R in a heartbeat, but I don't think that is going to happen.

答:
I would still suggest (the ANSIfied second edition of) K&R for anyone who is just learning C and who wants to learn Straight Procedural C (minus objects).  I'd double that recommendation if they intend to be hacking on *NIX kernel code one day as K&R truly has the "Unix Mentality" in a programming book.

Once they've grasped the basics of C syntax and have a reasonable idea of style you can introduce them to other references that talk about the C99 features and explain that it may change the way they organize what they write, but they'll have (generally) good habits from starting out with K&R (like doing declarations up front) and they'll be cognizant of the why behind doing something contrary to those habits -- I think you build better programmers that way.

ContentLicense: CC BY-SA 3.0


问:
Constant database calls or store in objects?
I'm creating a pretty simple database driven application. Whenever I create a db app, I create classes that mimic the data in the db. Is this good practice?

Am I better off making one big call to the database and populating my objects and working with these objects, or should I retrieve data from the db only when needed?

答:
If your domain mimics the basic structure of your database, that's usually considered a good thing; it's easy to trace the retrieval and persistence of data as it moves between the data and domain layers. Population via stored proc or view can obfuscate exactly where a particular field comes from in the data layer.

As far as how often to populate data, that totally depends on your application. The more often you "synchronize" data between your app and the DB, the more up-to-date both sides are, HOWEVER, increasing the frequency of data transfer will increase network traffic and server CPU usage (which may make the DB less available for other demands on it from other apps), and may reduce the amount of work that can be undone (if you write changes to the DB immediately when made, instead of allowing the user to "commit" those changes, they can easily make a mistake that immediately goes to the DB and affects other users).


问:
In a 4 hour Powershell 101 class should I skip for/while/do and just teach ForEach-Object
I'm making a syllabus to teach non-programmer co-workers PowerShell. The first non-pilot group I will run the course with will be a team that deploys and configures one of our software products. They are bright intelligent motivated IT workers, but not programmers.

I intend to cover the basics (variables, arrays, functions, and loops), and then move onto examples that are close to their problem domain. I'm not married to a 4 hour class, if necessary I can expand it to two four hour classes.

I'm toying with the idea of skipping for and while loops and simply teaching ForEach-Object. I've personally used traditional for and while loops in powershell scripts, but they can always be rewritten  as ForEach-Object loops with a bit of creativity. Part of me feels the good old for ($i=0 $i < foo; $i++) is a necessary fundamental before moving onto foreach, but the other part of me thinks that might be me clinging to my Model M and my K&R Bible.

To draw an analogy to SQL, I'd never teach a CURSORs or other loops in a 4 hour class there because you're supposed to be able to do everything in SQL as a SET operation. In theory you should stick to the pipeline in PowerShell. I use for and while loops in PowerShell more often than I do do cursors and while loops in SQL. However, PowerShell is a scripting language and conventions are less strictly enforced and I also push the boundaries of powershell with inline C# and excessive dependencies on calling native .NET APIs. My audience will not be ding this.

For those not adept at powershell, I'm pretty sure you don't actually need a for or while loop. I use them, but that's because I have experience with other languages. For example if you only want the first 10 members of an array of 20 members:

```<code>1..20 | Select-Object -First 10 | ForEach-Object { Write-Host $_ }
</code>```

答:
I think this hinges on what kind of programming experience they have coming in --

If they are rank beginners and have never seen loops/control structures before they definitely need to see traditional for and while structure: They'll see it in the wild (in nearly every language they'll ever use), and it shouldn't be a surprise when they do.

ForEach-Object, much like Perl's foreach is a tasty shortcut dipped in syntactic sugar.  They should know it because it saves a lot of typing and is logical when you read it.

If they're already programmers (or have at least some limited experience) they'll grasp the concept quickly.  If not, contrive a for loop that is easier to do with ForEach-Object, and have them do it both ways (for loop first, ForEach-Object second) so they see a real and immediate benefit.


问:
Pass in single settings object vs multiple setter methods?
Working with C++.  Suppose I have a class BoxFilter.  The class is used to filter boxes which have properties such as height, width, depth, weight, etc.  The filter might have something like MaxWidth so that boxes with a width greater than MaxWidth would not pass the filter.  Usage would be something like (C#-style pseudocode):

```<code>IBoxFilter filter = new BoxFilter();

foreach(Box box in boxes)
{
  if(filter.PassesFilter(box))
  {
     // do something
  }
}
</code>```

(sorry for the C# example but I think it's easier to understand)

In setting up the filter object I need to configure the settings of the filter.  The filter currently has 7 properties although it could get more over time.  I'm debating whether the filter class should have multiple setters such as SetWidthMax(), SetWidthMinimum(), SetHeightMax(), SetHeightMinimum(), etc or should I create a BoxFilterSettings object/struct and then have a single method on the box filter class called SetSettings(BoxFilterSettings settings)?

答:
The filter currently has 7 properties although it could get more over time. I'm debating whether the filter class should have multiple setters {snip} or should I create a BoxFilterSettings object/struct

I think you will end up doing both. Based on experiences (at my previous employer) with some applications that have been sold for over 15 years, you will slowly add more and more properties. This is normal. But a constructor with 20 parameters is not. Nor is having 20 different constructors, all which vary by 1 setting.

What we ended up doing:

We left the setters/getters. Adding more as the years go by.

We created a big settings object. This settings object would be passed to the constructor (the number of constructors was reduced to 2: one with settings, one with none). We also had a separate settings setter that took this settings object.


问:
Does forcing a user to add numbers or uppercase letters really make a password stronger?
Recently my university updated their password storage procedure, and they have several criteria such as that the password must contain a number, symbol, and uppercase character, and has a length requirement. Realistically, when a brute force / dictionary attack is being performed, doesn't this just make it easier for the person to crack one that works? I understand that this is to prevent people from doing things like "password," but what about one such as "youwillneverguessmypassword" ?   </p>

答:
Realistically, all the matters for the attacker is that you could use them. It doesn't matter if you actually do, because they still have to enumerate those possibilities, from the perspective of a brute force attack. Having a very long length is a better protection- and even better, you can find apps such as KeePass that will encrypt very long passcodes so you don't even have to remember a different one for every site.

Of course, the restrictions do enforce that you won't be vulnerable to a dictionary attack.


问:
Best option for PDF viewer embedded in web app
I have a web app that needs to be able to display a PDF.  It needs to allow the user to page through the PDF, and my application needs to be able to know which page is currently being viewed, because other aspects of the web app will change based on the current page.  Ideally it would not be dependent on the client having Adobe Reader but I could probably support that dependency.

What are my best options for this?  My application stack consists of ASP.NET 4 along with optionally Silverlight 5.  Also, I could use something that is client-side based as well using JavaScript / HTML if such a thing exists.

I found ComponentOne's offering for this and that seems like the leading candidate at this point, but I want to know if there are other options I should consider.

Edit: Per Fosco's comment, converting the PDF to another format (such as HTML) might be an option, as long as I could tie back parts of the converted document to the original PDF page #s.

Another note: this has to run entirely on our servers.  It would not be acceptable to use a third-party service to view the PDFs.

答: My suspicion is that if you want to keep track of the page, and do other things, you'll have to get away from PDF in the browser. Based on what you've said, probably the easiest solution will be to extract pages from the PDF as images (perhaps preprocess the PDFs and store each page image separately), then use a Silverlight control to show the pages one by one. A possible starting place is this codeproject sample. According to some other StackOverflow answers, it is not possible to do this with iText. </p>


答:
It's a Tradeoff

Anytime you add constraints to a password you make it weaker.  Conditions reduce the number of possible passwords.  You also adding commonality to all the passwords which may or may not be useful in cracking them.

That being said it also prevents people from choosing single character password, english word passwords, etc.  These are much easier to crack using things like a dictionary attack.

Title: Does forcing a user to add numbers or uppercase letters really make a password stronger?

Body: Recently my university updated their password storage procedure, and they have several criteria such as that the password must contain a number, symbol, and uppercase character, and has a length requirement. Realistically, when a brute force / dictionary attack is being performed, doesn't this just make it easier for the person to crack one that works? I understand that this is to prevent people from doing things like "password," but what about one such as "youwillneverguessmypassword" ?   </p>


问:
Why and for what reasons developers may not like "daily scrum"?
There are advantages in holding daily scrum, like:

Team get coordinated with each other

Everyone knows what amount of task has been done

Burndown chart gets more and more complete

Task board is updated

It doesn't last that much, 15 minutes won't kill anybody

However, recently (after 6 months of implementing and using scrum), I feel like that our developers don't like scrum daily that much anymore. People just update the task board, without explaining enough and it seems that  they're bored of it. I see that when for any reason, we don't hold it, they kind'of become extra-happy.

I just don't know what could be wrong with this. Are there any reasons mentioned somewhere for disadvantages the "daily scrum" can have for a team? What could be the reasons for developers getting tired of daily scrum?

答:
My observation is far too often these meetings are for the managers to look and feel like they're actually doing something rather than them being useful for the team and the project.

For example, a team is assigned to do series of short bug fixes on different projects. They're really not working as a team but as individuals. However, because company/department policy mandates it, the team lead/manager holds a daily scrum meeting anyway. All that's accomplished is taking out 15+ minutes for a useless meeting and tacking on 15-30 minutes of distraction and lack of productivity before and after the meeting.

Now, I have seen scrum done well in a project that had tight deadlines and required a lot of coordination between people working on various pieces. In that context it was a great system. But, in the context of "We're having a meeting because we're a scrum/agile shop and that's what we're suppose to do" can really suck.


问:
What are the steps required to ensure you've covered technical due diligence when purchasing a software product (and IP) created by another company?
If you were tasked with performing due diligence for a software product/IP you/your company was considering buying.  What would be your steps to make sure the purchase was acceptable from a technical risk level?  The scenario is one company has a product you or your company is interested in buying in it's entirety (IP and code) so that your company can now sell that product or it's services.  The upfront assumption is the product has some value, but you want to assess the technical foundation of the product to ensure it's not a complete hack and nightmare to support.

Examples of this might include

Compile/Build and install the software on a clean computer to verify the build and deploy cycle.

Run a code profiling tool against the code base to get an idea of overall code quality.

What else?  Are there any resources/checklists on the web which might help?

答:
Since I didn't get a true answer to my question I though I'd follow up with what I did.

I ended up putting together a combination of a Due Diligence Checklist and a Software Quality Assessment in a combined document along with a list of questions and answers received from the various communications with the company we were buying the product from.

For the Software Quality Assessment I used a variant of the ISO/IEC 9126 standard tailoring it to our internal needs and weightings.  This covers key aspects of software including maintainability, evolvability, portability and descriptiveness.

The due diligence checklist had a list of activities along with whether they had been completed and comments on how the activity was done.  Activities included the following:

Software Architecture

High level Software Architecture Overview Presented

Software Architecture Documentation Provided

Code Quality Analysis Performed

Hardware Architecture

High level Hardware/Infrastructure Overview Presented

Hardware/Infrastructure Architecture Documentation Provided

Support

High Level Support Overview Presented

Support and troubleshooting documentation provided

High level onboarding walkthrough

Onboarding documentation delivered

Build and Deploy

Build and Deploy Documentation Delivered

Clean Machine Build and Deploy executed

Cost Estimates

Estimate ongoing Support costs for onboarding and keeping the product running

Estimate initial hardware and resource costs for bringing the solution “in house”

Estimate initial software and resource costs for bringing the solution “in house”


问:
Why are strings so slow?
Ever since my very first programming class in high school, I've been hearing that string operations are slower — i.e. more costly — than the mythical "average operation." Why makes them so slow? (This question left intentionally broad.)</p>

答:
"The average operation" takes place on primitives.  But even in languages where strings are treated as primitives, they're still arrays under the hood, and doing anything involving the whole string takes O(N) time, where N is the length of the string.

For example, adding two numbers generally takes 2-4 ASM instructions.  Concatenating ("adding") two strings requires a new memory allocation and either one or two string copies, involving the entire string.

Certain language factors can make it worse.  In C, for example, a string is simply a pointer to a null-terminated array of characters.  This means that you don't know how long it is, so there's no way to optimize a string-copying loop with fast move operations; you need to copy one character at a time so you can test each byte for the null terminator.

ContentLicense: CC BY-SA 2.5

Title: Why are strings so slow?


答: It depends on your assessment of the threat profile and your user community.  It definitely helps against the intended profile - of people choosing real words as passwords, and attackers guessing them.   On the other hand, it makes it more likely that the passwords will be written down instead of remembered, so the attackers who work by looking for scraps of paper will have more to work with.


问:
What can you do about the quality of existing integration and unit tests while being the new guy in a team ?
A recurring theme that I came across in my career is being the new developer to arrive in a team, and quickly having an inherent distrust of the existing unit and integration test suites.

During the interview you are told by the management that they "strongly support unit testing" and that they openly encourage it. They do, but everything about the tests themselves is just plain wrong. Like the fact that they are claiming 100% coverage when there is 100% integration test coverage but less than 10% repeatable unit test coverage. Some other problems I have found:

No clear indication between what is a unit test and what is an integration test. Unit and integration tests are mixed together in the same class.

Integration tests that have undeclared explicit dependencies on very specific dynamic data on a specific environment's database.

Non-transactional integration tests, basically tests that may or may not bother to clean up after themselves, sometimes requiring manual database "scrubbing" to make the test repeatable.

No mocking whatsoever, and application code requires a major overhaul just for mocking to be possible. In other words, design without testing in mind.

No clear naming conventions to quickly look at a test name and determine roughly what tests are being done.

This is all not to say that ALL of the tests are useless or bad, a good deal of them are pretty good and worth keeping, but it feels like panning for gold sometimes. I would purposely avoid running tests just because I was afraid of screwing up the database for my black-box test cases.

This has essentially given me an inherent mistrust of unit and integration tests that I have not personally written or reviewed in some way.  At some level if you don't have faith in the quality of your test suite then it really brings no value to the team or the project whatsoever.

What do you do when you find yourself in this situation?  What do you feel the best plan of attack would be to tackle something like this?

Should all of the tests be refactored in a monumental effort spanning across releases?  Should you just abandon the idea that this legacy project may have one day solid unit test coverage?

答:
The good thing about being new to the team is that you have a "fresh" approach to things. The bad part may be that others may have a hard time believing you.

Don't make a laundry list of things to be done. But pick ONE thing that seems urgent, and that others are most likely to respond to, and suggest a solution. If it works, great, then suggest another solution to another problem, on the strength of your first success.

But take it slow, one by one, and hope that your ideas slowly "catch on" among the new group.


问:
Should a design document contain a discussion of the pros/cons to a given design or should it focus on facts and rationale?
I'm currently in the process of updating a design document so that it is correct and up-to-date for future developers.

Currently, the document focuses on only the facts, presenting how the design is. There is no rationale for any decisions presented. I believe that it's important to capture rationale so that developers know why something is the way it is, as that will probably affect future decisions. It's not possible for me to add rationale for all of the design decisions, especially those made before I started working on the project, but I'm doing what I can in this department.

However, some of the design decisions are, respectfully, very poor decisions given the requirements of the project. There are some good ones, though, as well.

My initial thought was that I should include a discussion of design problems and potential solutions or workarounds to these problems to focus the attention of future maintainers, but I'm not sure if the design document is a place for this type of discussion and information. I don't want a design "critique" to snowball into "ripping this design a new one" as other people work on this system and update the document, as that is clearly inappropriate.

My manager would support either decision, so it's up to me. Regardless of the approach that I take, the document produced would be officially versioned and provided to developers working on the system, typically before they are tasked with development work. It's expected that a new developer familiarize themself with the documents associated with a given software system prior to beginning development work.

Questions:

Should a design document stick to raw facts ("this is the design") and rationale ("here is why this is the design") or should it also be used to point out non-defective issues with the design that could be problematic for future developers?

If the design document should not be used to capture this information, what type of document should capture it, and what else should be captured with a discussion of design rationales, tradeoffs, and known issues (that aren't defects, as defects are tracked using other tools)?

答:
There are 3 important facts in the process of decision making:

What was tried and did not work (and why it didn't work, because you're targetting a moving target)

What is

What could be (just waiting for X to be implemented...)

However, apart from "What is", all the others will confuse the reader and prevent her from groking the system.

I like the idea of capturing the other 2, though they are less interesting for learning the system, they can be time savers when changing it.

Therefore, I would build on the idea exposed @FrustratedWithFormsDesigner, with a twist. Instead of creating yet another document, with a life-cycle of its own, I would tack-on an annex section. Then for each decision worthy of discussion, I would point to the relevant entry in the annex.


答: Let me answer your question with a question. Why does saying a string of words take longer than saying a single word?</p>

Title: Why are strings so slow?

Body: Ever since my very first programming class in high school, I've been hearing that string operations are slower — i.e. more costly — than the mythical "average operation." Why makes them so slow? (This question left intentionally broad.)</p>


问:
How should I choose the right Android phone for testing my app?
I am looking to buy an Android phone to test my first Android app on.

What things should I pay attention to to make sure I pick the most suitable device?

答:
If I developed for Android I'd get me a dedicated device which is relatively powerful, easy to root and easy to reflash. This would give me more ability to test my app in various conditions, especially user-reported conditions, on real hardware.

Of course you'll test your apps on several emulators: different Android versions, screen sizes, presence/absence of hardware buttons, all the things you can't change easily on a physical phone. But an emulator can't tell you much about how usable your app is in daily use, while a physical phone is something you can carry around to field-test your app.

And certainly enoug you'll be asking your Android-owning friends and willing beta-testers to run your app on various devices they have. It's hardly imaginable to actually own all of the hundreds of devices that run Android.


答:
I would turn the problem on its head.

Some people want to filter on width, others on height, others want only square forms, or rectangles that roughly have a 16:9 aspect...

You cannot possibly propose all alternatives.

Therefore the easier is to propose an interface:

```<code>class IFilter: boost::noncopyable {
public:
  virtual bool passes(Box const& box) const = 0; // const or not ?
  virtual ~IFilter() {}
};
</code>```

And perhaps setup some easy filters:

```<code>class MaxWidthFilter: public IFilter {
public:
  MaxWidthFilter(size_t max, IFilter const* next = 0): _max(max), _next(next) {}

  virtual bool passes(Box const& box) const {
    if (box.getWidth() > _max) { return false; }
    return _next ? _next->passes(box) : true;
  }

private:
  size_t _max;
  IFilter const* _next;
};
</code>```

Note: you might want to go full cloning/owned here.

Advantages:

Extensible

Order of tests is configurable

Can do more than filtering (ie: statistics on tests, ...)

Disadvantages:

A bit more complicated to begin with (though you already have 7 properties...)

A bit more slower probably, though the possibility to reorder tests depending on the collection to filter might outweight this

Note: you could recognize a Decorator here, or perhaps a Chain of Responsability.

Title: Pass in single settings object vs multiple setter methods?

Body:
Working with C++.  Suppose I have a class BoxFilter.  The class is used to filter boxes which have properties such as height, width, depth, weight, etc.  The filter might have something like MaxWidth so that boxes with a width greater than MaxWidth would not pass the filter.  Usage would be something like (C#-style pseudocode):

```<code>IBoxFilter filter = new BoxFilter();

foreach(Box box in boxes)
{
  if(filter.PassesFilter(box))
  {
     // do something
  }
}
</code>```

(sorry for the C# example but I think it's easier to understand)

In setting up the filter object I need to configure the settings of the filter.  The filter currently has 7 properties although it could get more over time.  I'm debating whether the filter class should have multiple setters such as SetWidthMax(), SetWidthMinimum(), SetHeightMax(), SetHeightMinimum(), etc or should I create a BoxFilterSettings object/struct and then have a single method on the box filter class called SetSettings(BoxFilterSettings settings)?

Body:
I would turn the problem on its head.

Some people want to filter on width, others on height, others want only square forms, or rectangles that roughly have a 16:9 aspect...

You cannot possibly propose all alternatives.

Therefore the easier is to propose an interface:

class IFilter: boost::noncopyable {
public:
  virtual bool passes(Box const& box) const = 0; // const or not ?
  virtual ~IFilter() {}
};

And perhaps setup some easy filters:

class MaxWidthFilter: public IFilter {
public:
  MaxWidthFilter(size_t max, IFilter const* next = 0): _max(max), _next(next) {}

  virtual bool passes(Box const& box) const {
    if (box.getWidth() > _max) { return false; }
    return _next ? _next->passes(box) : true;
  }

private:
  size_t _max;
  IFilter const* _next;
};

Note: you might want to go full cloning/owned here.

Advantages:

Extensible

Order of tests is configurable

Can do more than filtering (ie: statistics on tests, ...)

Disadvantages:

A bit more complicated to begin with (though you already have 7 properties...)

A bit more slower probably, though the possibility to reorder tests depending on the collection to filter might outweight this

Note: you could recognize a Decorator here, or perhaps a Chain of Responsability.


问:
Are certifications worth it?
I am finishing my college degree in programming soon and I'm exploring the next steps to take to further my career. One option I've been considering is getting a certification or a series of certifications in the area of development I want to work in.

Are these certifications worth the time and money? Do employers place a lot of value in them?

答:
Consulting/Contracting

No one has mentioned the particular case of consulting/contracting. If you are in this category or you would like to be, this can definitely help you.

You are easier to 'sell' on a project if your boss or sales guy can pitch you as being certified in 'niche category X'.

That being said you are not necessarily better or more knowledgeable on a particular topic if you are not certified, and I agree with others who might take a dubious take on them in general. Although, having a few MS certifications I can say for you, if you crank on them on a technology that you are trying to learn, it really forces you to get up to speed.

Title: Are certifications worth it?


答: If this is a web based application then you should keep in mind "paging" your data result set.</p>

Title: Constant database calls or store in objects?

Body:
I'm creating a pretty simple database driven application. Whenever I create a db app, I create classes that mimic the data in the db. Is this good practice?

Am I better off making one big call to the database and populating my objects and working with these objects, or should I retrieve data from the db only when needed?


问:
How important is it to be syntactically correct during an interview?
When asking an interview candidate to write a program on the whiteboard, do you expect the candidate to write code that is syntactically correct?

I had two candidates, one of which wrote a syntactically correct program but the logic was not up to the mark, and the other had the logic better written but the syntax was crap.

I favor the first candidate.

答:
It would definitely depend on the position for which the interview is, and probably on the language as well.

Working on C++, having a guy stuttering on syntax is scary. C++ is full of dark corners, traps lay basically everywhere. A stutter on the syntax means a poor exposition to the language, and C++ beginners make lots of mistakes (not to say that others don't from time to time).

To answer your question, then:

if I need to fill a simple developer position, I would take the guy with a good grasp of the C++ syntax. He won't shine, but should not provoke too many catastrophes.

if I need to fill a lead developer position, I would not take either. A lead developer is supposed to have both experience and logic.

There is only one caveat: people acknowledging their lack of experience. Ideally people should code in their language of choice, or pseudo code if they so prefer (students for example).


问:
Can you write an unambiguous specification in a natural language like English?
It seems to me that you cannot possibly write a software specification in English that is completely free of ambiguities, simply due to the informal nature of natural language - and therefore that a truly unambiguous specification must include code written in a formally specified language.

Is this a known result or am I missing something?

答:
Impossible?  Let's ask if it's desireable first.  If we agree that it's impossible, and there's still lots of useful software out there, then the goal of an unambiguous specification seems academic.

I'd say that it's impossible to prove that anything is perfect and unambiguous, both for the spec and the software.

I think it depends on the size of the problem.  If the problem is small enough, mathematical in nature, and perhaps some other criteria that I'm missing I'd say it's possible to write an specification that's workable.

The larger the problem, the wider the audience, the harder it is to do.

But avionics and other complex problems suggest that it's possible to write "good enough" specifications in English to solve large problems.

OwnerDisplayName: duffymo


答:
You're not missing anything, except that documentation is written for humans to read. Some ambiguity is expected, and even welcome, because terse text is difficult to read (=not for humans).

Specifying documentation for a formal language in yet another formal language would be a sort of chicken-and-egg problem.

If you really need formal specification, then there are formal ways of checking models. It's an active and very interesting area of research, but the end "users" here are machines, not humans.

Title: Can you write an unambiguous specification in a natural language like English?

Body:
It seems to me that you cannot possibly write a software specification in English that is completely free of ambiguities, simply due to the informal nature of natural language - and therefore that a truly unambiguous specification must include code written in a formally specified language.

Is this a known result or am I missing something?

OwnerDisplayName: Radim


答:
Assume there is a formal language which allows to write unambiguous specifications. Then I propose that there should be a bijective mapping to a subset of English. Therefore, it should be possible to write unambiguous specifications if you stick to this subset.

But any formal language that is expressive enough to do anything interesting will not be free of inconsistencies (Gödel incompleteness).

OwnerDisplayName: hfs


答:
I strongly recommend you research using some kind of data abstraction layer. In Perl I use Data::ObjectDriver and/or Moose. Every language has its equivalent. What these frameworks provide is a simple way for you to define the properties of an object, and then the framework will manage interfacing with the database for you. Often there is no need for you to create your database tables, or even write a single line of SQL code. Not only does this make the mundane task of writing SQL for each of your objects completely unnecessary, but these frameworks also help you solve other potentially large architectural problems, like database partitioning and caching.

Let's just look at Data::ObjectDriver as an example, which I select only because I have experience using it. The source code samples provided by its documentation make the API clear: you define a data structure and a database, and the framework will then create the tables for you make interacting with a recipe for example as simple as:

```<code>my $recipe = Recipe->new;
$recipe->title('Banana Milkshake');
$recipe->save;

my $ingredient = Ingredient->new;
$ingredient->recipe_id($recipe->id);
$ingredient->name('Bananas');
$ingredient->quantity(5);
$ingredient->save;
</code>```

Now here is one more advantage of using a framework like this: one of the things Data::ObjectDriver does for you automatically is to interface with a memcached server should one be present. This automatically offloads a lot of traffic from your database to a low-latency caching system over the network. This ability and others are capabilities you get "for free." And from the big picture point of view, a developer should never bother themselves with reinventing the wheel -- unless the wheel you need has not yet been invented. :)

Now, let's return to your question.

Am I better off making one big call to the database and populating my objects and working with these objects, or should I retrieve data from the db only when needed?

My answer to this question is therefore, don't worry about it, but only if you are using a good data abstraction layer. A good data abstraction layer will have addressed many scaling problems and challenges already, or least provide specific remedies for common problems you might face.

If you find that you must write this code yourself, then I would err on the side of simplicity. Keep your database queries simple, even if that means requiring more of them for any given request. Then use memcached to cache the results of your query. That way, even if it takes 100 queries to build a single object, then so be it. The first time through, generate the 100 queries. In subsequent requests, you won't hit the database at all.

Body:
I strongly recommend you research using some kind of data abstraction layer. In Perl I use Data::ObjectDriver and/or Moose. Every language has its equivalent. What these frameworks provide is a simple way for you to define the properties of an object, and then the framework will manage interfacing with the database for you. Often there is no need for you to create your database tables, or even write a single line of SQL code. Not only does this make the mundane task of writing SQL for each of your objects completely unnecessary, but these frameworks also help you solve other potentially large architectural problems, like database partitioning and caching.

Let's just look at Data::ObjectDriver as an example, which I select only because I have experience using it. The source code samples provided by its documentation make the API clear: you define a data structure and a database, and the framework will then create the tables for you make interacting with a recipe for example as simple as:

my $recipe = Recipe->new;
$recipe->title('Banana Milkshake');
$recipe->save;

my $ingredient = Ingredient->new;
$ingredient->recipe_id($recipe->id);
$ingredient->name('Bananas');
$ingredient->quantity(5);
$ingredient->save;

Now here is one more advantage of using a framework like this: one of the things Data::ObjectDriver does for you automatically is to interface with a memcached server should one be present. This automatically offloads a lot of traffic from your database to a low-latency caching system over the network. This ability and others are capabilities you get "for free." And from the big picture point of view, a developer should never bother themselves with reinventing the wheel -- unless the wheel you need has not yet been invented. :)

Now, let's return to your question.

Am I better off making one big call to the database and populating my objects and working with these objects, or should I retrieve data from the db only when needed?

My answer to this question is therefore, don't worry about it, but only if you are using a good data abstraction layer. A good data abstraction layer will have addressed many scaling problems and challenges already, or least provide specific remedies for common problems you might face.

If you find that you must write this code yourself, then I would err on the side of simplicity. Keep your database queries simple, even if that means requiring more of them for any given request. Then use memcached to cache the results of your query. That way, even if it takes 100 queries to build a single object, then so be it. The first time through, generate the 100 queries. In subsequent requests, you won't hit the database at all.


答:
Isn't this what lawyers always did to avoid ambiguities?

The result is they write in the most unnatural ways, trying to read their papers is more difficult than ever, and despite this there are always inconsistencies and ambiguities.

You are right, you cannot write a software specification that is completely free of ambiguities, but you won't manage to do that implementing a formal specified language either.

This is also why we document our code, because sometimes it's difficult to read for our minds.

No point in documenting code with another code.


问:
Difference between templates in JavaScript and design patterns
What is the difference between templates and design patterns in JavaScript?

I read about the template method design pattern and now I wonder how it relates to JavaScript templates (if at all).

答:
Templates (in the Javascript world) are a method to display Javascript (model) data in an HTML (or other) view.

Design patterns are known (and battle tested) methods of solving common problems.

Really, Javascript templates could be construed as a design pattern (depending on who you ask ;)).

OwnerDisplayName: Hari


答:
Design patterns are used to solve commonly encountered problems related to software design.
Once you know how to solve a particular problem, when that problem presents again you can reuse the same approach you used before, the same pattern.

Patterns are not related to JavaScript only, but to every language.

The JavaScript Templates you are referring about may be a technique used to generate data in the document, originally called Micro-templating by the inventor, John Resig (jQuery).

Here's an article to better understand them.

And here's one for applying common design patterns in JS.

Title: Difference between templates in JavaScript and design patterns

Body:
What is the difference between templates and design patterns in JavaScript?

I read about the template method design pattern and now I wonder how it relates to JavaScript templates (if at all).


答:
well.. a completely unambiguous specification of the problem is the actual code itself :)

This is a known problem and for special mission critical systems it is mandatory to write unambiguous specification in a formal (programming) language and then transform that to a code that is provably does what the specification says. This is a very narrow field, 99.999% of the developers never has to do tasks like this, but I once talked with a guy who did this for a traffic controlling/railway system.


答:
There is very big problems with complexity in the example above:

The actual structure of the problem is 2d array (of booleans) where one dimension is boxes and another dimension is the properties. This structure is pretty much coming from visual basic from 1980.

Then there is arbitrary boolean expressions manipulating these booleans from the 2d array

These two features together make it extreamly complex. For example, testing that the code works requires going through all elements of the 2d array (and evaluating boolean expression in each element of the 2d array) and then further evaluating the boolean expressions that connect the rows and columns of the 2d array. It's like adding your excel spreadsheet to your program and then making it calculate some values from the data; except that you need to add the setters/getters manually and manipulating the data is very burdensome. The complexity is still there.

So my recommendation is to try to make it simpler somehow - reducing rows/columns is a start, but try to get rid of the 2d array structure. So that you don't need to implement whole excel for it. Excel also uses this kind of 2d array where each node can have differently typed data in it. These conventions coming from C# seems to have this kind of hidden complexity in them.

Here's some c++ code which is pretty much equivalent of your code above, and allows you to see the actual 2d array structure:

```<code>template<class T> class Array1d { virtual T Map(int x) const=0; };
class Array2d { virtual bool Map(int x, int y) const=0; };
class Array2dImpl : public Array2d {
     Array2dImpl(Array1d<Box> &b) : b(b) { }
     bool Map(int x, int y) const
        { if (y==0) { return b.Map(x).width < maxwidth; }
           if (y==1) { return b.Map(x).height < maxheight; }
         ...  }
   Array1d<Box> &b;
   int maxwidth;
   int maxheight;
 };
 class BooleanExpression : public Array1d<bool>
 {
 public:
     BooleanExpression(Array2d &a) : a(a) { }
     bool Map(int x) const { return a.Map(x,0) && a.Map(x,1) && a.Map(x,2) && a.Map(x,3); }
 private:
     Array2d &a;
 };
</code>```

Like your example above, this code can be used with a simple piece of code:

```<code>int main() {
   Array1d<Box> boxes;
   Array2dImpl array(boxes);
   BooleanExpression e(array);
   for(int i=0;i<e.size();i++)
      {
       if (e.Map(i)) { /* do something */ }
      }
  }
</code>```

Now returning to your question about how to set the maxwidth variable in this example. It might seem that it requires separate setter for each property. But this is not the case, actually, best way forward is to add a function like this:

```<code>void SetElement(int x, int y, bool b);
</code>```

This naturally belongs to the 2d array which is already included in your example. The real problem  with this example is that there is 2^(x*y) different states the system can be in. This comes from x*y calls to SetElement. This kind of state explosion is completely crazy for such a system and this will break your software very badly.

Even if we assume you want to generate x*y booleans using the code above by just providing the dimensions, the trick how your example did the evil complexity is very hidden. Passing the box from foreach to PassesFilter() function looks very simple, but it causes all this trouble, reconfiguring all the booleans in single line of the excel. Related is also the state space involved in the coordinates of the boxes. Those are even worse problem.

(and no, hiding the 2d array by using C# code does not make it easier to understand,)

(In fact, it's very evil to post such code for other programmers to read, I hope you didn't know the 2d array is there and you still have a chance to somehow fix your software...)

Body:
There is very big problems with complexity in the example above:

The actual structure of the problem is 2d array (of booleans) where one dimension is boxes and another dimension is the properties. This structure is pretty much coming from visual basic from 1980.

Then there is arbitrary boolean expressions manipulating these booleans from the 2d array

These two features together make it extreamly complex. For example, testing that the code works requires going through all elements of the 2d array (and evaluating boolean expression in each element of the 2d array) and then further evaluating the boolean expressions that connect the rows and columns of the 2d array. It's like adding your excel spreadsheet to your program and then making it calculate some values from the data; except that you need to add the setters/getters manually and manipulating the data is very burdensome. The complexity is still there.

So my recommendation is to try to make it simpler somehow - reducing rows/columns is a start, but try to get rid of the 2d array structure. So that you don't need to implement whole excel for it. Excel also uses this kind of 2d array where each node can have differently typed data in it. These conventions coming from C# seems to have this kind of hidden complexity in them.

Here's some c++ code which is pretty much equivalent of your code above, and allows you to see the actual 2d array structure:

template<class T> class Array1d { virtual T Map(int x) const=0; };
class Array2d { virtual bool Map(int x, int y) const=0; };
class Array2dImpl : public Array2d {
     Array2dImpl(Array1d<Box> &b) : b(b) { }
     bool Map(int x, int y) const
        { if (y==0) { return b.Map(x).width < maxwidth; }
           if (y==1) { return b.Map(x).height < maxheight; }
         ...  }
   Array1d<Box> &b;
   int maxwidth;
   int maxheight;
 };
 class BooleanExpression : public Array1d<bool>
 {
 public:
     BooleanExpression(Array2d &a) : a(a) { }
     bool Map(int x) const { return a.Map(x,0) && a.Map(x,1) && a.Map(x,2) && a.Map(x,3); }
 private:
     Array2d &a;
 };

Like your example above, this code can be used with a simple piece of code:

int main() {
   Array1d<Box> boxes;
   Array2dImpl array(boxes);
   BooleanExpression e(array);
   for(int i=0;i<e.size();i++)
      {
       if (e.Map(i)) { /* do something */ }
      }
  }

Now returning to your question about how to set the maxwidth variable in this example. It might seem that it requires separate setter for each property. But this is not the case, actually, best way forward is to add a function like this:

void SetElement(int x, int y, bool b);

This naturally belongs to the 2d array which is already included in your example. The real problem  with this example is that there is 2^(x*y) different states the system can be in. This comes from x*y calls to SetElement. This kind of state explosion is completely crazy for such a system and this will break your software very badly.

Even if we assume you want to generate x*y booleans using the code above by just providing the dimensions, the trick how your example did the evil complexity is very hidden. Passing the box from foreach to PassesFilter() function looks very simple, but it causes all this trouble, reconfiguring all the booleans in single line of the excel. Related is also the state space involved in the coordinates of the boxes. Those are even worse problem.

(and no, hiding the 2d array by using C# code does not make it easier to understand,)

(In fact, it's very evil to post such code for other programmers to read, I hope you didn't know the 2d array is there and you still have a chance to somehow fix your software...)


答:
Specifications are ambiguous and imprecise because people are ambiguous and imprecise.  Find a perfect person and perhaps then you can get a perfect specification.

English, Swahili, Sanskrit or Babylonian makes no difference.


答:
Fix them over time

I've been in the same situation.  I just spent an hour every morning going through tests and fixing them until they were all fixed.  It was a medium sized codebase and I think I finished in 1.5 months.  I also got much more confident in our tests.

I personally don't care if a test is a unit test or integration test as long as it's a good test.  By good test I mean that it:

cleans up after itself

is repeatable

minimizes environmental interactions

is consistent

Along the way I evangelized better test construction (which is to say I bugged people alot).

Title: What can you do about the quality of existing integration and unit tests while being the new guy in a team ?

Body:
A recurring theme that I came across in my career is being the new developer to arrive in a team, and quickly having an inherent distrust of the existing unit and integration test suites.

During the interview you are told by the management that they "strongly support unit testing" and that they openly encourage it. They do, but everything about the tests themselves is just plain wrong. Like the fact that they are claiming 100% coverage when there is 100% integration test coverage but less than 10% repeatable unit test coverage. Some other problems I have found:

No clear indication between what is a unit test and what is an integration test. Unit and integration tests are mixed together in the same class.

Integration tests that have undeclared explicit dependencies on very specific dynamic data on a specific environment's database.

Non-transactional integration tests, basically tests that may or may not bother to clean up after themselves, sometimes requiring manual database "scrubbing" to make the test repeatable.

No mocking whatsoever, and application code requires a major overhaul just for mocking to be possible. In other words, design without testing in mind.

No clear naming conventions to quickly look at a test name and determine roughly what tests are being done.

This is all not to say that ALL of the tests are useless or bad, a good deal of them are pretty good and worth keeping, but it feels like panning for gold sometimes. I would purposely avoid running tests just because I was afraid of screwing up the database for my black-box test cases.

This has essentially given me an inherent mistrust of unit and integration tests that I have not personally written or reviewed in some way.  At some level if you don't have faith in the quality of your test suite then it really brings no value to the team or the project whatsoever.

What do you do when you find yourself in this situation?  What do you feel the best plan of attack would be to tackle something like this?

Should all of the tests be refactored in a monumental effort spanning across releases?  Should you just abandon the idea that this legacy project may have one day solid unit test coverage?


答:
Are you aware of the Android Developer phone? It could be a good starting point. You can find information on testing your app on hardware at:

https://developer.android.com/studio/run/device.html

Title: How should I choose the right Android phone for testing my app?

Body:
I am looking to buy an Android phone to test my first Android app on.

What things should I pay attention to to make sure I pick the most suitable device?


问:
Debugging applications
In my current developement, I have decided to keep the command prompt open so I can see debug messages. For example, if something wasn't happening when it should, I would put a cout statement at every function to determine where the broken link is. Sometimes, I might get hundreds of the same message (like WM_MOUSEMOVE) and I need to determine whether or not the messages are still coming, so I would using a static variable, and increment it, so I might have:

```<code>...
3> WM_MOUSEMOVE processed.
4> WM_MOUSEMOVE processed.
54> WM_CLICK processed.
5> WM_MOUSEMOVE processed.
...
</code>```

in my cmd. (Don't ask me why there would be 54 WM_CLICK and 4 WM_MOUSEMOVE)

What I would like to know is your opinion. Is this a good approach to debugging? What kind of syntax would you use for consistency? Does a syntax even matter? And would you make any suggestions to how this method could be improved.

答:
There are a few ways.

What you are using is a rudimentary form of logging. It's probably the most time-efficient way of debugging most errors. It's worth your time to write a solid logging module that can be redirected to screen or file, buffered/unbuffered, etc. It should have a timestamp and a message, if nothing else.

There is also throwing exceptions - this can be more useful with languages that perform a stack trace using symbols, e.g., Java or Python.  Perl can croak()  or die() with similarly useful information.

One other method is having a large array of unit tests which can pick up errors in a refined fashion. That of course implies well-written tests.

The above are essentially non-interactive methods.

There is also Ye Old Interactive Debugger, which functions in various levels of usefulness depending on development environment.  Lisp probably has the best debugging facilities available; C# probably has the most developed UI. Interactive debuggers can be very useful when your code "logically" should work, and you really need to do some serious variable-ogling and probe around. It's probably the most inefficient and hard to replicate of all the methods, but can be really useful.

The interactive debugger can be extended to have various conditions and scripts run on variables hitting values, but I'm not sure if any current environments support it - the last one I heard of was developed in '93 for... Prolog? Can't recall off the top of my head.

One method that was researched in the early 80s and is having a minor comeback today is replayable/reverse debugging. I am working on doing that in my thesis for a highly exotic embedded system.

Title: Debugging applications


答:
(Some of my points have already been alluded to by other answers, but I feel that I'm providing a different enough perspective to make this worth an answer rather than a comment.)

Before we address the issue of whether a specification can be truly and completely unambiguous, we must address the question of whether it should be unambiguous, at least at the level that you are asking about.

Let me approach this from the perspective of a program manager working on a small-to-medium sized project, or a feature as part of a larger project. There are usually two different types of specifications that will be written for such a project: a Functional (or PM) specification and a Design (or Dev) specification:

The Functional specification has the job of describing what the projecty or feature should do, often from the perspective of the customer. It should not, in general, describe how this should be done. Depending on the type of project, the customer may care what the external-facing API looks like, but does the customer care whether class A inherits from class B or implements interface C? He shouldn't. And neither should the functional specification. This already introduces one level of ambiguity: that of technical design.

The Design specification has the job of describing how the functional requirements should be met, from the perspective of the architect or technical designer of the feature or project. It is intended to resolve the high-level ambiguities of technical design. This will contain those details that you didn't want in the functional specification, such as the architecture of the solution, including class sctructure, inheritence, perhaps even individual functions and methods, depending on the scope and scale of the project. Does the architect care what you call your temporary variables or whether you use a list or an array for an internal datatype? Assuming she trusts her developers, she shouldn't, and neither should the design specification. This introduces a second level of ambiguity: that of implementation.

In general, these implementation-level details are not captured in a formal document, but rather documented, per se, in the code itself, including the comments. This level of ambiguity allows a good developer to use his or her own skills and make the detail-oriented technical decisions that are the hallmark of a good individual developer. Because of this, I will not hesitate to say that ambiguity in a specification is, in fact, a good thing: it allows developers to do their jobs, and elevates them above mere "code monkeys".

This isn't to say, however, that there should be ambiguity through the whole document. On the high level, there should be no ambiguity about the interface with the customer. If the feature has a public-facing API, it should be strictly defined. If the system requires a date to be passed in to do it's job, should this date be in the local time zone or UTC? What format is needed? Does it need to be accurate to the millisecond, or is the minute just fine?

Coming back to the question of whether natural language can be used to create unambiguous specifications, it's true that it isn't very good at capturing this level of clarity. I've seen it done in certain limited circumstances, but those are likely unique exceptions that we can't apply universally. Most often, ambiguity is resolved with the help of technical jargon, diagrams, or even pseudocode. Once you start enlisting the help of such tools, the natural language ceases to be the sole descriptor. Because these tools can make even a completely functionally unambiguous specification much more clear, I would venture to say that such an undertaking shouldn't even be attempted.

Having said that, because natural language is generally supplemented by these tools to make it functionally unambiguous, it is my professional opinion that no, natural language alone is not sufficient to create unambiguous specifications in all cases.


问:
Most efficient way to learn java if you already know how to code?

Possible Duplicate:

  Is there a canonical book for learning Java as an experienced developer?

I've been coding for close to 25 years now in basic, (C64 & Amiga), (Object) pascal, C, LPC and for the last few years, Python.
Python is definitely my favourite (and strongest) language. However, lately I've been forced to do stuff in Java - I have never written a single line of java code so far.

So I'm asking your advice - what is the fastest and most efficient crash course to learn java.

EDIT: I'm really looking for something along the lines teaching java to people who know how to code and what OOP is - not something that has with no previous programming experience in the synopsis.

答: Write an Android app. You might end up producing something genuinely useful along the way.</p>


问:
What are the advantages of showing line numbers in a text editor?
I feel weird when I'm editing code in an IDE that does not have line numbers in the text editor.

The questions I have are:

Are line numbers visually excessive, particularly when a find by line function exists in your IDE of choice?

What are the uses of showing line numbers?

答: I've found that current line highlighting can solve most "where are you looking" problems. But, the point about stack traces is critical.</p>


问:
Project problems from a Java beginner
A week ago I asked the question; First big project, how to get started. Make menus, save to harddrive etc. I tried to do everything without doing a GUI with Swing but I realized that for every view I wanted to present to the user I had to make a new class. Right now I have 3 menu classes (the mainMenu, computerCategoryMenu,laptopCategoryMenu) I stopped because I would need to make another 6 menu classes and then another 6 if the user registered and another 6 for the administrator of the site. It doesn't look right to me. Furthermore everything looks too static for me. I don't know how to make the administrator add or delete products.

Should I store all my products in a hashmap and then get them to show in different menus? Do you think that doing a GUI with Swing will make things much easier?

答:
It doesn't look right to me.

First of all, usually when it doesn't feel right is because it isn't. You should always try to make your code intuitive for others. Ever tried to change someone else´s code and complained everything is a mess? Well, that's because the coder was only coding for himslef. When you code you should try to make clear for everyone else what youre trying to accomplish. And this usually means choosing the right level of granularity, and choosing the right names for classes, methods, variables, packages and so on.

Should I store all my products in a hashmap and then get them to show in different menus?

If you store all your products on a hashmap you can find them easily with some key. That's good. But is that all you need? You may need to find them by category, by name, order them, specify relations between them and so on. So my guess would be that  you should have a Products class with all this common operations as a public interface. I bet you will find this a lot easier to implement because everything is encapsulated in a single place, and you only need to think about a single -hopefully- simple operation at a time. Remember:clases should ALWAYS be specialists. Keep it short, and simple. I personally like the spartan programming principle.

Do you think that doing a GUI with Swing will make things much easier?

Nope, whatever problems you're having right now may disappear by changing the way you read user input, but you will find new ones. My guess is that you're doing too much in each of your menu classes. Instead of creating a new class for each use case, and stuffing everything inside. I think, you should maybe have a single class which references business objects, and delegates the real job to them depending on the users input. Remember:clases should ALWAYS be specialists. Ask yourself, whats the point of this menu class? Well if it's a menu then it's just about choosing what i want, and that's it. Simple as that. Let someone else do the real work.

Title: Project problems from a Java beginner


答:
One can make natural language relatively unambiguous, but only with great difficulty.

The legal profession quite desperately needs language to be as unambiguous as possible. While much about how a law is applied may be open to interpretation, what the words mean should not.

This need lead to the invention of legalese. How far are you willing to go?


答:
set the example you want to see, but appreciate another developer's perspective in a test: one developer may test for successes, while another may test for failures, one developer wrote the class while another may have used it the first time when writing the test.

the existing tests (erm, most) still have purpose, although it may not be immediately evident. i don't recommend overhauling and refactoring everything all at once (it is tedious and error prone). bad tests ultimately need to be updated, rewritten, or they may simply become obsolete as software evolves.

if your approach to testing is superior in some regards, people will learn from that model or ask you for your assistance. there will be a balance of resources, but you can extend as needed to support your tests.

ultimately, you want to increase the quality of the programs via tests and improve coverage. you can do this by placing more emphasis on testing and setting a good example - but do appreciate other's perspectives.

when emphasizing the importance, you can make your tests' operational environment different - one obvious example is to run tests in parallel; if it's not reentrant, you have located a bug in your program or test (win/win). a more rigorous testing environment will force the bad tests to be fixed and/or rewritten (hopefully the right way the second time around). slowly introduce such changes (don't break half the tests all at once -- that's a real problem), forcing them to learn what makes a good test, and ultimately a good program. then when you and other go in and modify/repair/extend tests, apply what you have learned -- it's incremental and you have a better understanding of the context/program at the time.


问:
Namespace and class name guidelines
I'm having problems naming my classes and services correctly when utils and other help classes are involved.

How would you structure the following:

```<code>EventService.cs
EventServiceUtils.cs
EventServiceValidators.cs
EventServiceCoordinator.cs
</code>```

etc...

I have multiple services with the same needs as the above service. One thought is to separate all of this into a suitable namespace, making it look something like this:

```<code>Services.EventService.EventService.cs //(the actual service)
Services.EventService.Validators.DateValidator.cs
Services.EventService.Validators.ParticipantValidator.cs
Services.EventService.Coordinators.ParticipantCoordinator.cs
Services.EventService.ExtensionMethods.Extensions.cs
</code>```

and so on. Every namespace is of course a separate folder. But this doesn't feel 100%, since there are probably more DateValidators in the other services, which can easily lead to an unwanted reference.

And also the Services.EventService.EventService.cs includes the class name in the namespace, which is no good either. You could use Services.Event.EventService.cs, but there is of course already an entity with that name.

This is the domain model.

答:
Proper namespace design will consider both logical and physical design.

Although the original rationale for namespaces was mostly to prevent name clashes between object and method names, it has become an important element in overall solution architecture and design.  Not only do you want your conceptual hierarchy and logical design to make sense, you probably also want your code to be tidily packaged in well designed and easily reusable libraries that can be easily bundled into other projects and products later.  That is perhaps more the desired outcome of good physical design.

Look at the .NET Framework and how units of related functionality are given to you in reasonably sized assemblies.  You can drop in a reference and a using statement and suddenly you have relevant functionality available without having to drag in any number of kitchen sinks.  This is because the .NET Framework's physical design—including intelligent namespacing—has packaged logically related code in physically related deployable units.  By creating an excellent mapping between namespaces and assemblies, the architects and developers of Microsoft's .NET framework have made your work significantly easier (of course some may argue otherwise, but I'm rather happy with what they did).

Namespaceing in C# is rather arbitrary, really.  You can put namespaces in the oddest places, in assemblies far removed from each other.  Any helpful discipline in this area is really your personal contribution to a well organized software product.  I would not dare to advise you of exactly what to do in each case.  What I hope to accomplish, in this answer, is to get you to think about physical design as well as logical design when you define your namespaces.  The more you keep things logically related and deployably (physically) bundled the easier things will be later, both for you and for others who might need to deal with your code some day.

So, please do think about how your code will be packaged in assemblies and components when you resolve your namespacing issues!

OwnerDisplayName: Mattias

Title: Namespace and class name guidelines


问:
How to tackle complex business rule and logic?
I have a domain expert to work with, but he would throws a lot of details to me verbally.  The business logics are complex, business rules change often, the business process is long and multi-ending / intermediate wait-state.  There are a lot of cases to deal with (because there are many states for the account, product and subscription).

What's the best way to deal with it?  BPMN diagram isn't even low level enough to explain.  Written documentations are time consuming to write and read.  UML state diagram can become crazily complex very soon.

Any advice would be appreciated.

答:
break it down:

get general outline first and create a prelim design of the simple version

then start adding complexities in line with business logic but keep the changes small and compatible with expected updates (but keep consistency always)

(this is a top-down approach)

shut the domain expert up and/or interrupt him regularly with questions/remarks if you need to. you can't help if you don't know what should be done

and business rules shouldn't be changing often, there is likely a scope problem if they do. see if that can be fixed


问:
Have objects delivered in terms of code reuse?
I have often heard it said that objects have not delivered in terms of code reuse. Do you agree? If you believe that they haven't, why not?</p>

答:
Yes.  Good object oriented programming promotes separation of concerns, low coupling, high cohesion, and information hiding.  These things are all critical to reusable code.

I would argue that the main benefit of OOP is modularity and modifiability, rather than reuse, but that's another question.


问:
How do I get into R&D?
I'm beginning to think that I might be best suited for a job in R&D.  The reason being that I like jobs that allow me to be creative and I generally am more interested in solving puzzles than building things.  I really dislike jobs that just boil down to translating requirements into code.

Here's the kicker though:  I don't have a bachelor's much less a masters or phd.  Is it possible for me to land a job like this?

答:
I work at R&D. For one thing, most of it is about the "D" part, that is, building things. You can't escape it. The primary goal of any commercial R&D department is to develop things that work (and that can be sold to customers in order to pay your salary). As Edison put it: 1 % inspiration and 99 % perspiration.

Then there's of course the rare "R" part, tinkering, which is quite enjoyable. The proportion between R and D certainly depends on the field and firm where you're working, but it's typical that making things that work (D) is the high priority, and trying to come up with something completely new (R) gets the remaining time, which may not be much.

I can only talk about myself, but if you're a decent programmer, you have a good chance of getting a R&D job via ordinary job interview. Look for firms that inspire you, and let them know about yourself. Don't ignore small, innovative firms; if you get to work at such, you can actually affect what they and you are doing (not so with giant corporations).

If you meant academic research, then it's definitely less work to first get the degree and then a job at the university than trying to do any meaningful research alone, without a degree, unless you're a genius.

Title: How do I get into R&D?


问:
Writing a game engine using javascript
..by this I mean a logic handler for a chess game. Basically validating a move and checking if somebody has won.

Now ignore the complexity of the game(if you can..) I'd like some sort of psuedo code on how it would look using callbacks in javascript.

For arguments sake imagine once a move is completed in the browser it sends a JSON object of the piece that has been moved and to which space it has been moved to. On the server we have access to a JSON object which contains data for the complete board. With this information I expect to pass it in to my engine and determine from the output if the move is valid..and if so is it a winning move?

I'm not looking for any specific logic on how to determine a move in chess -> just a kind of psuedo example/template of the flow of the game using the above paragraph as a guide to what must be done.

The reason for this is I would like to understand how callbacks can be used to produce something of this nature as opposed to synchronous code.

答:
Have I interpreted it correctly that you have a server that records all of the game board layouts, and each game has two clients that can see the board and move the pieces?

So there's a server program and a client program:

Client player moves piece to destination square:

```<code>If moving piece from piece.square to destination is an invalid move then
    Alert "You cannot move that piece there."
Else
    Send (game, piece, destination) to server
    While within 30 second timeout
        Listen for response
    If no response received then
        Alert "Cannot contact server."
    Else
        If response is failure then
            Alert "You cannot move that piece there."
        Else
            Move response.piece to response.destination
            If response.check is check then
                Alert "You put them in check."
            ElseIf response.check is checkmate then
                Alert "You win!."
                End game
            Wait for the server to say it's your turn
</code>```

Server receives a move:

```<code>Retrieve board for game
If moving piece from piece.square to destination is an invalid move then
    Send (failure) to client
Else
    Move piece to destination
    Save game board
    Check = check if player is safe, in check or in checkmate
    Send (piece, destination, check) to client
    Send (your move, check) to other client
</code>```

Client waits for their turn:

```<code>Until a response is received
    Listen for response
If response.check is check then
    Alert "You are in check."
If response.check is checkmate then
    Alert "You lose!"
    End game
Let player make their move.
</code>```

The program double-checks that the move is valid.  It checks at the client end to prevent sending an obviously invalid move to the server and wasting the player's time.  It checks at the server end to ensure a player isn't sending hacked packets to make illegal moves.  The server returns the move to the client because that what the server has acted upon, and accurately represents the state of the game.

Title: Writing a game engine using javascript

Body:
Have I interpreted it correctly that you have a server that records all of the game board layouts, and each game has two clients that can see the board and move the pieces?

So there's a server program and a client program:

Client player moves piece to destination square:

If moving piece from piece.square to destination is an invalid move then
    Alert "You cannot move that piece there."
Else
    Send (game, piece, destination) to server
    While within 30 second timeout
        Listen for response
    If no response received then
        Alert "Cannot contact server."
    Else
        If response is failure then
            Alert "You cannot move that piece there."
        Else
            Move response.piece to response.destination
            If response.check is check then
                Alert "You put them in check."
            ElseIf response.check is checkmate then
                Alert "You win!."
                End game
            Wait for the server to say it's your turn

Server receives a move:

Retrieve board for game
If moving piece from piece.square to destination is an invalid move then
    Send (failure) to client
Else
    Move piece to destination
    Save game board
    Check = check if player is safe, in check or in checkmate
    Send (piece, destination, check) to client
    Send (your move, check) to other client

Client waits for their turn:

Until a response is received
    Listen for response
If response.check is check then
    Alert "You are in check."
If response.check is checkmate then
    Alert "You lose!"
    End game
Let player make their move.

The program double-checks that the move is valid.  It checks at the client end to prevent sending an obviously invalid move to the server and wasting the player's time.  It checks at the server end to ensure a player isn't sending hacked packets to make illegal moves.  The server returns the move to the client because that what the server has acted upon, and accurately represents the state of the game.


问:
Is wrapping third-party API calls a design smell?
Five methods within my API call the same third-party method. In trying to abide by DRY, does it make sense to wrap this call in a private method?</p>

答:
I would recommend you leave your code as-is.

However, say, if you're calling 20 differing methods in third-party code on 1000 lines of your code, perhaps creating a thin layer between you and your third-party code may save you (or someone else) some pain the future, in the event that the third-party code changes and you have to update all your calls.

OwnerDisplayName: Mike Atlas


问:
Plagued by indecision - how to choose technologies to use for projects?
I have always been fascinated with the newest and best technologies available.  I graduate from college this year, and over the course of the past few years, I have spent a lot of time learning new programming languages, web frameworks, Linux distributions, IDEs, etc., in an effort to find the best of each.

I have installed and played around with Ubuntu, Gentoo, Debian, Arch Linux, SUSE, VectorLinux, Puppy Linux, Slackware, and Fedora, I have spend a good amount of time in Vim and Emacs, and have played around with Visual Studio, Eclipse, NetBeans, gedit, and several more obscure ones.

I have played with all sorts of languages - I started with the common ones like C, Java, Visual Basic, but always heard that they were "bad" (for relative definitions of bad). I then discovered the scripting languages and have quite a bit of experience in PHP, Perl, Python, and Ruby. Then I heard that functional languages are where it's at, so I played around with Scheme, Lisp, Haskell, Erlang, and OCaml. I've played around with obscure languages like Forth and J. When I do web development, I go back and forth between frameworks and languages. Should I use plain PHP, Ruby on Rails, Django, CakePHP, CodeIgniter, Yii, Kohana, or make my own?

I have a very broad and shallow knowledge of computer science. As soon as I have learned a useful amount of one technology, I see something else shiny and go after it. My progression often goes like this: "Perl is better than PHP, but wait, Python is better than Perl. Oh, but now I see that Ruby has the power of Perl and it is cooler than Python. Well, now that I have seen a little of Ruby, it is too complicated. Python is cleaner. Oh, but it is too hard to deploy Python, so I should use PHP if I want to do real web development." And so on and so forth.

What  technology should I use for projects? Should I just pick one language/framework/IDE and sort of forget about the other things that are available for a while? I don't have all that much in the way of completed projects, because I never stay with something long enough to finish it.

答:
Should I just pick one language/framework/IDE and sort of forget about the other things that are available for awhile?

Basically, yes.

If you keep flitting between technologies, you'll never get the depth of experience that you need to be an effective developer in any of them.  And when all is said and done, while no technology is perfect, many of them are good enough to get the job done ... depending on the job.

I don't have all that much in the way of completed projects because I never stay with something long enough to finish it.

You'll need to learn to deal with that, especially if you aspire to be a professional software developer.  No boss is ever going to want to employ someone who doesn't have the self-discipline to finish projects.


答:
The reason why you should always wrap the api is:

The api you're using was designed for 50 different uses, while you're choosing just one of them into use. So your function prototypes will look considerably different because the scope of the projects is different.

Because you can choose smaller scope, your wrapped api necessarily is considerably simpler and you get huge abstraction benefits by wrapping it

Obviously just manually copy-pasting the prototypes is not going to work. You actually need to make it simpler.

Title: Is wrapping third-party API calls a design smell?

Body: Five methods within my API call the same third-party method. In trying to abide by DRY, does it make sense to wrap this call in a private method?</p>


答:
You appear to have a very complex task at hand, and need to treat it with the respect it deserves. Are you sure you don't have a tiger by the tail thinking of it as a domestic cat. The outcome of such a mistake is fairly predictable.

The documentation will take a while because its a big complex job requiring complex documents. The UML gets complex and hard to understand because the job is complex and hard to understand. The job needs to be treated as a big complex job, until proven otherwise.

Therefore my advice is start by 'employing' a Project Manager and a Business Analyst. If you are 'it', put away you compiler and read a book on the above two jobs and perform those roles, before being a software developer.

Title: How to tackle complex business rule and logic?

Body:
I have a domain expert to work with, but he would throws a lot of details to me verbally.  The business logics are complex, business rules change often, the business process is long and multi-ending / intermediate wait-state.  There are a lot of cases to deal with (because there are many states for the account, product and subscription).

What's the best way to deal with it?  BPMN diagram isn't even low level enough to explain.  Written documentations are time consuming to write and read.  UML state diagram can become crazily complex very soon.

Any advice would be appreciated.


问:
Difference between Idiom and Design Pattern?
What is the difference between idiom and design-pattern? It seems that these terminologies overlap somewhere; where exactly, I don't know.  Are they interchangeable? When should I use what?

Here is a list of C++ Idioms. Can I call them design patterns?

Wikipedia defines,

Programming Idiom as a low-level Design Pattern

What does it mean? What does "low-level" mean here?

This question is inspired from another question : https://stackoverflow.com/questions/7343531/are-the-some-design-patterns-language-dependent

答: the point of an Idiom is to be an idea or concept that spans programming languages, it is a way of doing things and a process that works without much conceptual restructuring when you take it from one and stick it in another, like the lowly bubble sort. Design patterns are specific implementations of an idiom, or extentions of the idea to fit into a language, you therefore have the javascript design pattern of the event-listener idiom etc.</p>

OwnerDisplayName: Nawaz

OwnerDisplayName: shortstick


答:
I'm not 100% sure, but idioms are simply terms pertaining to a certain field.
When you say "design patterns", you think of "Observer Pattern" "Chain of responsability" "Visitor pattern" "factory". These are common patterns used to solve common problems in programming.
Look here for a comprehensive list:
http://en.wikibooks.org/wiki/C++_Programming/Code/Design_Patterns</p>

Title: Difference between Idiom and Design Pattern?

Body:
What is the difference between idiom and design-pattern? It seems that these terminologies overlap somewhere; where exactly, I don't know.  Are they interchangeable? When should I use what?

Here is a list of C++ Idioms. Can I call them design patterns?

Wikipedia defines,

Programming Idiom as a low-level Design Pattern

What does it mean? What does "low-level" mean here?

This question is inspired from another question : https://stackoverflow.com/questions/7343531/are-the-some-design-patterns-language-dependent

OwnerDisplayName: EddieBytes


答:
What does it mean? What does "low-level" mean here?

I take it to mean that it is not a high level, abstract way to model your application or components of your application, but instead a clever or common use of language semantics.

for example, setting a variable if it evaluates to false (commonly used to set nil variables conditionally):

```<code>var ||= some_default_value
</code>```

Body:
What does it mean? What does "low-level" mean here?

I take it to mean that it is not a high level, abstract way to model your application or components of your application, but instead a clever or common use of language semantics.

for example, setting a variable if it evaluates to false (commonly used to set nil variables conditionally):

var ||= some_default_value

OwnerDisplayName: Ed S.


答: Design patterns are not usually language specific.  Language idioms tend to depend on particular feature of a language (or class of languages) or work around a specific deficiency in said language(s).</p>

OwnerDisplayName: BioBuckyBall


答:
I have a very broad and shallow knowledge of computer science.

This is your issue. Pick a language and stick with it. What are you developing? Want a wide range of coverage? Pick PHP. Want to shoot your career in the foot? Pick Ruby. (Kidding, maybe).

There is no "correct" language to choose, pick the one that you are comfortable with.

Title: Plagued by indecision - how to choose technologies to use for projects?

Body:
I have always been fascinated with the newest and best technologies available.  I graduate from college this year, and over the course of the past few years, I have spent a lot of time learning new programming languages, web frameworks, Linux distributions, IDEs, etc., in an effort to find the best of each.

I have installed and played around with Ubuntu, Gentoo, Debian, Arch Linux, SUSE, VectorLinux, Puppy Linux, Slackware, and Fedora, I have spend a good amount of time in Vim and Emacs, and have played around with Visual Studio, Eclipse, NetBeans, gedit, and several more obscure ones.

I have played with all sorts of languages - I started with the common ones like C, Java, Visual Basic, but always heard that they were "bad" (for relative definitions of bad). I then discovered the scripting languages and have quite a bit of experience in PHP, Perl, Python, and Ruby. Then I heard that functional languages are where it's at, so I played around with Scheme, Lisp, Haskell, Erlang, and OCaml. I've played around with obscure languages like Forth and J. When I do web development, I go back and forth between frameworks and languages. Should I use plain PHP, Ruby on Rails, Django, CakePHP, CodeIgniter, Yii, Kohana, or make my own?

I have a very broad and shallow knowledge of computer science. As soon as I have learned a useful amount of one technology, I see something else shiny and go after it. My progression often goes like this: "Perl is better than PHP, but wait, Python is better than Perl. Oh, but now I see that Ruby has the power of Perl and it is cooler than Python. Well, now that I have seen a little of Ruby, it is too complicated. Python is cleaner. Oh, but it is too hard to deploy Python, so I should use PHP if I want to do real web development." And so on and so forth.

What  technology should I use for projects? Should I just pick one language/framework/IDE and sort of forget about the other things that are available for a while? I don't have all that much in the way of completed projects, because I never stay with something long enough to finish it.


答:
I wouldn't put too much currency in the Wikipedia definition.

At the very least an idiom is language-specific whereas a design pattern strives, or should strive, to be language-agnostic. Going further, idioms are usually conventions for enhancing readability, or are the superior alternative (on some technical merit) when there is more than one way to do something. All of those things are related on how ideas are expressed (clarity, verbosity, conciseness), but not to the ideas themselves.

On the other hand, design patterns are the essence of a recurring idea, an idea that a priori can be expressed in any languages that lends itself to it. The Visitor is an implementation of double-dispatch relying on single-dispatch and overloading and this can be used in any language that has single-dispatch and overloading. Knowing about the pattern doesn't help write more expressive or more readable code, it helps solving the related problem. There is nothing idiomatic about it because for instance there is no canonical form of the Visitor in e.g. C++.

OwnerDisplayName: Luc Danton


答:
The normal English language definition of Idiom. Is a phrase whose accepted meaning is not contained in the words used. Examples would be "Raining cats and Dogs" or "Where's the Beef?"

In programming languages it usually refers to a syntactical shortcut that does something not immediately obvious from the code itself but which is used often enough that other programmers recognize the meaning instantly.

Perl is perhaps the most idiom rich language. With constructs like:

```<code>while (<IN>) {
    print $_
}
</code>```

Whose meaning is obvious to an experienced perl programmer but a mystery to anyone else

Body:
The normal English language definition of Idiom. Is a phrase whose accepted meaning is not contained in the words used. Examples would be "Raining cats and Dogs" or "Where's the Beef?"

In programming languages it usually refers to a syntactical shortcut that does something not immediately obvious from the code itself but which is used often enough that other programmers recognize the meaning instantly.

Perl is perhaps the most idiom rich language. With constructs like:

while (<IN>) {
    print $_
}

Whose meaning is obvious to an experienced perl programmer but a mystery to anyone else

OwnerDisplayName: James Anderson


答:
Here's an example of an idiom (in C#) for handling an event. You're not allowed to fire an event if it doesn't haven't any handlers attached, so the idiom is to always check this first.

Therefore the general idiom for handling events becomes:

```<code>EventHandler handler = this.MyEvent;
if ( null != handler ) { handler( param1, param2 ); }
</code>```

This idiom is specific (although not exclusive) to the C# language.

More generally however, the C# eventing mechanism is an example of the observer design pattern which could be implemented in any language.

Body:
Here's an example of an idiom (in C#) for handling an event. You're not allowed to fire an event if it doesn't haven't any handlers attached, so the idiom is to always check this first.

Therefore the general idiom for handling events becomes:

EventHandler handler = this.MyEvent;
if ( null != handler ) { handler( param1, param2 ); }

This idiom is specific (although not exclusive) to the C# language.

More generally however, the C# eventing mechanism is an example of the observer design pattern which could be implemented in any language.

OwnerDisplayName: cxfx


答:
An idiom is an idea to work around the quirks of a language.  Some examples that come to mind are any of the C++ idioms you linked in the original question.  They solve a common problem in that language in a canned way.

A design pattern is similar, in that it solves a common problem.  But the ideal design pattern is based on common language features, and thus is language agnostic.

There is a continuum between idioms and design patterns, though, just as there is from low-level to high-level languages.

The Visitor pattern is a good example; if there were only one language that only supported single dynamic-dispatch, then we might consider the Visitor pattern an idiom of that language.  But there are whole hordes of languages that don't directly support multiple-dispatch.  Hence, the Visitor pattern was born.

The Observer pattern also comes to mind - C# directly supports it, so it doesn't need the common work-around form of the pattern.

An example going the other direction is OO features (inheritance, polymorphism, etc).  C doesn't directly support them.  If more languages were like C, then we might develop design patterns to implement v-tables, type-safety, etc.  Since plenty of languages support those feature, we'd call any common solution in C an idiom, rather than calling the generalized solution a design pattern.

OwnerDisplayName: Merlyn Morgan-Graham


答:
I think that this is not unusual. All the litrature in requirements gathering can qualify for an answer here but you can see this elsewhere of course.

On a high level, I would approach the problem this way:

Clearly identify the problem at hand.

Define objective of the system.

Now you have a scope to work with. Identify the main business processes.

For each business process in scope, define: inputs, outputs, actors and business rules (pre conditions, post conditions, rules, exceptions)

Use BPMN to document essential business flow from a business perspective to show how processes relate

At this point, you have documented your understanding of the business. Confirm it and Proceed from this point with your software design to solve the problem.

Time spent on analysis is well worth it.


答:
I would focus on use-cases and user-stories.  I could document them, perhaps in a wiki, and give each one an ID (like UC00001).  Then when I wrote unit tests and/or integration tests, I'd label them with the use case they inform.

Then when I get to two unit tests that can't both pass because they're mutually exclusive, I'd throw those two use cases back at the domain expert and have him/her reconcile them.  That's the only way I can think of to keep it all straight.


答:
There are a number of specifications by the open group, ISO, the IETF and ITU that are sufficiently unambiguous for highly competitive companies to interoperate quite successfully. There are a number of specifications that are the basis of contracts or laws where millions of dollars are at stake.

So specifications may not be "perfect". However that is because humans are not perfect. For example it is unambiguous that HTTP should use a "Referer" header - the correct spelling is in fact "Referrer".

The English language is capable of being unambiguous, but humans are capable of making mistakes - including ambiguity.

In addition it may be helpful to be deliberately ambiguous for details that have not been finalised or may need to be updated in the future. For example a specification may specify a "hash" rather than specifically specifying md5, sha1, crc32 etc.