问:
Why does PHP have interfaces?
I noticed that as of PHP5, interfaces have been added to the language. However, since PHP is so loosely typed, it seems that most of the benefits of using interfaces is lost. Why is this included in the language?</p>

答:
Interfaces are useful for dependency injection much more so than concrete. As a barebones example :

```<code>interface Istore {
  public function save();
}

class Article_DB implements Istore
{
  public function save($data)
  {
    // do save to format needed.
  }
}

class Article
{
   private $content;

   public function content($content)
   {
     $this->content = $content;
   }

   public function save(Istore $store)
   {
     $store->save($this->content);
   }
}

$article = new Article();
$article->content('Some content');

$store = new Article_DB();
$article->save($store);
</code>```

Now say if your needs change and you want to save to a pdf. You could create a a new class for that purpose instead of polluting the Article class.

```<code>class Article_PDF implements Istore
{
  public function save($data)
  {
    // do save to format needed.
  }
}

$article = new Article();
$article->content('Some content');

$store = new Article_PDF();
$article->save($store);
</code>```

The Article class now has a contract that classes it uses to save must implement the Istore interface. It does not care where it saves or how it saves.

Title: Why does PHP have interfaces?

Body:
Interfaces are useful for dependency injection much more so than concrete. As a barebones example :

interface Istore {
  public function save();
}

class Article_DB implements Istore
{
  public function save($data)
  {
    // do save to format needed.
  }
}

class Article
{
   private $content;

   public function content($content)
   {
     $this->content = $content;
   }

   public function save(Istore $store)
   {
     $store->save($this->content);
   }
}

$article = new Article();
$article->content('Some content');

$store = new Article_DB();
$article->save($store);

Now say if your needs change and you want to save to a pdf. You could create a a new class for that purpose instead of polluting the Article class.

class Article_PDF implements Istore
{
  public function save($data)
  {
    // do save to format needed.
  }
}

$article = new Article();
$article->content('Some content');

$store = new Article_PDF();
$article->save($store);

The Article class now has a contract that classes it uses to save must implement the Istore interface. It does not care where it saves or how it saves.


问:
Should I start developing code before planning out the interface?
I'm starting a gaming project on the side of my normal school/work projects and I'm wondering if I should start planning out the user interface before starting an actual project in code.

I see some pros/cons to doing both first and was wondering what advice some seasoned developers could suggest.

答:
At the end of the day, your UI drives the requirements for your application and your code provides solutions for them.

So yes, I would absolutely plan out my UI prior to coding. I'd also write up a technical design once the UI design has been completed prior to coding, but that's another discussion altogether ;)

Try pencil for UI design. It makes me happy inside.

ContentLicense: CC BY-SA 3.0


问:
Where should heavy development assets like specification documents and multimedia editor source files be stored?
It's not uncommon where I'm working on a site that includes things like binary (or effectively undiffable due to factors outside my control) specification documents (e.g., PDFs, Word Documents, Excel Spreadsheets) and multimedia source files (e.g., FLA source files, Photoshop files, Illustrator files).

How should these be stored?

My instinct is to just throw them into git. Storage is cheap, but it does make the clone operation take much, much longer than it otherwise would.

A potential alternative would be to use a wiki. I've tried it in some cases but never ran into a case where the wiki format's inherent strengths (layperson-accessible version history and easy access to latest copies) have or would have led to enough benefit to justify the additional work in maintaining the wiki.

The third option is to just let them hang out locally and in email threads.

So what approach should I take to this?

答:
I'd say it depends how you are using that data:

if you are improving it heavily and frequently, use the advantages of modern revision control systems. But think about the structure and modularity of your repositories (who is going to use the revision control system in what way).

if the documents are barely updated but heavily used for look-ups, a wiki is a great solution and worth the effort.

if neither is the case, use a cheap and simple solution. I'd still go with a local place instead of email-attachment-chaos, but a (samba-)directory or files/links within your wiki/issue-tracker/wordpress/... will do.


答:
The approach that you take depends on your team and the process methodology that you are using. Whatever fits best into your workflow is what you should be doing. You do want these artifacts to be versioned and managed, just like the code. Email doesn't easily provide that, while a version control system and most wiki software does. Ultimately, you want to be able to link a specific revision of the software with specific and accurate artifacts that describe that revision of the software.

You mention that you create some documents in Microsoft Office. Office products have change and review tracking built in. Although you still need to version your documents on top of this, the changing tracking will allow you to see how a document has progressed over time. I would recommend learning about this feature and seeing how you can make effective use of it within your process.

You also mention PDFs. I'm not sure how you use PDFs, but if they are generated from other files, version only the native file. It probably doesn't take that long to go from a native file into a generated PDF. This really goes for anything that gets generated from other sources. Don't keep generated products, only what you use to generate them as a versioned artifact. It'll save space and help you maintain your sanity.

Title: Where should heavy development assets like specification documents and multimedia editor source files be stored?

Body:
It's not uncommon where I'm working on a site that includes things like binary (or effectively undiffable due to factors outside my control) specification documents (e.g., PDFs, Word Documents, Excel Spreadsheets) and multimedia source files (e.g., FLA source files, Photoshop files, Illustrator files).

How should these be stored?

My instinct is to just throw them into git. Storage is cheap, but it does make the clone operation take much, much longer than it otherwise would.

A potential alternative would be to use a wiki. I've tried it in some cases but never ran into a case where the wiki format's inherent strengths (layperson-accessible version history and easy access to latest copies) have or would have led to enough benefit to justify the additional work in maintaining the wiki.

The third option is to just let them hang out locally and in email threads.

So what approach should I take to this?


答:
we're using a wiki for this (confluence), used to be versioning, and it's been an extreme pleasure to work with. The level of organization a wiki gives you is just not reachable using directory trees (what you would be doing using git/samba) or email. Also think about scalability and the future: git might work now, but would it also in 10 years, when there are x more documents?
Another huge benefit: have a quick idea? just find a suitable place and start typing. You don't even have to publish in the first place. </p>


问:
Why doesn't Google use GWT in most of its applications?
Google created Google Web Toolkit (GWT) and doesn't use it when building their own web applications.

Does this mean GWT is not suitable for building dynamic applications? Or have caching problems? Or have RPC problems? Or are there other concerns that prevent Google from using this technology?

EDIT: I don't say here that Google don't ever used GWT in any app, but What I am want to say, why they are not using it in a wide range?

答:
What you are talking about is a concept commonly known as:

eat your own dog food

However, not all companies can really be their own customers. For example, consider Microsoft. SQL Server in previous versions were not as powerful as now for enterprise purposes. Thus Microsoft couldn't use it and it had to use something like Oracle, or DB2 for enterprise level developments.

I mean, the first point is that not everybody should eat his/her own dog food.

The second point is that, how can you ever get sure that Google is not using GWT? I mean, after all, what it produces is JavaScript and they can have it customized, so that it doesn't contain any kind of signature to denote the usage of GWT. In other words, almost any platform on the web can be configured such that no-one understand what language, OS, web server, etc. has been used to create it.

For example, sites built with ASP.NET and running on IIS have an HTTP Response header field known as X-Powered-By: ASP.NET, or something like that. But you can easily delete these headers from IIS. Also websites created by ASP.NET usually have paths ending with .aspx files. However, this also can be easily changed to extension-less URLs with the concept of URL Rewriting.

So the second point I'm emphasizing, is that, you can't ever for sure say that Google is not using GWT. Maybe it does.


答:
Well, firstly, most Google products are older than GWT. You don't re-write a perfectly good product every time a new library is released.

Secondly -- and this is really my personal opinion -- is that GWT is to Javascript what ASP.NET (classic) is to HTML. It's great for simple interfaces, but if you need to do anything complex, it can be a bit of a pain.

A lot of projects at Google are written using the Closure Javascript library. Closure stays closer to the "metal" of the browser, while still providing powerful templating and many other features that a complex web application requires.

Having said that, there are projects within Google that use GWT. The AdWords frontend is one that comes to mind.

Title: Why doesn't Google use GWT in most of its applications?

Body:
Google created Google Web Toolkit (GWT) and doesn't use it when building their own web applications.

Does this mean GWT is not suitable for building dynamic applications? Or have caching problems? Or have RPC problems? Or are there other concerns that prevent Google from using this technology?

EDIT: I don't say here that Google don't ever used GWT in any app, but What I am want to say, why they are not using it in a wide range?


问:
Do you prefer conciseness or readability in your code?
Language shortcuts can often be used to make code more concise.

For example, ternary and null coalescing operators can reduce the amount of code, but arguably to the detriment of readability:

In C#:

```<code>Person newGuy = new Person();
if (boss == null) {
    newGuy.Boss = GetDefaultBoss();
} else {
    newGuy.Boss = boss;
}
</code>```

is functionally equivalent to:

```<code>Person newGuy = new Person();
newGuy.Boss = boss ?? GetDefaultBoss();
</code>```

but obviously a lot more verbose.

Where do you draw the line when it comes to conciseness vs readability?

答:
I would say I prefer readability, though that sometimes means using concise code.  (I.e. ternary for relatively simple conditionals inside a larger conditional block.)

Basically, if it is unnecessarily difficult to understand, don't do it.

ContentLicense: CC BY-SA 2.5


问:
Should every git commit leave the project in a working state?
I'm curious to know what the prevailing best practice is. Should git commits be enforced such that the project is in a working state (builds properly, all tests pass etc), or is committing broken code OK?

For example, if you waive this requirement you can be more flexible with commits (use them as logical chunks, even though the app is not in a working state etc). However if you enforce it you gain the flexibility of being able to cherry-pick any given commit later on...

答:
Assuming you are using branches, and good commit messages, committing "broken" code on a branch with a commit message that makes that clear would be fine, so long as your team agree that it's a good working practice.

You also clone the git repository locally, so you might well just have a local branch with local commits not pushed to origin where you're committing "broken" code as you go along; then, when you have it all working, you could merge it in to master or some other branch, and delete your working branch with the various "broken" commits.

To me, it's all about agreeing with your team what is acceptable; some teams won't accept broken code even on a branch, others will.

OwnerDisplayName: Suan

ContentLicense: CC BY-SA 4.0

OwnerDisplayName: Kenny


答:
Since git commit only affects your own copy of the repository, there's no need for the project to be in a working state after every commit.  Go ahead and commit whenever you want to save the work you've done.  Probably a good rule of thumb is that a commit is appropriate when you can describe the changes you've made in the commit message.

It's git push that affects other users.  Policies for what should be pushed are a matter for your development team to decide.  Pushing non-working code onto the main branch is presumably a no-no, but it's probably ok to push non-working code onto a separate branch (as long as nobody else is going to try to do a build from that branch).

Title: Should every git commit leave the project in a working state?

Body:
I'm curious to know what the prevailing best practice is. Should git commits be enforced such that the project is in a working state (builds properly, all tests pass etc), or is committing broken code OK?

For example, if you waive this requirement you can be more flexible with commits (use them as logical chunks, even though the app is not in a working state etc). However if you enforce it you gain the flexibility of being able to cherry-pick any given commit later on...

OwnerDisplayName: Keith Thompson


答:
We generally follow both approaches. In the local repository on my box I commit all I want. When it's time to push to my team's central repo, I first do an interactive rebase and mold my commits into logical packages. Typically one commit per story, with the story (or defect) id included in the comment (we are a kanban based shop).

Then on our central repro we have Jenkins listening and it kicks off the build and all tests. If anything fails, we generally allow people to try and get the build fixed with another commit. If it's not looking good, reverting the faulty commit is easy to do.

OwnerDisplayName: Matt Greer


答:
We are using git flow at work, and we also commit unfinished or broken code - as it only lands in local or remote branches made for that specific problem. Only once the task is finished, it gets merged into the develop branch (which represents the current working copy in the flow model). That way, we also can collaborate on the code (some coworkers are in another city, including the project lead) and help each other.

However, it depends on how you and your coworkers are thinking. Personally, I think branch commits are okay, as you might need a history of changes with a bigger refactor or similar.

OwnerDisplayName: Femaref


答:
Use your local clone of the repository for whatever makes you comfortable while developing.

I commit broken code regularly, and when I am ready to make the code available to other developers, I use a great feature:

```<code>git rebase -i HEAD~4
</code>```

This allows me to compress my intermediate (in this case 4 of them), possibly broken, commits into one good commit. You will be presented with an editor allowing you to choose how those commits are compacted. Typically I marked the first commit the 'pick' commit, and mark the others 'squash'.

Then I can push that one atomic commit, or in fact what I do if my new feature is really ready, is use 'git cvsexportcommit' to get my work into the existing CVS repo.

Body:
Use your local clone of the repository for whatever makes you comfortable while developing.

I commit broken code regularly, and when I am ready to make the code available to other developers, I use a great feature:

git rebase -i HEAD~4

This allows me to compress my intermediate (in this case 4 of them), possibly broken, commits into one good commit. You will be presented with an editor allowing you to choose how those commits are compacted. Typically I marked the first commit the 'pick' commit, and mark the others 'squash'.

Then I can push that one atomic commit, or in fact what I do if my new feature is really ready, is use 'git cvsexportcommit' to get my work into the existing CVS repo.

OwnerDisplayName: memetech


问:
Daily standups- yea or nay?
How valuable (or not) do you think daily stand-up meetings are?

If you're not familiar with it, this refers to a daily meeting that is part of Scrum adherents (and some other agile methodologies).  The idea is that you hold a daily meeting, timeboxed to 15 minutes, and in which everyone must stand (to encourage people to be to-the-point).

In the meeting, you go around the room and each say:
- What you did yesterday
- What you plan to do today
- Any blockers or impediments to your progress.

Do you think this practice has value?  Has anyone worked at a place that's done it, and what did you think?

答:
On the plus side, these meetings can have the effect of boosting productivity in terms of achieving urgent and immediate business objectives.

On the negative side, these meetings (daily: what did you do? what are you going to do? what's in your way?) discourage what we might call "google-time", or working/learning on a side project that has no immediate impact on the business, but could have significant impact down the line.

One product that I did the prototype for would never have passed the daily meeting test, and thankfully, my old manager gave boatloads of freedom to work on my own, and now the real product is live. But now that the old manager has left, and a new one has entered who embraces the concept of a daily scrum, I don't see how I could have ever developed the prototype in the daily scrum environment.

Title: Daily standups- yea or nay?


答:
Two of the great benefits of version control are that it lets developers recover previous versions of their work, and it lets developers try different, possibly conflicting changes at the same time. Version control gives developers the freedom to try ideas that might fail.

Developers should be encouraged to branch and commit their work regularly, whether it builds or not. To refuse to allow branching or broken commits is to hamstring your developers and make poor use of your tools.

That said, it's an excellent practice to require that commits to certain branches always build. Many organizations go further and prohibit developers from committing to certain branches at all. For example, developers might be required to merge their work back to the main development branch, but only the lead developer might be allowed to merge those changes from development to the production branch.


问:
Does it always require a lot of programming practice before you really master an algorithm?
I have programmed for several years. And I found it is always difficult to master an algorithm(What 'master' mean here is to understand how the algorithm works and could implement independently in some programming language).

I could implement some easy algorithms(such as bubble sort, binary search, basic graph traversal algorithms such as DFS, BFS, basic dynamic programming problems such as ). But it is very difficult for me to master some advanced algorithms such as KMP, max-flow.

I could understand the basic idea behind the algorithms. But I am usually stucked at implementation and forget the algorithm in a while.

So my questions are:

what is a reasonable procedure to learn/master a new algorithm?

Do I need practice it again and again in platform such as USACO, topcoder to master it? Or is there any better way?

答:
I think on a more abstract level about algorithms than in a programming language: the essential ideas, mechanisms and bigO-complexity in space and time do not require the detailed level a programming language has.

Hence I think you shouldn't force it upon yourself to being able to implement every algorithm in one pass. Rather know a large set of algorithms or even more abstract algorithmic concepts. Then you can decide which algorithm to choose, and if you do not find an appropriate one in a library, only then spend more time  implementing it.

To learn these algorithms and abstract algorithmic concepts, rather read a book or lecture slides about algorithms, see e.g. https://stackoverflow.com/questions/366418/resources-and-tutorials-to-get-started-on-algorithms.


答:
I think delnan's comment is pretty much the answer you need. To add something from my side, i would say every requirement or code you implement is an Algorithm in itself. Suppose you want to add 100 employees to a company database and extract the one's with salary less than 5k/month. The algo for this will be :-

```<code>input:
a list of 100 employees, EmployeeTable
parameter to sort, SalaryParam
output:
a sortedList of employees, EmployeeTableWithFilter
----
define variables :
an integer count, i=0
----
While i < 100, do :
if List[i].Salary == SalaryParam
    EmployeeTableWithFilter.Add(List[i])
    i++
    return
otherwise,
    i++
    return
-----------------
</code>```

I am not that good at Algorithm but i hope you can buy what i am trying to explain. In essence, an Algorithm is a generalized and effective method expressed as a finite list of well-defined instructions for calculating a function. So, every function or program you write is an algorithm in itself

Title: Does it always require a lot of programming practice before you really master an algorithm?

Body:
I have programmed for several years. And I found it is always difficult to master an algorithm(What 'master' mean here is to understand how the algorithm works and could implement independently in some programming language).

I could implement some easy algorithms(such as bubble sort, binary search, basic graph traversal algorithms such as DFS, BFS, basic dynamic programming problems such as ). But it is very difficult for me to master some advanced algorithms such as KMP, max-flow.

I could understand the basic idea behind the algorithms. But I am usually stucked at implementation and forget the algorithm in a while.

So my questions are:

what is a reasonable procedure to learn/master a new algorithm?

Do I need practice it again and again in platform such as USACO, topcoder to master it? Or is there any better way?

Body:
I think delnan's comment is pretty much the answer you need. To add something from my side, i would say every requirement or code you implement is an Algorithm in itself. Suppose you want to add 100 employees to a company database and extract the one's with salary less than 5k/month. The algo for this will be :-

input:
a list of 100 employees, EmployeeTable
parameter to sort, SalaryParam
output:
a sortedList of employees, EmployeeTableWithFilter
----
define variables :
an integer count, i=0
----
While i < 100, do :
if List[i].Salary == SalaryParam
    EmployeeTableWithFilter.Add(List[i])
    i++
    return
otherwise,
    i++
    return
-----------------

I am not that good at Algorithm but i hope you can buy what i am trying to explain. In essence, an Algorithm is a generalized and effective method expressed as a finite list of well-defined instructions for calculating a function. So, every function or program you write is an algorithm in itself


答:
This workflow gives good results for most large software projects that follow some version of the the Atlassian Git Flow model

Each merge to the branch from which the release is cut must leave the project in a working state.  In Git Flow, this is called the master branch, and usually only the release engineers can merge code there.  Run all your tests for each merge;

Each merge to the mainline development branch (in Git Flow it's called develop branch, but many use the master branch for that purpose) should leave the project in a working state (and it must build at least).  Run most of your tests, except the longest running ones, accept some flakiness, don't run unaffected tests.  But sometimes you'll merge two branches that both pass tests, but their merge is broken.  This is okay.  You'll fix this soon, and you'll make sure your release branches are good.

Each other individual commit has a primary goal of explaining why the change is made, and what is it for, and what parts of the project it affected.  All other goals, such as leaving the project in a working state, are optional.


问:
Unit testing newbie team needs to unit test
I'm working with a new team that has historically not done ANY unit testing.  My goal is for the team to eventually employ TDD (Test Driven Development) as their natural process.  But since TDD is such a radical mind shift for a non-unit testing team I thought I would just start off with writing unit tests after coding.

Has anyone been in a similar situation?  What's an effective way to get a team to be comfortable with TDD when they've not done any unit testing?  Does it make sense to do this in a couple of steps?  Or should we dive right in and face all the growing pains at once??

EDIT

Just for clarification, there is no one on the team (other than myself) who has ANY unit testing exposure/experience.  And we are planning on using the unit testing functionality built into Visual Studio.

答:
I've managed to convince my whole company to switch to TDD. It wasn't easy, but it was well worth the effort: the quality of the code went up after the transition, and now nobody imagines going back to the horrible, cowboy coding times.

Explain, explain, explain. You don't want your team to write tests. You want your team to want to write tests. This means that they should fully understand why they should be doing it, what are the benefits, and how this will make their job much easier. Red, Green, Refactor, writing a regression test as proof that a bug has been fixed, etc. You have to convince them the whole thing makes sense before you ask them to write any code.

Go for the real thing (first tests, then code). Writing tests after the code hardly makes any sense, as you will never know if they actually work (and people do write buggy test cases). My intuition is that the amount of effort you need to go from no tests to tests first is much less than what you need to go form no tests through code first to tests first, so you may as well skip the middle step.

Start with regression tests. These are pretty simple to understand, and they give instant gratification. Of course, this assumes that the code is properly modularized and easily testable. If not, skip this step.

Take baby steps. TDD takes some time to get used and may be frustrating at first. Try to introduce testing in a brand new project or component, ideally: something not very important. You want to avoid at all costs the situation when there's something really important to be done really quickly and the programmers feel that TDD is getting in the way.

When the team starts being comfortable, have all new functionality written in a TDD manner. This depends on the size of your project, but after some time you should get a pretty good coverage, with only some legacy parts of your project written in the old way.

By this point, the team should already understand and embrace TDD, and the legacy (non TDD) stuff should be considered difficult and annoying to work with. Get it refactored: most pople will do it with pleasure.

Some other important points:

Make sure you are using the best testing framework available. It will be much harder to convince people to do TDD if they have to interact with a library that is poorly written.

Make sure the tests are easy to run and don't take to much time to finish (or cheat, for example by using an in-memory db for the tests).

Setup some continuous integration software, so that broken tests are found immediately.


答:
In The Art of Computer Programming Donald Knuth suggests doing the algorithm by hand with pencil and paper to really internalize it. I have found this to work well.

I'm sure a lot of people here will deride this as pedantic, but if you're actually doing algorithmic analysis (i.e., trying to find hardware-neutral performance and memory characteristics) this is worth a shot. This is prima facie required if you're analyzing anything in crypto as you likely want to prove certain probabilistic aspects of the algorithm.

I am first to admit that this practice requires a lot of time and is probably at odds with most programmers... I do research so I don't really have deadlines. I do think it is good to get familiar with the algorithm in the abstract though, and seeing the particular programming language as a mere implementation of that algorithm. Unfortunately, the theoretical body of work for the relationship between something like a mathematically-abstract algorithm and its 'reification' (sorry!) into syntax is not yet complete.


问:
Managing contractors on Github
I want to manage outsourced contractors to help develop our code.
The code sits on Github.

I wish to use a simplified version of this branching model: http://nvie.com/posts/a-successful-git-branching-model/

For now, the code is not modular, so I cannot hide parts of it from some developers, a la https://stackoverflow.com/questions/3852601/github-branches

I do want to hook up our production and staging servers to a repository, so I need to manage write access to the code repository.

Q1 - does this mean I need an ORGANIZATION account on Github?
I'm assuming I do.

Q2 - Would this branching methodology work:
A Main repository with the Master and Integration branches.
Contractors (not having write access) will pull from this repository (or fork it?).
When they are done with a task, they will send a pull-request via the site.

Q2A - does this mean I will not have the ability to track task branches in my repository?

Q2B - how will the integration process work? Do I need to assign a new team, called integrators? Will they pull the completed tasks to the integration branch of the main repository, test it and if good merge to the master branch?

Q3 - Is there a better model?

EDIT - I trust these developers with my code (with regards to secracy). I do not trust them to decide when a feature is ready for production, or which fixes go into the next release.

Thanks!

Tal.

答:
Even as Organization (example), it's tricky because you can only assign read/write permissions per repository, not per branch. So you would have to split your modules into separated repositories to be able to hide parts of it from the contractors.

Also, org users only get few private repositories, so you might run out repos sooner than later, which is why I almost completely made the switch to Codebase because you can have as many repos per "project" as you want, so it's a lifesaver to be able to have multiple repo point to the same issues and wiki instead of having to recreate (or store separately) as I had to in Github, and you can still set permissions on each repo [but not per branch].

OwnerDisplayName: Tal Weiss

Title: Managing contractors on Github


问:
Is it bad practice to use short-circuit evaluation instead of an if clause?
I'm working on an installation script, and especially there I have many things that need to be checked and actions that only need to be performed in case of related outcomes. For example, a folder only needs to be created if it doesn't exist:

```<code>MyDesktopFolderPath := AddBackslash(ExpandConstant('{commondesktop}')) +
                         'My Folder';
if not DirExists(MyDesktopFolderPath) then
begin
  ForceDirectories(MyDesktopFolderPath); //Create full path
end;
if DirExists(MyDesktopFolderPath) then
begin
  //Perform other actions
</code>```

Instead of this, I could use (exploit?) short-circuit evaluation to make it more compact:

```<code>MyDesktopFolderPath := AddBackslash(ExpandConstant('{commondesktop}')) +
                        'My Folder';
IsMyDesktopFolderExisting := DirExists(MyDesktopFolderPath) or
                               ForceDirectories(MyDesktopFolderPath);
if IsMyDesktopFolderExisting then
begin
  //Perform other actions
</code>```

This would work too, but I wonder if it is bad practice, mostly because it is less obvious that actions might be performed. Any opinions on that?

Edit: As pointed out by Secure, the code is not completely equivalent, but the discussion topic still stands for other cases.

答:
Short circuiting was added as a means to improve performance when evaluating a boolean expression. Using it as a form of control flow can lead to confusion many people will not expect evaluating an expression to have a side effect. In most cases, being more explicit about what you are doing is better for readability.

If you look at this example, exploiting short circuiting only saves you two lines. In my opinion, that is not enough to accept the potential issues that may arise from the implicit side effect. In order to prevent the confusion, you might add a comment to explain it. But you are not decreasing the line count savings. In the end, you need to perform a simple operation and by taking advantage of this feature, you decrease the clarity of the operation. You now have to add an explanation instead of letting the code speak for itself.


答:
"Good practice" - NO. As your peers may not be as intelligent as you are. But yes, in some languages (I'd dare say, Perl), That is a common idiom. But "exploiting" short circuit evaluation - if it was considered good practice,

It certainly would have appeared to be a common idiom in a place like the Linux kernel source (Those guys swear to write the clearest code on earth).

If..Then..Else would have been done away with by now.

So, my suggestion, keep it simple, even if it means a few more keystrokes. Just an observation and a personal opinion, though.

Title: Is it bad practice to use short-circuit evaluation instead of an if clause?

Body:
I'm working on an installation script, and especially there I have many things that need to be checked and actions that only need to be performed in case of related outcomes. For example, a folder only needs to be created if it doesn't exist:

```<code>MyDesktopFolderPath := AddBackslash(ExpandConstant('{commondesktop}')) +
                         'My Folder';
if not DirExists(MyDesktopFolderPath) then
begin
  ForceDirectories(MyDesktopFolderPath); //Create full path
end;
if DirExists(MyDesktopFolderPath) then
begin
  //Perform other actions
</code>```

Instead of this, I could use (exploit?) short-circuit evaluation to make it more compact:

```<code>MyDesktopFolderPath := AddBackslash(ExpandConstant('{commondesktop}')) +
                        'My Folder';
IsMyDesktopFolderExisting := DirExists(MyDesktopFolderPath) or
                               ForceDirectories(MyDesktopFolderPath);
if IsMyDesktopFolderExisting then
begin
  //Perform other actions
</code>```

This would work too, but I wonder if it is bad practice, mostly because it is less obvious that actions might be performed. Any opinions on that?

Edit: As pointed out by Secure, the code is not completely equivalent, but the discussion topic still stands for other cases.


问:
Are suffix trees and suffix arrays identical? What are the differences?
I have read some information through internet...i found that somehow suffix tree is quite similar to suffix array but somehow they are no the same thing..

Given a string, a suffix tree construction algorithm looks something like this (I copied the algorithm from a website)

```<code>FOR i ← 1 to n-1
FOR j ← 1 to i+1
   find the end path for S[j…i]
   extend the path, if needed, to S[i+1]
</code>```

suffix tree able to list down all the subtring obtained from a given string

However, does the suffix array also give the same functionality to obtain the list of substrings? Or are suffix arrays just an implementation of suffix trees? Or suffix array just provide some storing function?

答:
The word "suffix array" seems to be used ambiguously. On the one hand, it may mean precisely what the term says: an array of (sorted) suffixes. On the other hand, it may refer to this array of suffixes together with some other tables, making the data structure more useful for various purposes. For clarity, you can use the term "suffix table" for the array itself, and use the term "suffix array" as a cover term for the various multi-table data structures that employ a suffix table. So with this terminology, it seems clear that you downloaded a program for suffix table construction. In other words, you downloaded an implementation of a suffix sorting algorithm.

This distinction between suffix array and suffix table is important to make when comparing the efficiency of suffix arrays and suffix trees. The suffix table itself is obviously succint and efficient. But with each additional table, the gap  is narrowed, so that in the end, it is difficult to say which is more efficient. A number of papers in the last ten years have reported an advantage for suffix arrays. But to achieve this superior performance, you need to be a very clever programmer.

If you really want to learn about suffix arrays, then in my opinion, learning about suffix sorting is not the place to start. Start instead with the "Extended Suffix Array" paper by Abouelhoda et al. This is not an easy paper. But on the other hand, it is very widely cited, and each paper that cites it also needs to summarize it to some extent. So in the end, if you put some work into it, you will definitely get through the paper. Once finished with Abouelhoda, read any papers that cite Aboueloda. Then read the earlier Computational Linguistics paper by Yamamoto and Church and of course papers citing this. My guess is that non-computational linguists will also get something out of this paper (don't be too constrained by your own narrow field of study). Pretty soon you'll become a suffix array expert without ever having learned about suffix sorting. When you get to this point, then go back and read some of the suffix sorting literature. You'll see that it's a very interesting fundamental CS problem. Finally, for other fundamental CS issues related to suffix arrays (combinatoric issues), I recommend the dissertation of Klaus Schürmann (Bielefeld University).


答:
If you think someone might be confused by a construct, there's two solutions:

Write a comment explaining what you did.

Write it in a less confusing manner.

If you find you're having to do #1 more often than you'd like, try #2.


问:
What is the term that describe objects representing both logic and data?
The reason I am asking this question is I want to know how to properly call an architecture where classes have either data or logic but not both. I know this goes against object orientation and encapsulation. I want to use the proper terms for discussing this architecture.

EDIT: By reading the answers I have received, I can see my question wasn't clear. I also feel the edit that was made didn't push the question in the direction I was going for.

I will restate the question in other terms.

Suppose you are working in C#, Java or some other OO language.

You have 2 designs:

DESIGN A:

```<code>class Car
{
     // data
     int numberOfWheels;
     Engine carEngine;

     // methods
     public void StartCar();
}
</code>```

DESIGN B:

```<code>class Car
{
     // this class contains only data (be it entity, DTO, whatever)
     int numberOfWheels;
     Engine carEngine;
}

class CarStarter
{
     public void StartCar(Car aCar);
}
</code>```

In DESIGN B, some classes are used as data structures/DTO/entities (they contain only data and should not contain methods). Other classes contains logic and work with the data classes.

Now suppose you have a design/architecture where DESIGN B, should be applied throughout rather than design A.

I was looking either for a term that described DESIGN B, or the OOP term/notion that consist of DESIGN A. Preferably both.

For the OOP term I guess encapsulation could be it. From Wikipedia Encapsulation

A language construct that facilitates the bundling of data with the methods (or other functions) operating on that data.

I still don't know how to call DESIGN B though.

答:
Neither design does anything with the Car other than reference it. The Car is a black-box representation. I assume that is just an omission.

You should call the second design Procedural Programming, since that is what it is without a doubt.


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

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

答:
Einstein argued that there must be simplified explanations of nature, because God is not capricious or arbitrary. No such faith comforts the software engineer.

  — Fred Brooks, "No Silver Bullet"

LastEditorDisplayName: Roger Pate


答:
This is Delphi-Pascal code - setting a boolean using 'or' could be considered obfuscation but I don't think any attentive, experienced developer would have any problem with it - I use this construct very frequently and I've never had a complaint.

However, I'd limit such a shortcut to one condition in most cases - if you string together a few conditions to get to one boolean value, you are definitely taxing the reader and introducing potential for nasty bugs.

As an aside, if I understand your code correctly, in second example, 'if IsMyDesktopFolderExisting then' is unnecessary: at that point the condition is always true.

Also: first example: 'if DirExists(MyDesktopFolderPath)' all you need here is 'else'   - boolean is binary: it's either true or false. - if that's not what's supposed to be happening here, this code needs refactoring.


问:
"Pythonic" equivalent term for code written in modern C++ style?
There's a lot of good idioms promoted in modern C++. These include RAII and elegant use of boost or STL or a std::algorithm to solve a given problem.

Just like you can write C in any language, you can certainly write C in C++. However you can write really good  modern C++ code with the right subset of features. When someone does something really cool with an STL or boost construct I always get the urge to call it "pythonic" in the sense that its the canocical elegant way to do something. Is there a term like how "pythonic" is used in python to refer to C++ code written in the modern style with modern idioms?

答: 'Slick' is a term I've used and heard for many years to describe clever, concise, well written code - from before Python was invented.</p>


问:
What defines robust code?
My professor keeps referring to this Java example when he speaks of "robust" code:

```<code>if (var == true) {
    ...
} else if (var == false) {
    ...
} else {
    ...
}
</code>```

He claims that "robust code" means that your program takes into account all possibilities, and that there is no such thing as an error - all situations are handled by the code and result in valid state, hence the "else".

I am doubtful, however. If the variable is a boolean, what is the point of checking a third state when a third state is logically impossible?

"Having no such thing as an error" seems ridiculous as well; even Google applications show errors directly to the user instead of swallowing them up silently or somehow considering them as valid state. And it's good - I like knowing when something goes wrong. And it seems quite the claim to say an application would never have any errors.

So what is the actual definition of "robust code"?

答:
I agree with @gnasher729 's statement: Your professor's approach is totally misguided.

Robust means it's resistant to breakage/failure because it makes few assumptions and is decoupled: it's self contained, self defining, and portable. It also includes being adaptable to changing requirements. In a word, your code is durable.

This generally translates into short functions that get their data from parameters passed in by the caller, and the use of public interfaces for consumers - abstract methods, wrappers, indirection, COM style interfaces, etc - rather than functions containing concrete implementation code.

Title: What defines robust code?


问:
Local and cloud editions?
I have a .NET web server application I'm building that I plan to host at a .NET cloud hosting platform, like AppHarbor with SQL server. It will be used by multiple small groups of people to record and processes votes at an election (the current system is called TallyJ).

I also need my users to be able to set up a self-contained edition on a single PC, or as a server on a PC with an ad hoc LAN that is not connected to the internet when it is being used.

My current plan would be to use IIS Express and SQL CE for a local setup. With that, the local and hosted versions of code and SQL would be the same.

Does this sound viable, or am I missing something?

Do you have any suggestions for a better set of tools (but limited to C# and a relational database on the server/cloud)?

答:
It certainly sounds viable.

It has the great advantage of allowing you to keep with one version of the application which will always be easier to develop and maintain.

However, is it going to present any difficulties to the user?

One issue might be that you are limiting the users of your off line application to Windows users. Is this acceptable? If not then you'll have to find a different platform for the application. This is just one example that sprang to mind immediately. There will be others. You will need to draw up a list and see if any are show-stoppers for you.

Title: Local and cloud editions?


问:
Can we replace XML with JSON entirely?
I'm sure lots of developers are familiar with XML and JSON, and they've used both of them. Thus no point in explaining what they are, and what is their purpose, even in brief.

If we try to map their concepts, we can say (correct me if I'm wrong):

XML tags are equivalent to JSON {}

XML attributes are equivalent to JSON properties

XML tag collection is equivalent to JSON []

The only thing I can think of, which doesn't exist in JSON, is XML Namespaces.

The question is, considering this mapping, and considering that JSON is highly lighter in this mapping, can we see a world in future (or at least theoretically think of a world) without XML, but with JSON doing everything XML does? Can we use JSON everywhere XML is used?

PS: Please note that I've seen this question. It's something entirely different from what I'm asking here. Thus please don't mention duplicate.

答:
It gets ugly when you try to model these two objects in JSON:

```<code><customer><name>John Doe</name></customer>
<employee><name>John Doe</name</employee>
</code>```

Using JSON as it is used to in 99% cases one gets lost with:

```<code>{ name: "John Doe" }
</code>```

And now you have to add some meta-structures and all the beauty of JSON is gone while you are left with the downsides.

Title: Can we replace XML with JSON entirely?

Body:
It gets ugly when you try to model these two objects in JSON:

<customer><name>John Doe</name></customer>
<employee><name>John Doe</name</employee>

Using JSON as it is used to in 99% cases one gets lost with:

{ name: "John Doe" }

And now you have to add some meta-structures and all the beauty of JSON is gone while you are left with the downsides.


答:
Short-circuit evaluation is not just about performance.  It's also about preventing run-time errors.  For example, I would consider:

```<code>if (foo != null && foo.bar == 4) {
    // do something
}
</code>```

to be perfectly clear and preferable to

```<code>if (foo != null) {
    if (foo.bar == 4) {
        // do something
    }
 }
</code>```

Note that the first form only works if there is short-circuit evaluation... otherwise it generates a run-time error whenever foo == null.

Body:
Short-circuit evaluation is not just about performance.  It's also about preventing run-time errors.  For example, I would consider:

if (foo != null && foo.bar == 4) {
    // do something
}

to be perfectly clear and preferable to

if (foo != null) {
    if (foo.bar == 4) {
        // do something
    }
 }

Note that the first form only works if there is short-circuit evaluation... otherwise it generates a run-time error whenever foo == null.


答: "Modern C++" as Nemanja Trifunovic already answered is well used, but the generic adjective for all languages is "idiomatic". So for C++ it would be "idiomatic C++". "Pythonic way" is the same as "idiomatic Python".

Title: "Pythonic" equivalent term for code written in modern C++ style?

Body:
There's a lot of good idioms promoted in modern C++. These include RAII and elegant use of boost or STL or a std::algorithm to solve a given problem.

Just like you can write C in any language, you can certainly write C in C++. However you can write really good  modern C++ code with the right subset of features. When someone does something really cool with an STL or boost construct I always get the urge to call it "pythonic" in the sense that its the canocical elegant way to do something. Is there a term like how "pythonic" is used in python to refer to C++ code written in the modern style with modern idioms?


问:
How can I use Scrum with a freelance team?
I'm working in a start-up. I have a background with teamwork and management, but I'm currently the only developer. We have a project that will involve a few developers in the form of 2 freelancers. I will function as a developer as well as the ScrumMaster. The project is scheduled to last three to four months. The 3 developers (myself and the two freelancers) have never worked together before.

Would it be possible or advisable to use Scrum to manage this type of project? Would there be any problems organizing or running the team using Scrum?

答:
In my experience the overhead costs of Scrum are too high when your team is three people or less. With a team of that size you are better off using an adhoc/informal team process.

By costs I mean Planning, Review, Retrospective and Grooming meetings are better being replaced by informal sessions that occur spontaneously. There is still value is planning, demonstrating what you have completed, obtaining feedback and regularly applying continuous improvement however you are better off doing this informally.

Good luck with your project, just remember that communication between the three of you, and your business customer is the key.


问:
Do speakers get paid for tech talks?
I'm curious if speakers (bloggers, google employees like Matt Cutts) get paid for speaking at conferences. If they do, how much? If they don't, or they get paid so little that it's as though they don't, why do it? What are the attractions beyond money that lead a developer into public speaking?</p>

答: Speakers at tech conferences generally get their travel costs refunded, but nothing more.</p>

OwnerDisplayName: FluffyCoder

Title: Do speakers get paid for tech talks?


答:
I have two concerns with using Scrum on this project.

First, the team size is too small. Scrum works best with a total team size of 4-11 people. With only 3 people, you are below that recommended size. Also, a key role in Scrum is the Product Owner, and you don't mention someone acting in this role.

Second, you have what appears to be a deadline, where the project will conclude in 3-4 months. Scrum (and other iterative and incremental methodologies) works best when you have a flexible window with with to work. The idea is that you very quickly get to a point where you can determine what features you can implement in a 2-4 week increment and the Product Owner is capable of prioritizing features and stopping development as soon as the cost of implementing another set of features outweighs the value added by those features.

I think that you can take lessons from Scrum and other agile methodologies, but I'm not sure of vanilla, out-of-the-box Scrum is appropriate in this environment. 15 minute timeboxed daily standups, using a product backlog, continuous integration, TDD, and other agile practices would be worth looking into, but I would tailor the process to work for this project.

Title: How can I use Scrum with a freelance team?

Body:
I'm working in a start-up. I have a background with teamwork and management, but I'm currently the only developer. We have a project that will involve a few developers in the form of 2 freelancers. I will function as a developer as well as the ScrumMaster. The project is scheduled to last three to four months. The 3 developers (myself and the two freelancers) have never worked together before.

Would it be possible or advisable to use Scrum to manage this type of project? Would there be any problems organizing or running the team using Scrum?


答:
It's fine to me; this is a very common idiom in many languages: sh, C++, Perl, Lisp, Ruby, etc.

I would not add a comment; the comment would add nothing to the code.

I don't have much sympathy for colleagues who can't be bothered to parse any code that is slightly unfamiliar.


答:
Why limit yourself to JSON when YAML is a super set and much more expressive and therefore powerful than XML or JSON.

That said, if you use the correct serialization frameworks you should be able to serialize and de-serialize all the above mentioned formats with a couple of simple lines of code.

Title: Can we replace XML with JSON entirely?

Body:
I'm sure lots of developers are familiar with XML and JSON, and they've used both of them. Thus no point in explaining what they are, and what is their purpose, even in brief.

If we try to map their concepts, we can say (correct me if I'm wrong):

XML tags are equivalent to JSON {}

XML attributes are equivalent to JSON properties

XML tag collection is equivalent to JSON []

The only thing I can think of, which doesn't exist in JSON, is XML Namespaces.

The question is, considering this mapping, and considering that JSON is highly lighter in this mapping, can we see a world in future (or at least theoretically think of a world) without XML, but with JSON doing everything XML does? Can we use JSON everywhere XML is used?

PS: Please note that I've seen this question. It's something entirely different from what I'm asking here. Thus please don't mention duplicate.


问:
Long parameter list versus long state variable list
In a C++ book, the author says we no longer need a function with a long parameter list because most of the parameters can be refactored into state variables in a class.
On the other hand,  a functional programming book says state variables are evil because it causes side-effects which cause bug-prone and hard to parallelize code.
I'm getting puzzled. Should the code avoid relying on state variables as much as possible by moving its state variable into the function parameter list?</p>

答:
Depends if you are programming in a procedural or functional paradigm. Mutable state is required for the former and crippling for the later. This is apples and oranges. They are both correct in their on bailiwicks!

You can apply single assignment and other functional techniques to imperative procedural languages, immutable state makes concurrent programming more deterministic, but making every object immutable in a language like Java or C++ is almost impossible because their memory models don't easily support this paradigm.


问:
Where should heavy development assets like specification documents and multimedia editor source files be stored?
It's not uncommon where I'm working on a site that includes things like binary (or effectively undiffable due to factors outside my control) specification documents (e.g., PDFs, Word Documents, Excel Spreadsheets) and multimedia source files (e.g., FLA source files, Photoshop files, Illustrator files).

How should these be stored?

My instinct is to just throw them into git. Storage is cheap, but it does make the clone operation take much, much longer than it otherwise would.

A potential alternative would be to use a wiki. I've tried it in some cases but never ran into a case where the wiki format's inherent strengths (layperson-accessible version history and easy access to latest copies) have or would have led to enough benefit to justify the additional work in maintaining the wiki.

The third option is to just let them hang out locally and in email threads.

So what approach should I take to this?

答:
First off its a really good idea to get all this stuff under version control!

The tool you use depends on the type of data. For multimedia files zipping up the originals and dumping them in a folder would seem to be the best option, perhaps, with copy of the cover document going into your main version control (git or whatever).

For word documents like use cases and specifications etc.  I think the best strategy would be to store them in one of the newer "xml" based formats and store them in "git". The "diff" would actually mean something then, and, although the documents themselves would be larger the "diffs" would be smaller.


问:
Search multiple tables
I have developed a web application that is used mainly for archiving all sorts of textual material (documents, references to articles, books, magazines etc.). There can be any given number of archive tables in my system, each with its own schema. The schema can be changed by a moderator through the application (imagine something similar to a really dumbed down version of phpMyAdmin).

Users can search for anything from all of the tables. By using FULLTEXT indexes together with substring searching (fields which do not support FULLTEXT indexing) the script inserts the results of a search to a single table and by ordering these results by the similarity measure I can fairly easily return the paginated results.

However, this approach has a few problems:

substring searching can only count exact results

the 50% rule applies to all tables separately and thus, mysql may not return important matches or too naively discards common words.

is quite expensive in terms of query numbers and execution time (not an issue right now as there's not a lot of data yet in the tables).

normalized data is not even searched for (I have different tables for categories, languages and file attatchments).

My planned solution Create a single table having columns similar to

```<code>id, table_id, row_id, data
</code>```

Every time a new row is created/modified/deleted in any of the data tables this central table also gets updated with the data column containing a concatenation of all the fields in a row. I could then create a single index for Sphinx and use it for doing searches instead.

Are there any more efficient solutions or best practises how to approach this? Thanks.

答:
Why not let the text search engine like lucene or sphinx do all the work?
I use Lucene and have found it to be very good at searching multiple tables and fields for whatever you set as a target.

You don't say what your web front end is written in but both of these tools can be used with most languages.

You will be adding a lot of code to maintain in the triggers that watch for created/modified/deleted in all the tables. Wouldn't it be easier to add the option for admins to mark a column as "to be searched".  Then write code to add this column to indexed fields?

I see that Sphinx has "offline index construction and incremental on-the-fly index updates" which would seem to allow you to add a field, rebuild the index offline and then bring the new index up.

Title: Search multiple tables


问:
Is it common to have downtime at a programming job?
At my company, I find that there are some days that there are very few tasks to do.  I make it a point to do research to learn new things about my craft on these days.

I would say that on average, I have about one day per week that there is not much to do (or some combination of time over the week).

I would like to know if this is a common situation in software development environments, and does the answer to this question vary between full-time and contract work.

答:
From my experience, it is relatively common. Although we used to have - free with nothing to do - days usually after the completion of some phase of the project, when it is being evaluated ... it would usually last up to a week or so even, before we got an answer from them, and then continued our work on the project.

Can't say whether this is a practice in the whole industry, though.


问:
Should a function use premature returns or wrap everything in if clauses?

Possible Duplicate:

  Where did the notion of “one return only” come from?

Which is better? I see pros and cons for both, so I can't really decide on which one to stick to.

Wrap in if clause

```<code>function doIt() {
   if (successfulCondition) {
      whenEverythingGoesWell();
   }
}
</code>```

Pro: Shows programmer's intention through indentation.

Con: Indentation can get really deep if you need to short circuit many times. For example, doThirdThing() requires the success of doSecondThing(), which in turn requires the success of doFirstThing(). This happens a lot in web development where many web services are not reliable.

Premature return

```<code>function doIt() {
   if (!successfulCondition) {
      return;
   }
   whenEverythingGoesWell();
}
</code>```

Pro: Subversion checkins would be succinct. Sometimes, I see co-workers wrap super long functions in an if clause. The whole shebang gets checked in and makes reading Subversion diffs difficult.

Con: Requires you to read the whole function to figure out the various run paths.

答:
Good question, one that I've often asked myself. But I always answer that exiting is cleaner than the burden of conditional logic. Just make sure that your intent is clear - it is in your example.

Also: well thought-out and well placed assertions are sometimes clearer and more effective in such situations - just make sure that you appropriately handle the potential assertion failure in your caller.

function doIt() {

```<code>  Debug.Assert(successfulCondition,"condition not met");
  whenEverythingGoesWell();
</code>```

}

Body:
Good question, one that I've often asked myself. But I always answer that exiting is cleaner than the burden of conditional logic. Just make sure that your intent is clear - it is in your example.

Also: well thought-out and well placed assertions are sometimes clearer and more effective in such situations - just make sure that you appropriately handle the potential assertion failure in your caller.

function doIt() {

  Debug.Assert(successfulCondition,"condition not met");
  whenEverythingGoesWell();

}


答:
Yeah i would say that there  can be alot of downtime if you end up in a situation where you are waiting on a response from a client or manager about how to proceed when you come across a design issue.

Another instance is when a server crashes in your dev env and you can't continue development until it has been resolved.

One last situation i've experienced downtime (as a consultant) when there was a weird gap between when one project ended and the next began.

That being said, I also believe it is a sign of bad management when your workers are not fully utilized.  You should have other tasks that should be able  to work on in case the server crashes.  Typically at my company if we hit a roadblock with something we go an update the project wiki and or go and do assigned learning (everyone has a specific topic they are suppose to be learning in downtime).

In regards to the contract and salaried employees, I find that the salaried employees have more downtime and contract/consultant workers, but that is merely the case of contract workers having a higher cost to the company and only bringing them in when you have need for more/specific programmers.

From what you are saying, it looks like you have 20% downtime, which is a lot and would hint at poor management.

Title: Is it common to have downtime at a programming job?

Body:
At my company, I find that there are some days that there are very few tasks to do.  I make it a point to do research to learn new things about my craft on these days.

I would say that on average, I have about one day per week that there is not much to do (or some combination of time over the week).

I would like to know if this is a common situation in software development environments, and does the answer to this question vary between full-time and contract work.


答:
Sometimes you have problems with either approach.  You may be tempted to put in a bunch of guard clauses but at the same time you may have resources that you need to be sure to clean up.

Something I do when there are lots of possible things to do before getting to the meat of the method, especially when I want to have an orderly exit is to us a do/loop with a guaranteed break at the end.  This is sort of a compromise premature exit.  Instead of exiting out of the method, and instead of nesting many, many if blocks, you have one do/loop block which you can break out of if something bad happens.

It looks something like this...

```<code>public bool YourMethod()
{
    do    // For bailing, not for looping.
    {
        if (FirstBadThingHappens)
        {   // Do any logging or other follow up.
            break;
        }
        ...
        if (NthBadThingHappens)
        {   // And so forth...
            break;
        }
        // If we're still here then it must be OK to proceed...
        DoTheMeatOfTheMethod();

    } while(false)   // Always only one pass
    // Do whatever needs doing to wrap up cleanly...
    CleanUpResourcesOrWhatever();
    return bResult;
}
</code>```

Title: Should a function use premature returns or wrap everything in if clauses?

Body:
Possible Duplicate:

  Where did the notion of “one return only” come from?

Which is better? I see pros and cons for both, so I can't really decide on which one to stick to.

Wrap in if clause

```<code>function doIt() {
   if (successfulCondition) {
      whenEverythingGoesWell();
   }
}
</code>```

Pro: Shows programmer's intention through indentation.

Con: Indentation can get really deep if you need to short circuit many times. For example, doThirdThing() requires the success of doSecondThing(), which in turn requires the success of doFirstThing(). This happens a lot in web development where many web services are not reliable.

Premature return

```<code>function doIt() {
   if (!successfulCondition) {
      return;
   }
   whenEverythingGoesWell();
}
</code>```

Pro: Subversion checkins would be succinct. Sometimes, I see co-workers wrap super long functions in an if clause. The whole shebang gets checked in and makes reading Subversion diffs difficult.

Con: Requires you to read the whole function to figure out the various run paths.

Body:
Sometimes you have problems with either approach.  You may be tempted to put in a bunch of guard clauses but at the same time you may have resources that you need to be sure to clean up.

Something I do when there are lots of possible things to do before getting to the meat of the method, especially when I want to have an orderly exit is to us a do/loop with a guaranteed break at the end.  This is sort of a compromise premature exit.  Instead of exiting out of the method, and instead of nesting many, many if blocks, you have one do/loop block which you can break out of if something bad happens.

It looks something like this...

public bool YourMethod()
{
    do    // For bailing, not for looping.
    {
        if (FirstBadThingHappens)
        {   // Do any logging or other follow up.
            break;
        }
        ...
        if (NthBadThingHappens)
        {   // And so forth...
            break;
        }
        // If we're still here then it must be OK to proceed...
        DoTheMeatOfTheMethod();

    } while(false)   // Always only one pass
    // Do whatever needs doing to wrap up cleanly...
    CleanUpResourcesOrWhatever();
    return bResult;
}


答:
Any sufficiently advanced technology is indistinguishable from magic.

-- Arthur C. Clarke

Body:
What's your favourite quote about programming?

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


答:
It is common in industry, but if a team is managed well, then the managers should have a readily available 'pipeline' of in house and/or lower priority projects that can be assigned on demand. These will ideally involve newer technologies and/or libraries. In my experience assigning people to work on code documentation or updating wikis is not well received by developers, who by nature are normally happier when actually developing something.

Another approach I've seen is to send people on full-time training courses of up to two weeks at a time, for upskilling the development team with knowledge that will be needed in the future.

Generally if you're a contractor and find yourself without active work at a company then you'd better start looking around for another position, because you will probably be the first one to be let go if the company hits a downturn.


答:
Most downtime I've encountered is usually on Financial year-end and/or end of the year (December season, as most customers goes on holiday). Company "closes" for various reasons and IT has no deployments for 2 to 3 months. Therefore, there is no changes.

It does happen: During this time, we evaluate all the changes/projects undergone in the year, find out where we improved or lacked and find a solution to improve better for the next season/term.

Don't feel worried.


问:
Why NoSQL over SQL?

Possible Duplicate:

  When would someone use MongoDB (or similar) over traditional RDMS?

How well the SQL and NoSQL go head-to-head. I read somewhere that SQL databases are not well for data that is well structured or has some graph-iness associated with it. Is it really the case?

Apart form Facebook, Google, and some other big players on the web, I don't know how well small-players and start-ups have used these tools. I found another similar question about the same here. But I couldn't gather much stats from here. These are certain specific cases, and is there a general pattern (like the one mentioned above) for which these NoSQL databases can be used?

How wise will it be for a start-up to go for a NoSQL database if the developers know that the amount of data involved will be a little large and is well structured, but requires frequent CRUD operations?

Here on stackoverflow, one can find questions about when not to use SQL, but are there any scenarios when one should avoid using NoSQL databases? Also, how effective will it be to use both in parallel so that we get the best of them both?

One last question, do these distributed NoSQL databases perform equally well when they are used in a single-node setup?

答:
Here are some pros for classical SQL databases like Oracle, MS SQL, Sybase, DB/2 against NO/SQL:

very mature

existing ecosystem (documentation, tools, lots of third party vendors, bindings to different programming languages etc.)

extensive security models

easy ad-hoc-queries, with very powerful query languages

most of them are scalable for hundreds of users/connections

Views and stored procedures

trustworthy transaction models

different indexing capapatibilities

different goodies like replication mechanisms, geographic datatypes, etc.

Those features are really good if you are going to develop some enterprise software system, where you don't know exactly what applications will work with these data in a few years. I don't think there are any No/SQL databases available today which can compete in the listed features with any of the "big" SQL databases.

On the other hand, NO/SQL-databases show benefits when you don't need many of those things, for example, as a backend db of a web application you won't need a complex security model, because there may be mostly just one user (the application server process) connected to you db at production time. Of course, you could also use some lightweight SQL database like SQLlite for those kind of applications (and many people do this), but then there's also to consider the structure of the data you are going to store. For example, a blog system, a QA forum, a content management system, a Wiki: there is a lot of text or html code or xml code to store, and less adminstrative data. That may be systems where NO/SQL can show it's benefits.

Title: Why NoSQL over SQL?


问:
Do you prefer conciseness or readability in your code?
Language shortcuts can often be used to make code more concise.

For example, ternary and null coalescing operators can reduce the amount of code, but arguably to the detriment of readability:

In C#:

```<code>Person newGuy = new Person();
if (boss == null) {
    newGuy.Boss = GetDefaultBoss();
} else {
    newGuy.Boss = boss;
}
</code>```

is functionally equivalent to:

```<code>Person newGuy = new Person();
newGuy.Boss = boss ?? GetDefaultBoss();
</code>```

but obviously a lot more verbose.

Where do you draw the line when it comes to conciseness vs readability?

答:
Both.

Your first example is certainly more verbose, and arguably more explicit... but it also requires me to scan five lines instead of one. Worse, it deemphasizes its purpose - assigning a value to newGuy.Boss.

Your second example may cost me a second if I'm unfamiliar with the null coalescing operator, but there can be no doubt as to its purpose, and if I'm scanning through a larger routine looking for the source of a value, it will be much easier for me to pick this one out.

Now, contrast this:

```<code>if (boss == null) {
    newGuy.Boss = GetDefaultBoss();
    newGuy.IsTemp = true;
    newGuy.AddTask("orientation");
} else {
    newGuy.Boss = boss;
    newGuy.IsTemp = false;
}
</code>```

...with:

```<code>newGuy.Boss = boss ?? GetDefaultBoss();
newGuy.IsTemp = boss == null;
if ( boss == null ) newGuy.AddTask("orientation");
</code>```

The latter example is again much shorter, but now it obscures its purpose by making tasks triggered by the same test appear to be distinct. Here, I feel the verbosity of the former is justified.

Body:
Both.

Your first example is certainly more verbose, and arguably more explicit... but it also requires me to scan five lines instead of one. Worse, it deemphasizes its purpose - assigning a value to newGuy.Boss.

Your second example may cost me a second if I'm unfamiliar with the null coalescing operator, but there can be no doubt as to its purpose, and if I'm scanning through a larger routine looking for the source of a value, it will be much easier for me to pick this one out.

Now, contrast this:

if (boss == null) {
    newGuy.Boss = GetDefaultBoss();
    newGuy.IsTemp = true;
    newGuy.AddTask("orientation");
} else {
    newGuy.Boss = boss;
    newGuy.IsTemp = false;
}

...with:

newGuy.Boss = boss ?? GetDefaultBoss();
newGuy.IsTemp = boss == null;
if ( boss == null ) newGuy.AddTask("orientation");

The latter example is again much shorter, but now it obscures its purpose by making tasks triggered by the same test appear to be distinct. Here, I feel the verbosity of the former is justified.


答:
It depends on the conference. For most conferences, the conf registration is comp'd, but travel & hotel are the speakers responsibility. I know of some other conferences where speakers are also required to pay their own registration fees.

Keynote presenters are almost always paid (in addition to having their hotel and flight covered). Some conferences have a middle tier of "invited speakers" who may get a small stipend or have hotel and flight covered.

If there's a particular conference you're interested in, the web sites for most conferences list this information with the speaker submission information.

Title: Do speakers get paid for tech talks?

Body: I'm curious if speakers (bloggers, google employees like Matt Cutts) get paid for speaking at conferences. If they do, how much? If they don't, or they get paid so little that it's as though they don't, why do it? What are the attractions beyond money that lead a developer into public speaking?</p>


答:
If I understand your question right, you are questioning what conditions qualify either the use of a parameter or class variable/member/field/etc? I'm assuming you're referring to a method, and not a function. If this is about C++ specifically, I suggest moving your question to stack overflow.

A long parameter list may be a sign that you might need to refactor your method into a set of more granular ones. Generally, using parameters will make your code more loosely coupled. I'm not sure if this is true for most modern OO languages anymore, but object creation can be expensive, especially if there are many class variables involved; so, if your class variables were objects and were referenced frequently in a program, then they may be justified as being class variables.

Also:

Could other methods make use of the class variables? If yes, then consider going with class variables.

Is your method public? If public, use parameters.

Can your parameter list appropriately be represented as a hash/map/array/collection/list/etc? If so, consider it an option.

Is your method static? If yes, use parameters.

Title: Long parameter list versus long state variable list

Body:
In a C++ book, the author says we no longer need a function with a long parameter list because most of the parameters can be refactored into state variables in a class.
On the other hand,  a functional programming book says state variables are evil because it causes side-effects which cause bug-prone and hard to parallelize code.
I'm getting puzzled. Should the code avoid relying on state variables as much as possible by moving its state variable into the function parameter list?</p>


答:
If you really must give 2 versions of your application, an online and other offline mode, I would strongly suggest to drop the web application entirely unless you must have a web version.

A simple windows application (maybe Silverlight so you can aim not only for Mac but for browser and out-of-the-browser as well), that will consume a local database and sync into the master when having a connection.

If you want to have an app in the browser, you can simply use the same Silverlight application in Hosted mode and on each user, in "out-of-the-browser" mode.

There is plenty of solutions to sync offline databases from Microsoft or others, plenty of questions/answers on StackOverflow about this:

https://stackoverflow.com/questions/1656652/syncing-sql-server-2008-databases-over-http-using-wcf-sync-framework

Title: Local and cloud editions?

Body:
I have a .NET web server application I'm building that I plan to host at a .NET cloud hosting platform, like AppHarbor with SQL server. It will be used by multiple small groups of people to record and processes votes at an election (the current system is called TallyJ).

I also need my users to be able to set up a self-contained edition on a single PC, or as a server on a PC with an ad hoc LAN that is not connected to the internet when it is being used.

My current plan would be to use IIS Express and SQL CE for a local setup. With that, the local and hosted versions of code and SQL would be the same.

Does this sound viable, or am I missing something?

Do you have any suggestions for a better set of tools (but limited to C# and a relational database on the server/cloud)?


问:
dbdeploy (phing) and development teams
Does anyone here use dbdeploy (phing) in a commands?

If so - how do you manage the migrations?

Let's suppose we have 2 different features developed in different branches of mercurial repository (phing build file and dbdeploy migrations are stored in mercurial). Which IDs to give to each feature changes?

答:
We are using ant + dbdeploy, we had been using phing + dbdeploy in the past.

Unfortunately there is no automated way of handling these type of changes, so we had to come up with an agreement. Our branches are temporary, when feature/bug is resolved, they are usually removed after the changes are merged into master branch. Few basic rules:

1. Make sure everyone knows you will be or you already have changed database structure and/or
data

This way conflicts are prevented. If Alice on changing something Bob already changed in a different branch, Alice can either use Bob's delta or make sure your change will not affect it.

2. Only one person is allowed to merge changes into master branch

When Charlie is merging branches into master, Alice and Bob help him resolve any DB delta issue. For example, Alice created 123_create_table_user.sql and Bob 123_alter_table_message.sql. Depending on the changes, there are two possible outcomes, 123_create_table_user.sql and 124_alter_table_message.sql or 123_alter_table_message.sql and 124_create_table_user.sql.

3. You are the owner of your local database

In above case, both Alice and Bob need to make sure their dbdeploy's changelog is in sync. If there are any problems when running dbdeploy because the values in the table are different than the delta scripts, it's Alice's and/or Bob's fault.

What we have seen so far, most frequent database changes are done at the beginning of the project, when everything is done on one branch. Later on, even with 5 or more developers each working in their own branches, we rarely run into database conflicts.

Title: dbdeploy (phing) and development teams


问:
Is the upgrade path from Win32 to .NET to WinRT feasible?
I support a VB6 application.  It's currently being replaced, module by module, with .NET (including a lot of new features as we go).  The GUI is in WPF, but with almost zero coupling to the business logic, so that's not as important.  I'm hoping the migration will be done by mid-2012.

I'm reading some of the news out of the MS build conference, and it looks like WinRT with Metro will be the API and GUI of choice for future development, especially if you want your application to run on mobile devices (which we will, certainly).

What kind of speed bump are we looking at when we (eventually) migrate from .NET to WinRT and Metro?  It looks like C# and Xaml will be around, but WinRT is not .NET.  Are the API's compatible (just a matter of changing an option in the VS build menu)?  If they're not, will there be a one-way conversion tool?  Will it be possible to easily maintain one application that runs under .NET/WPF on Windows XP/7 systems and simultaneously builds to a WinRT/Metro target during the time when we have all those systems in-house?

答:
Currently, as in 'it's just a developer preview after all'1, you mostly have to change a couple of namespaces for your XAML/C# based solutions to compile and run as a 'legacy' app.

That's because they have split some essential DLLs/namespaces from the core .NET framework that you're certain to be using right now.

Then, if you want your app to be 'Metroish', you will have to rethink its UI, which is not a big deal if you're already using a good Separation of Concerns, for instance MVVM.

1 What I mean is, probably the upgrade path will be smoother once the tools are mature.


答:
There is only one scenario where NoSQL is the way to go. And that is when you need to be very very flexible regarding database traffic.

That means you have to expect that all of a sudden the database-requests explode by a factor of - let's say - 10 or 100. The ability to react to such situations is called elasticity.

Here you have a problem with classic relational databases, cause due to their specialization on optimizing for JOINs they cannot just be copied to another server while still guaranteeing relational integrity. And even then copying those huge databases takes a lot of time.

So to deal with those explosion of request situations companies came up with different database-concepts that are specialized for that.

If you don't have to expect such extreme flucutations in your request-load, then relational is the way to go. And that maybe forever, cause what many people don't understand is that relationality is not just some tech-buzz-word from last century - information is almost always inherently of vectorial and therefore relational nature.

Title: Why NoSQL over SQL?

Body:
Possible Duplicate:

  When would someone use MongoDB (or similar) over traditional RDMS?

How well the SQL and NoSQL go head-to-head. I read somewhere that SQL databases are not well for data that is well structured or has some graph-iness associated with it. Is it really the case?

Apart form Facebook, Google, and some other big players on the web, I don't know how well small-players and start-ups have used these tools. I found another similar question about the same here. But I couldn't gather much stats from here. These are certain specific cases, and is there a general pattern (like the one mentioned above) for which these NoSQL databases can be used?

How wise will it be for a start-up to go for a NoSQL database if the developers know that the amount of data involved will be a little large and is well structured, but requires frequent CRUD operations?

Here on stackoverflow, one can find questions about when not to use SQL, but are there any scenarios when one should avoid using NoSQL databases? Also, how effective will it be to use both in parallel so that we get the best of them both?

One last question, do these distributed NoSQL databases perform equally well when they are used in a single-node setup?


问:
How do you manage refactoring with a large code base and many developers?
I would like to prevent a situation where two developers refactor the same code simultaneously without talking about it first, probably using a tool of some kind, maybe an Eclipse plug-in. Can you help?

We've got 4.5 million lines of code, and more than 20 teams of developers on four continents.

Ideally I would like the second of the developers mentioned earlier to notice that someone else is working on the same piece of code and talk to the first one before modifying anything.

Do you know of a solution?

答: If you leave notice that someone else is working on the same piece of code and talk to the first one before modifying anything, as per what you said, you need a version control system (CVS/SVN/GIT). I'm not sure though, but if you want to include that too, you will need some advanced things (some sort of triggering mechanism/some custom thing maybe).


问:
Is it bad practice to use short-circuit evaluation instead of an if clause?
I'm working on an installation script, and especially there I have many things that need to be checked and actions that only need to be performed in case of related outcomes. For example, a folder only needs to be created if it doesn't exist:

```<code>MyDesktopFolderPath := AddBackslash(ExpandConstant('{commondesktop}')) +
                         'My Folder';
if not DirExists(MyDesktopFolderPath) then
begin
  ForceDirectories(MyDesktopFolderPath); //Create full path
end;
if DirExists(MyDesktopFolderPath) then
begin
  //Perform other actions
</code>```

Instead of this, I could use (exploit?) short-circuit evaluation to make it more compact:

```<code>MyDesktopFolderPath := AddBackslash(ExpandConstant('{commondesktop}')) +
                        'My Folder';
IsMyDesktopFolderExisting := DirExists(MyDesktopFolderPath) or
                               ForceDirectories(MyDesktopFolderPath);
if IsMyDesktopFolderExisting then
begin
  //Perform other actions
</code>```

This would work too, but I wonder if it is bad practice, mostly because it is less obvious that actions might be performed. Any opinions on that?

Edit: As pointed out by Secure, the code is not completely equivalent, but the discussion topic still stands for other cases.

答:
Your first version could as well be like this:

```<code>IsMyDesktopFolderExisting := DirExists(MyDesktopFolderPath);
if not IsMyDesktopFolderExisting then
begin
  IsMyDesktopFolderExisting := ForceDirectories(MyDesktopFolderPath);
end;
if IsMyDesktopFolderExisting then
...
</code>```

While using a short-circuit tells me to look more carefully what's done here,  ignoring the return value of a resource handling function (like memory or files) immediately raises a red flag.

Body:
Your first version could as well be like this:

IsMyDesktopFolderExisting := DirExists(MyDesktopFolderPath);
if not IsMyDesktopFolderExisting then
begin
  IsMyDesktopFolderExisting := ForceDirectories(MyDesktopFolderPath);
end;
if IsMyDesktopFolderExisting then
...

While using a short-circuit tells me to look more carefully what's done here,  ignoring the return value of a resource handling function (like memory or files) immediately raises a red flag.


答: There are/were version control systems that make developers checkout code before they can edit but these have there own set of problems. Better practice is to get developers to commit and update often. One developer could then mark a class as depreciated and commit then if the other developer updates before they start their refactor they will see the intent.</p>

Title: How do you manage refactoring with a large code base and many developers?

Body:
I would like to prevent a situation where two developers refactor the same code simultaneously without talking about it first, probably using a tool of some kind, maybe an Eclipse plug-in. Can you help?

We've got 4.5 million lines of code, and more than 20 teams of developers on four continents.

Ideally I would like the second of the developers mentioned earlier to notice that someone else is working on the same piece of code and talk to the first one before modifying anything.

Do you know of a solution?


答:
In my workplace we get downtime when:

Network/servers are problematic

Nothing immediate to do (e.g. waiting for meetings to set requirements)

Waiting for someone to finish off something you need to do your job (even though that's not exactly the best idea)

When downtime is shared, which for me is about 5% of the time, I usually go talk to people, get my head off things, hear some jokes.

When I find myself with nothing important to do, I have a directory with tons of books, which I read when I'm allowed, or in between long compile (or something equivalent) sessions, etc.

But even though I do this, I have to acknowledge something (which does make me a sinner myself):

It's our job as programmers to develop our careers at home so that our boss wouldn't fire us or something like that. It's not the boss' job to let you improve yourself with his money (time he's paying you for).

But anyway, as an alternative, sometimes instead of reading I do some other stuff,such as come up with some useful scripts or ideas, write documents and presentations about methodology improvements, etc.

That also counts as self improvement because it makes you think, and makes you useful to other developers, who might even remember you for that some day, when it counts.
But the important thing is that it's worth the money you're paid better than reading books...


答:
Many 2nd-generation source control systems work using a connected "checkout" which informs the server that you are intending to modify a file.  Examples include TFS, SourceGear Vault, and many others.  In this way, you can technically accomplish your requirement.  As Adam Butler pointed out though, these types of tools come with their own issues (without getting into a lengthy debate - limited support for offline work, and generally counter-productive development workflow).

I would definitely suggest some kind of hierarchical approach to allocating the refactoring work.  The developers could be logically grouped into sub-teams, each responsible for specific areas of the code.  Depending on how you like to structure teams, each one could have a "lead" role who is responsible for the high-level design of the team's area.  This structure should be well-known to the developers, and it should simplify communication for refactoring.  I am sure that this approach seems too formal and backwards to some, but I think it is greatly preferable to having 20+ developers use a "free for all" approach to refactoring a large system.  Some refactorings will take place on a high-level (e.g. how will module X communicate with module Y), in which case you will need people who can make calls at the appropriate level.  Not every developer in the team should be making architectural decisions, so a hierarchy is almost imposed in any case, even if one chooses to be ignorant of it.

So basically, there are tools to meet the basic requirement you put forth, but no tool is going to replace proper communications and having a small number of people driving the general architecture of your project.


答:
Ensure developers are assigned specific modules.

Have a task/bug tracking system that tracks every refactoring change. Assign each issue to only one developer

Some version control systems have the ability to lock a file so that only one developer can have update rights over the file. I have never used that feature but if developers are constantly stepping over each other, this is something you may want to consider.

Have unit tests so that even if developers work on the same file, you know their changes don't break the app in any way.

All of the above would help if your refactoring is contained within modules. However, if someone does a refactoring on a cross-cutting concern such as logging or security, it will affect many files by definition. Those need to be handled with care especially if you have not taken advantage of aop approaches already.


问:
What should take precedence: YAGNI or Good Design?
At which point should YAGNI take precedence against good coding practices and vice versa?  I'm working on a project at work and want to slowly introduce good code standards to my co-workers (currently there are none and everything is just kind of hacked together without rhyme or reason), but after creating a series of classes (we don't do TDD, or sadly any kind of unit testing at all) I took a step back and thought it's violating YAGNI because I pretty much know with certainty that we don't require the need to extend some of these classes.

Here's a concrete example of what I mean: I have a data access layer wrapping a set of stored procedures, which uses a rudimentary Repository-style pattern with basic CRUD functions.  Since there are a handful of methods that all my repository classes need, I created a generic interface for my repositories, called IRepository.  However, I then created a "marker" interface (i.e. interface that doesn't add any new functionality) for each type of repository (e.g. ICustomerRepository) and the concrete class implements that.  I've done the same thing with a Factory implementation to build the business objects from DataReaders/DataSets returned by the Stored Procedure; the signature of my repository class tends to look something like this:

```<code>public class CustomerRepository : ICustomerRepository
{
    ICustomerFactory factory = null;

    public CustomerRepository() : this(new CustomerFactory() { }

    public CustomerRepository(ICustomerFactory factory) {
        this.factory = factory;
    }

    public Customer Find(int customerID)
    {
        // data access stuff here
        return factory.Build(ds.Tables[0].Rows[0]);
    }
}
</code>```

My concern here is that I'm violating YAGNI because I know with 99% certainty that there is never going to be a reason to give anything other than a concrete CustomerFactory to this repository; since we don't have unit tests I don't need a MockCustomerFactory or similar things, and having so many interfaces might confuse my co-workers.  On the other hand, using a concrete implementation of the factory seems like a design smell.

Is there a good way to come to a compromise between proper software design and not overarchitecting the solution?  I'm questioning if I need to have all of the "single implemenation interfaces" or if I could sacrifice a bit of good design and just have, for example, the base interface and then the single concrete, and not worry about programming to the interface if the implementation is that will ever be used.

答:
You're creating an interface anticipating multiple implementations in the future. You might as well have an I<class> for every class in your codebase. Don't.

Just use the single concrete class according to YAGNI. If you find you need to have a "mock" object for testing purposes, turn the original class into an abstract class with two implementations, one with the original concrete class and the other with the mock implementation.

You will obviously have to update all the instantiations of the original class to instantiate the new concrete class. You can get around that by using a static constructor up front.

YAGNI says not to write code before it needs to be written.

Good design says to use abstraction.

You can have both. A class is an abstraction.


答: Technology cannot solve social problems. You need to get your developers to talk to each other and coordinate their work. With 20 teams, some structure and rules will be essential. You will want to support them with technological solutions, but people come first.</p>