问:
When and how to use the advanced features of git?
I'm not exactly a new git user but I have never used any of its advanced features such as tags, branches, merging and others. I haven't even used anything equivalent features from other VCS software. My projects have been so simple that I have only needed commits and sometimes diffs.

Now I'm planning to open-source a server project of mine which probably will get a lot bigger and it probably needs to be organized better. Git can probably help me with that but how?

The development methods are scrum and TDD if that matters.

答:
Here's my short-list cheat sheet I use for OSS development

Day-to-day commands

```<code># Update the working copy from the trunk
git pull --rebase
</code>```

If you aren't the project owner you will use this command more than anything. Basically, pull the latest changes and change to the current version all in one step.

```<code># Goes back one commit in case something was forgotten
git reset --soft HEAD^
</code>```

Unless you write perfect code with 0 conflicts (don't worry, you don't) you'll need to go back and resolve issues. This drops back one revision so you can add whatever you forgot.

```<code># Reverts the working copy back to the trunk revision
git reset HEAD~
</code>```

Resets the repository to the HEAD revision. If there are multiple users working on the same codebase, it saves a lot of headaches to save away your changes and pull the latest commit before committing. The key is to keep the tree as clean as possible to cut down on the amount of conflicts/issues/headaches.

```<code># Gives a summary of a commit without executing it
git commit -a --dry-run
</code>```

Doing a dry run on a commit will let you know where conflicts exist without actually committing the code. Resolving conflicts before the actual commit is easier than after.

Making sure your commits go in clean is essential to maintaining a clean revision tree. especially when there are multiple devs working on a project in parallel.

```<code># Amend the log from the last commit
git commit --amend
</code>```

Nothing special but extremely useful. It lets you edit the last commit. If you're working on a team project, making good notes about commits is essential. This saves from having to go through all the effort of a soft reset to make the change.

```<code># Saves the uncommited changes
git stash save

# Shows a listing of the saved stashes
git stash list

# Applies the stash @ ID 0
git stash apply stash@{0}

# Removes a stash @ ID 0
git stash drop stash@{0}
</code>```

Sometimes you need the latest revision but your current branch isn't complete enough to save away as a commit. The quick-and-easy approach is to stash those changes away. It's also useful if you're just doing a few throwaway experiments that don't justify the creation of another branch.

Branching

```<code># Lists the branches
git branch

# Creates a branch
git branch <branchname>

# Deletes a branch (branch must be merged with HEAD)
git branch -d <branchname>

# Deletes a branch (Irrespective of its merged status)
git branch -D <branchname>

# Checks out a branch
git checkout <branch>

# Creates a branch and then checks it out
git checkout -b <branch_name>
</code>```

If there is more than one dev working on a code base then you should both be working on your own branches. The master should contain the current revision of the code with nothing extra. Changes to the master should be minimized because that's what the other devs are going to pull before they merge/rebase/push their new changes.

I repeat, any code that is in flux should remain on a separate branch. This is git not SVN we're talking about. It's not like it's hard to use branches.

Patching

If you're sane, you'll restrict push access to the repository to only the most skilled/trusted developers. If a dev steps in and wants to commit some changes ask them to submit a patch (or patches). Review them closely before committing.

```<code># Creates a patch from the last commit
git format-patch -1

# Creates a patch from the last commit
git format-patch -o ../_patch/ --start-number 0 -1

# Applies and commits a patch
git am ../_patch/*

# Applies and commits all the patches in a specified directory
git am --directory=../_patch/*
</code>```

All these are convenient variations of 'git format-patch' and 'git am'. The first is obvious, the second makes is so you can create multiple patches in one shot and output them to a different folder. If you change the -1 to a different number to specify the number of commits that will be changed into patches.

Remoting

Lets say that you've been collaborating with another developer who is submitting a ton of commits but you still don't want to grant push access. Well, branching gets to be a serious pain after a while. Isn't git supposed to be capable of using branches from multiple repositories. Yes, it is and here's how.

First create a remote repository (I used to use Gitorious but YMMV). To track the link to that repository you'll need to create a remote. Think of a remote as a web link to another repository.

```<code># Create a remote
git remote add <remoteName> <remote_url>

# Cleans the remotes
git remote prune <remoteName>
</code>```

First you want to update your listing of branches so you fetch the status of the remote branches.

```<code># Updates the status of the remote branch
git fetch
</code>```

Looking at remote branches is nice but you want to make changes to those branches so you should create a remote tracking branch.

```<code># Creates a remote tracking branch
git branch --track <remote> <branch>
</code>```

When you work with a remote tracking branch it's like working with the master/origin branch. It's linked to a remote server so you can push/pull changes except it can point to a completely different repository.

The workflow for a developer using a side-repository for mainstream development is to create the remote repository. Develop/commit/push his/her changes to that repository. Then the project owner/maintainer can also checkout the same remote tracking branches to pull/QC/test those changes before merging/rebasing them into the master branch.

This is how forking a project works. A subset of the development team breaks off of the main branch and creates their own independent line of development. They may selectively pull commits from the parent project (by keeping a remote tracking branch for the master branch of the parent repository) and the parent project may selectively pull commits from the child project (by keeping a remote tracking branch for the master branch of the child repository).

The concept of local commits and the ease of branching (and remote branching) make forking a tree of development as easy as typing in a few commands.

The hardest part about git is the sucky documentation.

Note: After reading a few of the replies, I realized that I have been under-utilizing the 'fetch' command. While my old workflow was based on pulling the latest on always merging/rebasing onto a clean master branch, I can see how updating the master and doing some dry runs before merging/rebasing would save time correcting conflicts.

Body:
Here's my short-list cheat sheet I use for OSS development

Day-to-day commands

# Update the working copy from the trunk
git pull --rebase

If you aren't the project owner you will use this command more than anything. Basically, pull the latest changes and change to the current version all in one step.

# Goes back one commit in case something was forgotten
git reset --soft HEAD^

Unless you write perfect code with 0 conflicts (don't worry, you don't) you'll need to go back and resolve issues. This drops back one revision so you can add whatever you forgot.

# Reverts the working copy back to the trunk revision
git reset HEAD~

Resets the repository to the HEAD revision. If there are multiple users working on the same codebase, it saves a lot of headaches to save away your changes and pull the latest commit before committing. The key is to keep the tree as clean as possible to cut down on the amount of conflicts/issues/headaches.

# Gives a summary of a commit without executing it
git commit -a --dry-run

Doing a dry run on a commit will let you know where conflicts exist without actually committing the code. Resolving conflicts before the actual commit is easier than after.

Making sure your commits go in clean is essential to maintaining a clean revision tree. especially when there are multiple devs working on a project in parallel.

# Amend the log from the last commit
git commit --amend

Nothing special but extremely useful. It lets you edit the last commit. If you're working on a team project, making good notes about commits is essential. This saves from having to go through all the effort of a soft reset to make the change.

# Saves the uncommited changes
git stash save

# Shows a listing of the saved stashes
git stash list

# Applies the stash @ ID 0
git stash apply stash@{0}

# Removes a stash @ ID 0
git stash drop stash@{0}

Sometimes you need the latest revision but your current branch isn't complete enough to save away as a commit. The quick-and-easy approach is to stash those changes away. It's also useful if you're just doing a few throwaway experiments that don't justify the creation of another branch.

Branching

# Lists the branches
git branch

# Creates a branch
git branch <branchname>

# Deletes a branch (branch must be merged with HEAD)
git branch -d <branchname>

# Deletes a branch (Irrespective of its merged status)
git branch -D <branchname>

# Checks out a branch
git checkout <branch>

# Creates a branch and then checks it out
git checkout -b <branch_name>

If there is more than one dev working on a code base then you should both be working on your own branches. The master should contain the current revision of the code with nothing extra. Changes to the master should be minimized because that's what the other devs are going to pull before they merge/rebase/push their new changes.

I repeat, any code that is in flux should remain on a separate branch. This is git not SVN we're talking about. It's not like it's hard to use branches.

Patching

If you're sane, you'll restrict push access to the repository to only the most skilled/trusted developers. If a dev steps in and wants to commit some changes ask them to submit a patch (or patches). Review them closely before committing.

# Creates a patch from the last commit
git format-patch -1

# Creates a patch from the last commit
git format-patch -o ../_patch/ --start-number 0 -1

# Applies and commits a patch
git am ../_patch/*

# Applies and commits all the patches in a specified directory
git am --directory=../_patch/*

All these are convenient variations of 'git format-patch' and 'git am'. The first is obvious, the second makes is so you can create multiple patches in one shot and output them to a different folder. If you change the -1 to a different number to specify the number of commits that will be changed into patches.

Remoting

Lets say that you've been collaborating with another developer who is submitting a ton of commits but you still don't want to grant push access. Well, branching gets to be a serious pain after a while. Isn't git supposed to be capable of using branches from multiple repositories. Yes, it is and here's how.

First create a remote repository (I used to use Gitorious but YMMV). To track the link to that repository you'll need to create a remote. Think of a remote as a web link to another repository.

# Create a remote
git remote add <remoteName> <remote_url>

# Cleans the remotes
git remote prune <remoteName>

First you want to update your listing of branches so you fetch the status of the remote branches.

# Updates the status of the remote branch
git fetch

Looking at remote branches is nice but you want to make changes to those branches so you should create a remote tracking branch.

# Creates a remote tracking branch
git branch --track <remote> <branch>

When you work with a remote tracking branch it's like working with the master/origin branch. It's linked to a remote server so you can push/pull changes except it can point to a completely different repository.

The workflow for a developer using a side-repository for mainstream development is to create the remote repository. Develop/commit/push his/her changes to that repository. Then the project owner/maintainer can also checkout the same remote tracking branches to pull/QC/test those changes before merging/rebasing them into the master branch.

This is how forking a project works. A subset of the development team breaks off of the main branch and creates their own independent line of development. They may selectively pull commits from the parent project (by keeping a remote tracking branch for the master branch of the parent repository) and the parent project may selectively pull commits from the child project (by keeping a remote tracking branch for the master branch of the child repository).

The concept of local commits and the ease of branching (and remote branching) make forking a tree of development as easy as typing in a few commands.

The hardest part about git is the sucky documentation.

Note: After reading a few of the replies, I realized that I have been under-utilizing the 'fetch' command. While my old workflow was based on pulling the latest on always merging/rebasing onto a clean master branch, I can see how updating the master and doing some dry runs before merging/rebasing would save time correcting conflicts.


问:
Can modern OO languages compete with C++'s array store performance?
I just noticed that every modern OO programming language that I am at least somewhat familiar with (which is basically just Java, C# and D) allows covariant arrays. That is, a string array is an object array:

```<code>Object[] arr = new String[2];   // Java, C# and D allow this
</code>```

Covariant arrays are a hole in the static type system. They make type errors possible that cannot be detected at compile-time, so every write to an array must be checked at runtime:

```<code>arr[0] = "hello";        // ok
arr[1] = new Object();   // ArrayStoreException
</code>```

This seems like a terrible performance hit if I do lots of array stores.

C++ does not have covariant arrays, so there is no need to do such a runtime check, which means there is no performance penalty.

Is there any analysis done to reduce the number of runtime checks necessary? For example, if I say:

```<code>arr[1] = arr[0];
</code>```

one could argue that the store cannot possibly fail. I'm sure there are lots of other possible optimizations I haven't thought of.

Do modern compilers actually do these kinds of optimizations, or do I have to live with the fact that, for example, a Quicksort always does O(n log n) unnecessary runtime checks?

Can modern OO languages avoid the overhead created by supporting co-variant arrays?

答:
You asked about other modern OO languages? Well, Delphi avoids this problem entirely by having string be a primitive, not an object.  So an array of strings is exactly an array of strings and nothing else, and any operations on them are as fast as native code can be, with no type checking overhead.

However, string arrays are not used very often; Delphi programmers tend to favor the TStringList class.  For a minimal amount of overhead it provides a set of string-group methods that are useful in so many situations that the class has been compared to a Swiss Army Knife.  So it's idiomatic to use a string list object instead of a string array.

As for other objects in general, the problem does not exist because in Delphi, like in C++, arrays are not covariant, in order to prevent the kind of type system holes described here.

OwnerDisplayName: FredOverflow

ContentLicense: CC BY-SA 3.0


答:
From test I have done on a cheap laptop, the difference between using int[] and Integer[] is about 1.0 ns.  The difference is likely to be due to the extra check for the type.

Generally Objects are only used for higher level logic when not every ns counts.  If you need to save every ns, I would avoid using higher level constructs like Objects. Assignments alone are likely to be very small factor in any real program. e.g. creating a new Object on the same machine is 5 ns.

Calls to compareTo are likely to be much more expensive, esp if you using a complex object like String.

Title: Can modern OO languages compete with C++'s array store performance?

Body:
I just noticed that every modern OO programming language that I am at least somewhat familiar with (which is basically just Java, C# and D) allows covariant arrays. That is, a string array is an object array:

```<code>Object[] arr = new String[2];   // Java, C# and D allow this
</code>```

Covariant arrays are a hole in the static type system. They make type errors possible that cannot be detected at compile-time, so every write to an array must be checked at runtime:

```<code>arr[0] = "hello";        // ok
arr[1] = new Object();   // ArrayStoreException
</code>```

This seems like a terrible performance hit if I do lots of array stores.

C++ does not have covariant arrays, so there is no need to do such a runtime check, which means there is no performance penalty.

Is there any analysis done to reduce the number of runtime checks necessary? For example, if I say:

```<code>arr[1] = arr[0];
</code>```

one could argue that the store cannot possibly fail. I'm sure there are lots of other possible optimizations I haven't thought of.

Do modern compilers actually do these kinds of optimizations, or do I have to live with the fact that, for example, a Quicksort always does O(n log n) unnecessary runtime checks?

Can modern OO languages avoid the overhead created by supporting co-variant arrays?


问:
What happened to Borland Delphi?
I have the impression that Delphi isn't very popular anymore. But now at work I had to make some changes to an old Delphi program that we are still using. I used Borland Developer Studio 2006 and it was very pleasant and intuitive to work with, even though I had practically no previous exposure to it. Is Delphi still widely-used and I am simply not aware of it or are there other reasons for its decline? </p>

答:
One aspect that a lot people have either ignored or somehow missed: Delphi failed to stay relevant.

When D1 came out in ('94?) there were only two development choices: Desktop or Server.  By D4 companies were basically testing the waters with Internet development.  By D7, a new application was more likely to be run in a browser than on the desktop.

Unfortunately, Delphi didn't change.  Around this time most compiler companies started failing.  Corporate was moving to the web and embracing those languages.

To be sure, there were new Desktop applications being built, but quite frankly the mainstream had moved on.

Yes, Borland screwed up, royally, but the main problem was that they didn't embrace the web.  .Net and Java did and won the hearts and minds of the vast majority of the development staff.  Even Delphi.Net was a miserable failure.  Either too little too late or simply bad execution, I'm not sure.

Unless Embarcadero changes direction, Delphi will continue to be a Desktop only product and it's potential market share will continue to shrink.  I understand that they have increased sales, but increasing sales in a shrinking marketplace isn't exactly where they need to be.  I suspect a lot of those sales are simply coming from companies switching away from other failures in that space.

I loved Delphi.  However, I, like many others, outgrew it over 10 years ago.  If we're lucky it will grow up too.

Title: What happened to Borland Delphi?


问:
open source flash environments
I have been looking for a really good open source flash development environment with no success.  The best I could find would help in the development of pretty much everything, but I still needed to have Adobe Flash Professional in order to compile my work.  Is there a way I can develop Flash applications and not need to purchase Flash Pro?</p>

答: FlashDevelop is a reasonable IDE, and one could use something like Sam Haxe to compile the resources down to an SWF file. I'm back to being a student again, so I qualify for the very much reduced price academic versions of the creative suites. Suites starting with CS4 will require you to send them your student ID. CS3 and below won't. </p>

Title: open source flash environments


问:
Strategy for building an application to replace a large spreadsheet
I'm working on an application that is going to replace a rather large spreadsheet. The spreadsheet is used to budget purchases and things like that. It is the largest spreadsheet I have ever seen, and it required a lot of manual data entry, so this application is going to automate much of that.

But as I'm working on this I've noticed its slow going. And I got to thinking this must be a common thing to do many companies will start with something like a spreadsheet, then when they get too big to maintain that, they will get a custom application built. So is there anything out there ( a framework or similar ) that does this sort of thing, migrating a spreadsheet to a custom application.

I've had a quick Google but not really seen the kind of thing that I'm looking for.

It's too late for this project, but I thought it would be worth having a look for next time.

How do you guys tackle this problem?

答:
I'm pretty sure this is easiest to do in the .NET framework.

Found on codeproject.com: Component for Fast Pass/Retrieve Data from Excel

Gembox has some proprietary software for doing this, and a free version here.

You may also want to look into COM Interop.


答:
It depends on what it is that you're trying to do.

If you're looking for something that provides you with functionality that Flash Pro provides (such as timelines, library imports, etc), then no, there's nothing that will replace that (you can replicate the library functionality with compiler options, but that requires knowledge of the compilers and writing your own pipeline).

If you're happy replacing that functionality with code (i.e. animating your own timeline/path based animations, masks, etc) then there are a few options available.

FlashDevelop (as mentioned by Tangurena) is a great IDE and I fully recommend it to anyone working with Flash, whether on personal or professional projects. It installs the FlexSDK as part of its installation routine and uses the compilers (mxmlc and compc contained therein).

The FlexSDK is open source and therefore the compilers and utilities are free for use (but it's always good to check with your legal department prior to using it if it's for commercial use).

Title: open source flash environments

Body: I have been looking for a really good open source flash development environment with no success.  The best I could find would help in the development of pretty much everything, but I still needed to have Adobe Flash Professional in order to compile my work.  Is there a way I can develop Flash applications and not need to purchase Flash Pro?</p>


答:
Spreadsheets are hard to replace because they are very much free-form. Replacing them is only marginally better than replacing a "paper and pencil application": in both cases, you will be writing an application pretty much from scratch.

My strategy would be to interview the key users of the spreadsheet, and find out how they use it to get the results that they need. Pay special attention when the users talk about modifying excel formulas: these are potential targets of customization in your future application.

I imagine there would be many kinds of results that they might expect from the mother-of-all-spreadsheets behemoth, so have them prioritize the things that they are looking to get from your application. Agree on a small subset of the features that would provide a complete end-to-end user experience, and start building. Show your work to your end users, gather feedback, and keep adding new features until your users are satisfied.

Title: Strategy for building an application to replace a large spreadsheet

Body:
I'm working on an application that is going to replace a rather large spreadsheet. The spreadsheet is used to budget purchases and things like that. It is the largest spreadsheet I have ever seen, and it required a lot of manual data entry, so this application is going to automate much of that.

But as I'm working on this I've noticed its slow going. And I got to thinking this must be a common thing to do many companies will start with something like a spreadsheet, then when they get too big to maintain that, they will get a custom application built. So is there anything out there ( a framework or similar ) that does this sort of thing, migrating a spreadsheet to a custom application.

I've had a quick Google but not really seen the kind of thing that I'm looking for.

It's too late for this project, but I thought it would be worth having a look for next time.

How do you guys tackle this problem?


问:
Defining Rank names for employees
I want to create a list of ranks for the employees in my company. We are an open source integrator that works usually with existing solutions and also building custom solutions.

We don't want to name our employees as normal senior consultant, trainee and we would like give them ranks as forums do to the users.

Does anyone have any suggestion for this?

答:
WARNING:

Keep monetary rewards separate from social rewards.

Please read this article for further explaination.

Title: Defining Rank names for employees

ContentLicense: CC BY-SA 2.5


问:
Intelligence as a vector quantity
I am reading this wonderful book called "Coders at Work: Reflections on the Craft of Programming" by Peter Seibel and I am at part wherein the conversation is with Joshua Bloch and I found this answer which is an important point for a programmer. The paragraph, goes something like this.

There's this problem, which is, programming is so much of an
  intellectual meritocracy and often these people  are the smartest
  people in the organization; therefore they figure they should be
  allowed to make all the decisions. But merely the fact they are the
  smartest people in the organization does not mean that they should be
  making all the decisions, because intelligence is not a scalar
  quantity; it's a vector quantity.

Here at the last sentence, I fail to get the insight which is he trying to share. Can someone explain it in a little further as what he means by a vector quantity, possibly trying to present the same insight.

Further down, I get the point that he is not taking about having an organization where non-technical people (sometimes clueless) can be managers of the technical people for some reason that they can spend more time to write emails well, because the very next statement following the above paragraph was.

And if you lack empathy or emotional intelligence, then you shouldn't
  be designing APIs or GUIs or languages.

I understand that he is saying that in Software engineering, programmers should know how the users will see their product and design for them.

I felt the above paragraph was very interesting.

答:
… because intelligence is not a scalar quantity; it's a vector quantity.

I can't speak for the author, but I would read it as an analogy to the fact that there is not a single dimension for practical intelligence as a programmer.

Another way to put it might be that some people are awesome at dealing with people, some people are awesome at dealing with hard computer science problems, and some people are awesome at writing well engineered code.

None of them are "more intelligent" than the other, they are equally intelligent and equally skilled at different things - but unequally skilled at the same things.

I understand that he is saying that in Software engineering, programmers should know how the users will see their product and design for them.

I read that as saying that if you don't have the skills to understand how users of the tool work, how they feel, how they thing, then you shouldn't be designing the interface they work with.  (Which includes the API, for values of "users" == "programmers")

In other words: just because you are awesome at one thing, don't assume you are awesome at everything.

Title: Intelligence as a vector quantity


答:
I've made some webcam experiments using swfc (it's a crazy language but it's good for putting objects on scenes and doing some as2) and as3compile straight out of the SWFtools toolset.

You have to bridge the gap between its own documentation and the Adobe one with some faith and imagination, but it somehow delivers.

Title: open source flash environments


问:
When am I ready to start using Jquery for Javascript?
I was told not to use Jquery as a beginner because it would hamper my learning of Javascript.  Now I've read a couple books on Javascript, read loads of sites, and made a Javascript web app.  Am I ready for Jquery? If not, then how will I know when I'm ready?</p>

答:
You don't have to listen to everything people say. Just download jQuery and start using it. Who cares if someone told you not to use it while you're a "beginner"?

The point is to write the best code you can, not to be a slave to every silly opinion another programmer has.

OwnerDisplayName: Cornucopia

LastEditorDisplayName: Cornucopia


答:
A vector has both a magnitude and a direction.  He is saying you can't describe intelligence by just its magnitude.  You must also know the direction the intelligence is pointed toward.  Einstein said:

“Everybody is a genius. But if you judge a fish by its ability to climb a tree, it will live its whole life believing that it is stupid.”

Bloch is saying don't assume your organization's best swimmer is just as good at climbing trees.

Title: Intelligence as a vector quantity

Body:
I am reading this wonderful book called "Coders at Work: Reflections on the Craft of Programming" by Peter Seibel and I am at part wherein the conversation is with Joshua Bloch and I found this answer which is an important point for a programmer. The paragraph, goes something like this.

There's this problem, which is, programming is so much of an
  intellectual meritocracy and often these people  are the smartest
  people in the organization; therefore they figure they should be
  allowed to make all the decisions. But merely the fact they are the
  smartest people in the organization does not mean that they should be
  making all the decisions, because intelligence is not a scalar
  quantity; it's a vector quantity.

Here at the last sentence, I fail to get the insight which is he trying to share. Can someone explain it in a little further as what he means by a vector quantity, possibly trying to present the same insight.

Further down, I get the point that he is not taking about having an organization where non-technical people (sometimes clueless) can be managers of the technical people for some reason that they can spend more time to write emails well, because the very next statement following the above paragraph was.

And if you lack empathy or emotional intelligence, then you shouldn't
  be designing APIs or GUIs or languages.

I understand that he is saying that in Software engineering, programmers should know how the users will see their product and design for them.

I felt the above paragraph was very interesting.


问:
How do you evaluate a small piece of code?
I'm creating a website based on users' code, a place where they can share code in a social way and one of the features I'm currently developing is Code Review.

This feature will allow users to evaluate code in certain aspects, from the top of my head I came out with things like:

Legibility,

Performace and

Modularity.

What are the general characteristics that you evaluate when reviewing code?

答:
AFAIK, most languages have some form of a lint program (i.e. jslint for Javascript, FlexPMD for Actionscript, pep8 and pylint for Python, etc.).

I would strongly suggest relying on standards set by the respective communities and using OS tools to parse code that you're hosting. If you were to couple this with peer reviews, you'd have yourself a pretty strong code review system. Linting is something that should be in any strong developer's pipeline, so I'd expect that most developers would like having this built into an automated system for them rather than having to build it into their pipelines (i.e. makefiles) themselves.


问:
What you should do if your junior did not adopt your suggestion?
I am leading a team of 3-4 junior developers. My job-- besides writing code-- is to provide supervision and guidance for the juniors.

But, I fully understand how much developers cherish autonomy in their work, and I don't want to destroy their intrinsic motivation by spoon-feeding them with my thoughts and my algorithms; I want them to explore the problem in their own ways, and think about it themselves and only come to me when they are really facing insurmountable issues.

When they do come to me, sometimes I would have to propose a completely different algorithm to solve the problem because their algorithm isn't robust enough ( remember, I am the senior and I have seen more than them). Of course I would explain this in a nice manner so as not to hurt their feelings, and I would gently outline how my solution is vastly superior than theirs, no condescending tone or condemning words.

But still, they are sometimes reluctant to accept my suggestion, partly because they have invested so much in their own algorithm, or partly because of the fear that using a new method would entail more learning time and make them appear to the management as if they are going nowhere. But deep in my heart I know very well that my algorithm is much better than theirs and they should just adopt it.

What should I do if they didn't adopt my suggestion? Should I just ask them to follow my way, or should I just let them have their heads banged on the wall many many more times and wait for them to come back to me? Doing the former makes me into a dictator, but doing the later would cost us precious development time and incur bug fixing cost. I am really in a dilemma here.

答:
Help them to understand why they should make your suggested change. And listen to them if they have a good reason not to make the change. Have a discussion, and come to an agreement on the basis of what is the best thing to do.

This approach is important for the following reasons:

You want them to be making the change because of solid business/technical reasons. It's important to be clear on what these are (any remember that you could also be wrong, so be humble....).

You really want to convey the reasoning behind your suggestion - that way the recipient will learn to solve similar problems themselves in the future. You'll also have a better relationship if your juniors feel that they are learning some good insights from you.

You won't be respected if you use your seniority and can't demonstrate that you actually have good reasons.

Your boss would presumably like to be confident that you are using your juniors' time effectively on things that create real value, not just "doing it my way" for the sake of it.

If you are smart, you can also get them to come to the answer just by asking questions. Done right, your junior will come to the correct conclusion themselves (and therefore be much more willing to implement it). Example questions:

Your code assumes access to the production database. How could we change that so that it will still work and can be correctly tested by JUnit in a disconnected development environment? (potential answer: ah! we should use dependency injection....)

What will happen if an attacker deliberately sent some cleverly constructed SQL in your online data entry form? (potential answer: ah! perhaps we shouldn't construct SQL statements by concatenating unverified text from the internets)

EDIT: If you succeed in persuading your junior that the right thing to do is to follow your suggestion, but they are still reluctant than here is some additional advice:

Explore why they are reluctant. It is possible that they need to come to a personal realisation that it doesn't matter if you throw code out, provided you get the result. Or it could be that they feel under time pressure because of some deadline. You need to know, otherwise you can't help them.....

You can make the point that they can treat the change as a way to improve their refactoring skills. Once refactoring skills are good enough, you should be able to re-purpose even a fairly large and complex code base relatively quickly.

You should emphasise that everything will be in source control, so they can always revert back to an old version if needed.


答:
I hated my last Team Leader's overbearing attitude but respect him for the fact that he had superior technical knowledge and he taught me a lot without lecturing me. Most importantly he never forced me go with his plan. He would play Devil's advocate with my plan, forcing me to prove that my plan was flawless. He would look for loopholes and wait for my explanation as to why it isn't a loophole or is a less expensive solution. He would ask me if there are any alternative solutions and propose some ideas if I didnt have any. I would have to evaluate his ideas and that his plan wasnt optimal or If he was convinced that my plan was right or at least had the same risk-reward ratio as his, he would give the go-ahead. If I failed  with my idea I would have to try his solution.

There has to be a tradeoff between liberty and deadlines. You dont have the luxury of extending the deadline and you cannot let your juniors breach it. You must be polite but firm with them that once they have tried their algorithm and didnt get it working, they have a duty to listen to you. Prove by example that you know your stuff. But, equally important make them learn, dont teach them.

Title: What you should do if your junior did not adopt your suggestion?

Body:
I am leading a team of 3-4 junior developers. My job-- besides writing code-- is to provide supervision and guidance for the juniors.

But, I fully understand how much developers cherish autonomy in their work, and I don't want to destroy their intrinsic motivation by spoon-feeding them with my thoughts and my algorithms; I want them to explore the problem in their own ways, and think about it themselves and only come to me when they are really facing insurmountable issues.

When they do come to me, sometimes I would have to propose a completely different algorithm to solve the problem because their algorithm isn't robust enough ( remember, I am the senior and I have seen more than them). Of course I would explain this in a nice manner so as not to hurt their feelings, and I would gently outline how my solution is vastly superior than theirs, no condescending tone or condemning words.

But still, they are sometimes reluctant to accept my suggestion, partly because they have invested so much in their own algorithm, or partly because of the fear that using a new method would entail more learning time and make them appear to the management as if they are going nowhere. But deep in my heart I know very well that my algorithm is much better than theirs and they should just adopt it.

What should I do if they didn't adopt my suggestion? Should I just ask them to follow my way, or should I just let them have their heads banged on the wall many many more times and wait for them to come back to me? Doing the former makes me into a dictator, but doing the later would cost us precious development time and incur bug fixing cost. I am really in a dilemma here.


答:
Do you control push access to the repository?

In open source, push access is always controlled by a gatekeeper who is in charge of enforcing quality. If you are actively monitoring the commits they're pushing, you should be acutely aware of where they can improve.

Do they get to hack on or improve your code. If they get a chance to see the internals about how your code works they may learn how to adapt to your style better. If you're pushing your suggestions without accepting suggestions with an open mind then they will be less inclined to listen to your opinion.

There are some circumstances where there's no right answer (such as coding style preferences). In that case, try to establish (or enforce) a company-wide policy so they understand that the style of the code should be geared to be consistent with the main codebase. Using an already-established style guideline (like Microsofts style guide for C#) is the best way to go, especially for new developers on the team.

If you're making blanket statements about their coding techniques, there's a pretty good chance that you don't completely understand the reasoning behind their choices. Just the tone of your question makes you sound arrogant. What do you gain/sacrifice by pushing your approach on the younger developers?

The key question you need to ask yourself is, are your suggestions geared to maintain/improve the quality of the codebase or to assert your dominance/superiority over your peers? The former is simple quality control and can be justified as such, the ladder is detrimental to the team dynamic whether or not your right.

Either way, if you want to push your solution onto your peers you should have concrete proof that it is, in fact superior. A magnitude increase in performance should be easy enough to improve, anything less isn't worth the effort (excepting performance critical applications). Forcing your work on others to justify your personal sense of superiority will end with you being singled out as the 'crotchety old guy'.

Note: The best and most talented programmers I have encountered over the years always seemed to be the ones who were willing to stop and explain the back story behind where they originated their approach.


答:
Learning really only happens where failures occurs, because failure is a motivator and provides memory cues for recall in the future.  This is essentially what we call experience, and good experience in the workplace will come from having failed and learned from the failures. If your juniors were capable of getting everything correct first time, either they wouldn't be learning anything, or they wouldn't be juniors.

If you have too many juniors messing things up, perhaps your company has staffed incorrectly, with too many junior grade developers where time constraints require better experienced people to minimize your risks, yet even then you can have problems and delays, as senior developers make mistakes to learn from as well.

Your juniors will need to learn and gain experience in order to be able to cope in an environment where the deadlines are tight.  As a team leader, it is your job to set an example and inspire your juniors to work efficiently, however the reality is that you have to set aside concerns of personal pride and concerns for your tight schedules if you want your juniors to actually learn something, and therefore you need to allow them to fail. Therefore, it is your job to make a call.  Sometimes you need to give the junior the space to fail, and then take them patiently through a review process to show them where they could improve their ideas.  At other times, you need to put your foot down, but do it in a way that allows you to show that doing so is out of a genuine need which doesn't reflect poorly on your junior's abilities per-se. If however you do head down this path, you must expect a certain amount of hand-holding and therefore it is up to you to decide if the extra burden on your time is worth it, or if you'd be better of just leaving your junior to fail and learn.

As for the issue of tight deadlines, this is where you need to schedule and allocate your work according to the relative strengths and weaknesses within your team.  Ultimately the buck stops with you.  When you are in charge of others you're not there to be everyone's friend, you're there to get a difficult job done under difficult circumstances. How you keep everyone on your side comes down to talking people through your concerns and issues, making a reasonable case for why you need your team members to do something in a particular way.

From my own personal experiences, you need to reserve a set amount of time with your junior to discuss the strengths and weaknesses of both ideas and then collaboratively look forthe best solution that will solve the problem at hand - even at the risk of allowing yourself to be proven wrong - and then move forward.  If you both can't reach a consensus by the end of your allocated time, then at that point you need to wind up the meeting with a summary that takes into account the concerns discussed and notes that no consensus has been reached. Regardless of the outcome of your meeting, you thank your junior for the time spent, and indicate that you will return with your decision shortly.  After careful consideration of your discussion you will have the option to either allocate additional time for further discussion, or instruct the junior to go ahead with whichever plan you have settled on subject to the outcome of your meeting.

Yes, time is precious at times, however when you choose to take on juniors you need to accept that you are taking on a responsibility to invest in and nurture their professional development, and you need to accept that as a result it will for a while at least cost you time.


答:
If it is a requirement, then note it as that.  If it is only a suggestion, as you note, then they should be free to do it otherwise.  Some questions I would ask:

Do you have the authority to push for specific solutions?

What is the extent for that authority?

Is there solution bad or just different?

I am sure you could ask more, but the first two focus on your authority and the last on whether the issue is really worth pushing.

The following answer has some great additional points and I would add here that you need to treat it more as a collaborative process where you work through at least some of these with your "team" rather than just issuing dictates to them.  They will learn as they work through the issues with you more than just being told, "consider doing it this way."


答:
Well this seems interesting and very much natural with young programmers very much attached to the code they have written, maybe they have spent quite some time in arriving at the same or they picked it from some good site (SO indeed, Hey Jon skeet wrote this man ! !).

Nonetheless the basic string attached here is there attachment with the code which is where you would need to concentrate and i think you would need to put in some considerable effort in making them understand that the execution and expected outcome is of more significance then their name being etched on the source repositories for pushing in this code. You will have to draw lines as why your code is better and is also good in terms of maintaining it for future works.

Take into consideration that a few failures is eminent (need a few heart breaks for any attachment) but with gradual effort i think they would come around and would be able to appreciate your efforts better. A bit of time and few failures is what i think you would need. Forcing it upon them would be other way round few success stories and then doomsday and revolt.


答:
You mention performance, will your website have the ability to measure this?

If so, I would think the most important thing to measure would be does it give the correct answer?

Next you could measure memory usage and speed as secondary goals.

Title: How do you evaluate a small piece of code?

Body:
I'm creating a website based on users' code, a place where they can share code in a social way and one of the features I'm currently developing is Code Review.

This feature will allow users to evaluate code in certain aspects, from the top of my head I came out with things like:

Legibility,

Performace and

Modularity.

What are the general characteristics that you evaluate when reviewing code?


问:
What do you think of this new if-then syntax
I was just thinking of something that would be really cool to have in my if-elif-else controls.

```<code>
if condition:
    stuff()
elif condition:
    otherstuff()
then:
    stuff_that_applies_to_both()
else:
    stuff_that_doesnt_aply_to_either()
</code>```

So basically a then will be run when any of the conditions are run EXCEPT the else condition. Do you think this is useful? It's similar to the try-except-else of python.

I think some of you are nitpicking a very preliminary implementation. The then block would be just like the else block in a try-except block in python. The real reason I suggest this is for situations like this.

```<code>
m = {}
if condition == '1':
    m['condition'] = condition
elif condition2 == '3':
    m['condition2'] = condition2
elif condition3 == 'False':
    m['condition3'] = True
then:
    run_test_that_relies_on_one_of_the_conditions_being_true()

return m
</code>```

The then block is scoped to the first if just like the else is. So nesting works fine. And if you need to run a method before the if statements, that really has nothing to do with this use case.

答: I think it looks horrible. If you want code to run after a variety of conditions then either (a) recheck those conditions or (b) set a variable to indicated success status.</p>


问:
Is 'process debt' a term people work with
As a result of a retrospective we were uncovering worse ways of developing
software. We had a idea we though was great and tried it. We stayed with it during the development of a major update which took 3 months. After a retrospective with the maintenance engineers it turn out our idea does not work for them (we had discussions with them before we tried the idea and the also thought it was a great idea). We came to the agreement we better get back to the old situation. The team for the update is dismantled and the maintenance engineers don't have time to do so (although their project manager has agreed to invest the time).

We're now in the situation the maintenance engineers pay the interest each time a minor release has to be made. This is very much like technical debt but has nothing to do with the product itself. Is this called process debt or is this put under the term technical debt? And what would be a good way of dealing with it? (Any other or concrete ideas to make it visible to product managers?)

PS The idea was migrating a 4 product VSS database to SVN. The database heavily leans on shared files and is a mess to untangle and pour in a usable SVN structure. It's very counter intuitive but is seems some things are better kept in VSS.

答:
I hope I have interpreted thing correctly, I would call this technical debt. Software consists of more than just source code. Source is probably less than 10% and no more than 20% of the SDLC effort (At a commercial level at least).  If you cannot reliably and easily build and deploy your source code, causing problems and costing money down the track, it's no different to source code that is hard to maintain, buggy and slow.

The fact you tried something different and it was not as good as what you left behind does not change things either. The software is now in a less maintainable state than it was previously, because of chosen technologies (VSS vs SVN) - technical debt.

The Process Debt you refer to undoubtedly exists, but that's due to the process making you do things that are no longer required. For instance if you had a process that required manual running and markup of a printed test book on each release, but you had implemented automated testing, that would be process debt, as it's something that is no longer relevant due to changes in the way things are done.


问:
How do I approach a coworker about his or her code quality?
I work on a new venture at a large enterprise software company (3000+ programmers). In my group, we have a bunch of projects and people usually work on several projects over the course of a year.

I just started work on a project that has been previously maintained by a buddy of mine (consultant who's been with us for 3+ years) to add some features. I got into the code, and the quality was really quite poor. Whether it was on the UI frontend or the services backend, the code simply wasn't indented, there were hundreds of lines commented out for no apparent reason, documentation was basically non-existent, coding standards weren't applied consistently (e.g. mixing camelCase and under_scored_variables), variable names were unintelligible, datatype choices were wrong, etc. etc.

I'm very much a non-confrontational person, so I don't want to attack my coworker, but I also don't just wanto to go to my boss and complain about his performance. What are the kinds of things I could say to politely mention that the code is poorly structured?

EDIT:

I want to clarify that while I understand there is an element of "Everyone else's code sucks" to all programmers, when I see something like this (names are chosen on purpose and some details left out/changed in this example):

```<code>public void doCalculate(Object argument) {
  if (argument instanceof String) {
    String argument2 = (String) argument;
    if (argument2 == "DataBase") {
      // do something
    } else {
      long argument3;
      try {
        argument3 = Long.parseLong(argument2);
      } catch (Exception e) {
        argument3 = -1;
      }
      // do something completely unrelated
    }
  }
}
</code>```

I think it's objectively fair to say that this is not a good idea. Furthermore, I'm not dealing with a newbie here (I'm only coding 3 years now). He's got maybe 20 years of experience on me. The advice you guys have given so far is great; just wanna make sure that we're not talking about a "fine line" here.

答:
You need to find out two things: What is your goal? How would you like to be approached yourself?

If your colleague, with 20+ years of programming behind him, is really, really open-minded, you can just go talk to him and point out specific examples, tell him why they looked wrong to you and discuss alternatives. Because he's really, really open-minded and keen to learn, he'll listen, a discussion will ensue, and he'll understand your points and you'll both live happily ever after.

In my experience, though, the colleague is most likely programming like that because he just doesn't care about style. It could be because he's really in the wrong job, or it could be because, in 20+ years of programming, he never found a reason to worry about it - maybe his code just works and he moves on.

If the latter is the case, you're just going to waste your and his time, and you may make a dent in your relationship if it turns into an argument. So what is your goal here?

Do you want him to clean up his code so that you can work on nicer code?
Do you want him to learn and improve?
Do you want to feel good about being a better coder?
Do you want your boss to know that you're a better coder than him?

The first one is not going to happen and the third is already established, although you probably want him to recognize it as well - good friend, father figure?

If you really want him to learn and improve, then figure out how you would like to be approached in the reverse situation, and do the same. And figure out what would annoy you, and make sure you don't do that.

The forth one is easy: either you want a better salary, and then you just demand it during the next feedback meeting (it doesn't really matter how good you are in this industry) or you want more responsibility and then you just keep doing a good job until you get it.


问:
Storing hierarchical template into a database
If this title is ambiguous, feel free to change it, I don't know how to put this in a one-liner.

Example:

Let's assume you have a html template which contains some custom tags, like <text_field />. We now create a page based on a template containing more of those custom tags. When a user wants to edit the page, he sees a text field. he can input things and save it.

This looks fairly easy to set up. You either have something like a template_positions table which stores the content of those fields.

Case:

I now have a bit of a blockade keeping things as simple as possible. Assume you have the same tag given in your example, and additionally, <layout> and <repeat> tags. Here's an example how they should be used:

```<code><repeat>
  <layout name="image-left">
    <image /> <text_field />
  </layout>

  <layout name="image-right">
    <text_field /> <image />
  </layout>
</repeat>
</code>```

We now have a block which can be repeated, obviously. This means: when creting/editing a page containing such a template block, I can choose between a layout image-left and image-right which then gets inserted as content element (where content for <image /> and <text_field /> gets stored). And because this is inside a <repeat>, content elements from the given layouts can be inserted multiple times.

How do you store this? Simply said, this could be stored with the same setup I've wrote in the example above, I just need to add a parent_id or something similiar to maintain a hierarchy. but I think I am missing something. At least the relation between an inserted content element and the origin/insertion point is missing. And what happens when I update the template file?

Do I have to give every custom tag that acts as editable part of a template an identifier that matches an identifier in the template to substitue them correctly?

Or can you think of a clean solution that might be better?

答:
First of all, thanks for all your answers. It is even nicer here than on stackoverflow because the answers are having more details in general and can be discussed better.

I have now found a more-or-less-solid solution for this (more-or-less because I am still experimenting with it) which I got accidentally while debugging some css.

My current solution: I use a library that internally splits it up into a hierarchical node list and returns that list as object. On this object, I can traverse and select nodes with either a css selector and also update or replace them.

Using xpath, I don't need to store hierarchical data for basic fields. There are just two fields in my table, xpath and replacement. So, rendering the template recursive also allows to nest things without having hierarchical data stored in mysql, because they are resolved via xpath. I just needed to add another table and a field for the repeat/layout path, but this basically also resolves via xpath.

(This is out of my brain because the project I am needing this is currently paused, and since I found a solution I wanted to share it).


问:
What is a Ph.D. good for in the software industry?
I'm a self-taught programmer and have just started a computer science degree to supplement my knowledge and fill in the gaps.

However, I'm already debating the direction of my education. I want a 4 year bachelor's degree for sure, but after that, I'm not sure: Is it worth it to get an M.Sc? What about a Ph.D.? What opportunities do these degrees open up?

Currently my goal is to be a software developer, but there are a number of fascinating fields in the software industry and I'm certainly interested in investigating many of them. It is in this respect that I think a higher degree may be worth it -- even if it wouldn't necessarily help a career of software development.

So will it be worth it? Will grad school open doors?

答:
From my personal experience, 3 years of hand-on experience in an IT industry with a graduation or post-graduation would definitely gain more weightage than a PHD.

From the job perspective of the IT industry, graduates from an arts and science background like BSC could definitely opt for a post-graduation degree like an MCA or MSC would act as a catalyst for entering into an IT industry.

In our company, while we used to recruit software developers the minimum requirement was an art and science degree with a proper programming and logical skill graded with practical programming tests but since competition has increased over time, the minimum qualification has been changed to an engineering or a post-graduation degree.


答:
Generally you can already do this with a switch/case and a switch/case provides more fine tuned control over what you are proposing.

It also doesn't read properly logically.  If A else if B then C.  Doesn't imply to someone that C will be executed if either A or B evaluate to true.

Title: What do you think of this new if-then syntax

Body:
I was just thinking of something that would be really cool to have in my if-elif-else controls.

```<code>
if condition:
    stuff()
elif condition:
    otherstuff()
then:
    stuff_that_applies_to_both()
else:
    stuff_that_doesnt_aply_to_either()
</code>```

So basically a then will be run when any of the conditions are run EXCEPT the else condition. Do you think this is useful? It's similar to the try-except-else of python.

I think some of you are nitpicking a very preliminary implementation. The then block would be just like the else block in a try-except block in python. The real reason I suggest this is for situations like this.

```<code>
m = {}
if condition == '1':
    m['condition'] = condition
elif condition2 == '3':
    m['condition2'] = condition2
elif condition3 == 'False':
    m['condition3'] = True
then:
    run_test_that_relies_on_one_of_the_conditions_being_true()

return m
</code>```

The then block is scoped to the first if just like the else is. So nesting works fine. And if you need to run a method before the if statements, that really has nothing to do with this use case.


问:
How independent is Clojure from Java?
I am quite new to the Clojure world. I appreciate the fact that one has easy access to all Java libraries via Clojure interop features, but I was wondering how much Clojure stands on its own legs.

Of course there are some platforms, like Android, where interoperability with Java will always be required, because the core libraries are written or exposed in Java. Moreover, since Clojure strings are Java strings, I expect string manipulation libraries to be a wrapper on the Java String methods.

But for other tasks I see no reason why native Clojure libraries couldn't be developed. Think of Http, date manipulation, XML parsing, templating, JSON serialization and deserialization, OAuth, math libraries and so on.

So my question is:

How far has Clojure come to become independent of the Java ecosystem? Does it have its own idiomatic libraries for most of these and other tasks?

答:
As Clojure continues to evolve it will certainly build more and more of its own libraries, allowing for easier ports to other VMs. As far as Clojure on the JVM is concerned I believe the long term goal will be to replace most libs with Clojure alternatives (thereby having that immutability by default, STM etc), bringing the Java interop layer down to the lowest level of primitives and base objects such as String.  This will especially true once the Java platform is modularised with jigsaw/OSGi in Java 8 (2013)

However, I believe that Clojure will still want to try and take advantage of invokedynamic (introduced as a bytecode instruction in Java 7) and will take a fairly pragmatic approach about which libraries to replace when (if Java has a perfectly good lib, then why change it early).

NOTE:  I'm not involved deeply in the Clojure community, so this is partly hearsay/guesswork.

Title: How independent is Clojure from Java?


答:
Process "debt" can't exist and certainly can't accrue.

You have a "gap" in your process where team B is doing "more" work because team A is doing "less" work.

This doesn't accrue.  It's just a shifting of the workload.

If something is accruing , then a year from now, team B would have a huge backlog of things to do.  Wait.  That's a backlog of technical work.  That's what technical debt is.

A "process debt" would be a backlog of process steps that must be executed. Checkin-Checkout?  Email updates that something's about to change? That's silly.  And not very Agile, either.

Title: Is 'process debt' a term people work with

Body:
As a result of a retrospective we were uncovering worse ways of developing
software. We had a idea we though was great and tried it. We stayed with it during the development of a major update which took 3 months. After a retrospective with the maintenance engineers it turn out our idea does not work for them (we had discussions with them before we tried the idea and the also thought it was a great idea). We came to the agreement we better get back to the old situation. The team for the update is dismantled and the maintenance engineers don't have time to do so (although their project manager has agreed to invest the time).

We're now in the situation the maintenance engineers pay the interest each time a minor release has to be made. This is very much like technical debt but has nothing to do with the product itself. Is this called process debt or is this put under the term technical debt? And what would be a good way of dealing with it? (Any other or concrete ideas to make it visible to product managers?)

PS The idea was migrating a 4 product VSS database to SVN. The database heavily leans on shared files and is a mess to untangle and pour in a usable SVN structure. It's very counter intuitive but is seems some things are better kept in VSS.


答:
Interesting, but seems to me (admittedly somewhat set in my ways) an invitation for readability, logic, and syntax problems.

Edit:
Your if-elif is very simple - what if there were 10 elifs?  20?  Would all conditions need to be true?  What are the chances of that?

Your if-elif is very simple - what if there were 10 elifs?  20?  Wouldn't that make this fairly unreadable?

Also, can easily be achieved by tried-and-true established methodology:

```<code>if (thisCondition or thatCondition)
{
  if (thisCondition)
     stuff();
  else
     otherstuff();

    stuff_that_applies_to_both();
}
else
{
    stuff_that_doesn't_aply_sic_to_either();
}
</code>```

What happens if "stuff_that_applies_to_both" needs to happen before the individual steps?  Your code doesn't handle this case:

```<code>if (thisCondition or thatCondition)
{
  stuff_that_applies_to_both();

  if (thisCondition)
     stuff();
  else
     otherstuff();
}
else
{
    stuff_that_doesn't_aply_sic_to_either();
}
</code>```

Finally, this syntax allows for greater flexibility with more conditions:
    if (thisCondition or thatCondition or anotherCondition)
    {
      stuff_that_applies_to_all();

```<code>  // Any combination of the three conditions using
  // whichever logical syntax you'd like here
  if (thisCondition and anotherCondition)
     stuff();
  else if (thisCondition or thatCondition)
     stuff_number_2();
  else
     otherstuff();
}
else
{
    stuff_that_doesn't_aply_sic_to_either();
}
</code>```

I have been using if/else, but could have as easily used a switch statement with a flag:

```<code>Boolean conditionApplies = true;

switch (someConditionToCheck)
{
    case thisCondition:
      stuff();
      break;

    case thatCondition:
        otherStuff();
        break;

    default:
        stuff_that_doesnt_aply_sic_to_either();
        conditionApplies = false;
        break;
}

if (conditionApplies)
    stuff_that_applies_to_both();
</code>```

Note that I didn't actually need the conditionApplies flag - I could have added the "stuff_that_applies_to_both()" function to both the non-default conditions - I just did this so it looks more like the syntax defined above, albeit the "then" rather than the "else".

Therefore, it seems to me to be a very specialized syntax, where a more general syntax fills the bill and more.

+1 for thinking of a possible feature (keep doing that!), but I wouldn't vote to implement it.

Body:
Interesting, but seems to me (admittedly somewhat set in my ways) an invitation for readability, logic, and syntax problems.

Edit:
Your if-elif is very simple - what if there were 10 elifs?  20?  Would all conditions need to be true?  What are the chances of that?

Your if-elif is very simple - what if there were 10 elifs?  20?  Wouldn't that make this fairly unreadable?

Also, can easily be achieved by tried-and-true established methodology:

if (thisCondition or thatCondition)
{
  if (thisCondition)
     stuff();
  else
     otherstuff();

    stuff_that_applies_to_both();
}
else
{
    stuff_that_doesn't_aply_sic_to_either();
}

What happens if "stuff_that_applies_to_both" needs to happen before the individual steps?  Your code doesn't handle this case:

if (thisCondition or thatCondition)
{
  stuff_that_applies_to_both();

  if (thisCondition)
     stuff();
  else
     otherstuff();
}
else
{
    stuff_that_doesn't_aply_sic_to_either();
}

Finally, this syntax allows for greater flexibility with more conditions:
    if (thisCondition or thatCondition or anotherCondition)
    {
      stuff_that_applies_to_all();

  // Any combination of the three conditions using
  // whichever logical syntax you'd like here
  if (thisCondition and anotherCondition)
     stuff();
  else if (thisCondition or thatCondition)
     stuff_number_2();
  else
     otherstuff();
}
else
{
    stuff_that_doesn't_aply_sic_to_either();
}

I have been using if/else, but could have as easily used a switch statement with a flag:

Boolean conditionApplies = true;

switch (someConditionToCheck)
{
    case thisCondition:
      stuff();
      break;

    case thatCondition:
        otherStuff();
        break;

    default:
        stuff_that_doesnt_aply_sic_to_either();
        conditionApplies = false;
        break;
}

if (conditionApplies)
    stuff_that_applies_to_both();

Note that I didn't actually need the conditionApplies flag - I could have added the "stuff_that_applies_to_both()" function to both the non-default conditions - I just did this so it looks more like the syntax defined above, albeit the "then" rather than the "else".

Therefore, it seems to me to be a very specialized syntax, where a more general syntax fills the bill and more.

+1 for thinking of a possible feature (keep doing that!), but I wouldn't vote to implement it.


答:
I have a M.Sc, it helped me nothing. 2 years of my life lost forever. At least in Romania, in software development, knowledge matters the most. A college degree helps a little and in some specific circumstances.

M.Sc and Ph.D are good only if you have plans in a career in education or research.

Title: What is a Ph.D. good for in the software industry?

Body:
I'm a self-taught programmer and have just started a computer science degree to supplement my knowledge and fill in the gaps.

However, I'm already debating the direction of my education. I want a 4 year bachelor's degree for sure, but after that, I'm not sure: Is it worth it to get an M.Sc? What about a Ph.D.? What opportunities do these degrees open up?

Currently my goal is to be a software developer, but there are a number of fascinating fields in the software industry and I'm certainly interested in investigating many of them. It is in this respect that I think a higher degree may be worth it -- even if it wouldn't necessarily help a career of software development.

So will it be worth it? Will grad school open doors?


问:
typedefs and #defines
We all have definitely used typedefs and #defines one time or the other. Today while working with them, I started pondering on a thing.

Consider the below 2 situations to use int data type with another name:

```<code>typedef int MYINTEGER
</code>```

and

```<code>#define MYINTEGER int
</code>```

Like above situation, we can, in many situations, very well accomplish a thing using #define, and also do the same using typedef, although the ways in which we do the same may be quite different. #define can also perform MACRO actions which a typedef cannot.

Although the basic reason for using them is the different, how different is their working? When should one be preferred over the other when both can be used? Also, is one guaranteed to be faster than the other in which situations? (e.g. #define is preprocessor directive, so everything is done way earlier than at compiling or runtime).

答: Use the tool with the least power that gets the job done, and the one with most warnings. #define is evaluated in the preprocessor, you are largely on your own there. typedef is evaluated by the compiler. Checks are given and typedef can only define types, as the name says. So in your example definitely go for typedef.</p>

Title: typedefs and #defines


答:
A typedef is generally preferred unless there's some odd reason that you specifically need a macro.

macros do textual substitution, which can do considerable violence to the semantics of the code.  For example, given:

```<code>#define MYINTEGER int
</code>```

you could legally write:

```<code>short MYINTEGER x = 42;
</code>```

because short MYINTEGER expands to short int.

On the other hand, with a typedef:

```<code>typedef int MYINTEGER:
</code>```

the name MYINTEGER is another name for the type int, not a textual substitution for the keyword "int".

Things get even worse with more complicated types.  For example, given this:

```<code>typedef char *char_ptr;
char_ptr a, b;
#define CHAR_PTR char*
CHAR_PTR c, d;
</code>```

a, b, and c are all pointers, but d is a char, because the last line expands to:

```<code>char* c, d;
</code>```

which is equivalent to

```<code>char *c;
char d;
</code>```

(Typedefs for pointer types are usually not a good idea, but this illustrates the point.)

Another odd case:

```<code>#define DWORD long
DWORD double x;     /* Huh? */
</code>```

Title: typedefs and #defines

Body:
We all have definitely used typedefs and #defines one time or the other. Today while working with them, I started pondering on a thing.

Consider the below 2 situations to use int data type with another name:

```<code>typedef int MYINTEGER
</code>```

and

```<code>#define MYINTEGER int
</code>```

Like above situation, we can, in many situations, very well accomplish a thing using #define, and also do the same using typedef, although the ways in which we do the same may be quite different. #define can also perform MACRO actions which a typedef cannot.

Although the basic reason for using them is the different, how different is their working? When should one be preferred over the other when both can be used? Also, is one guaranteed to be faster than the other in which situations? (e.g. #define is preprocessor directive, so everything is done way earlier than at compiling or runtime).

Body:
A typedef is generally preferred unless there's some odd reason that you specifically need a macro.

macros do textual substitution, which can do considerable violence to the semantics of the code.  For example, given:

#define MYINTEGER int

you could legally write:

short MYINTEGER x = 42;

because short MYINTEGER expands to short int.

On the other hand, with a typedef:

typedef int MYINTEGER:

the name MYINTEGER is another name for the type int, not a textual substitution for the keyword "int".

Things get even worse with more complicated types.  For example, given this:

typedef char *char_ptr;
char_ptr a, b;
#define CHAR_PTR char*
CHAR_PTR c, d;

a, b, and c are all pointers, but d is a char, because the last line expands to:

char* c, d;

which is equivalent to

char *c;
char d;

(Typedefs for pointer types are usually not a good idea, but this illustrates the point.)

Another odd case:

#define DWORD long
DWORD double x;     /* Huh? */


答: By far, the biggest problem with macros is that they are not scoped. That alone warrants the use of typedef. Also, it is more clear semantically. When someone who reads your code sees a define, he won't know what it is about until he reads it and comprehends the entire macro. A typedef tells the reader that a type name will be defined. (I should mention that I'm talking about C++. I'm not sure about typedef scoping for C, but I guess it's similar).</p>

Title: typedefs and #defines


答:
Keith Thompson's answer is very good and together with Tamás Szelei's additional points about scoping should provide all the background you need.

You should always consider macros the very last resort of the desperate.  There are certain things you can only do with macros.  Even then, you should be thinking long and hard if you really want to do it.  The amount of pain in debugging that can be caused by subtly broken macros is considerable, and will have you looking through preprocessed files.  It's worth doing that just once, to get a feeling for the scope of the problem in C++ - just the size of the preprocessed file might be an eye-opener.

Title: typedefs and #defines


答:
Source code is mainly written for fellow developers. Computers use a compiled version of it.

In this perspective typedef carries a meaning that #define doesn't.

Title: typedefs and #defines


问:
Is there a design pattern that would apply to discount models?
Are there any known design patterns for implementing discount models?

By discount models, I mean the following:

If a customer buys Product X, Product Y and Product Z he gets a discount of 10% or $100.

If a customer buys 100 units of Product X, he gets a discount of 15% or $500

If a customer has brought in the last year more than $100K, he gets a flat 20% discount

If a customer has purchased 2 units of Product X, he gets 1 unit of Product X (or Product Y) free.

...

Is there a generic pattern that can be applied to handle all of the above scenarios? I am thinking of a few models, but unable to come across a generic one.

答:
Strategy, Decorator, and State patterns stand out to me as potential starting points. State might be particularly useful for 2 or 3, since 2 is dependent on the state of the order and 3 is dependent on the state of the customer within a time period. Strategy and Decorator stand out for the others, since you can use strategy to implement multiple order-price calculation algorithms and decorator to add new discounts to the order.

However, remember that design patterns are just models. There might not be a single pattern that applies, but rather a systems of patterns. Also consider making modifications to the described models to make them better fit your solution. It's better to have a good design than to force a pattern where it doesn't necessarily help just for the sake of being able to say you have a pattern.


问:
What timestamp to use when pulling files from a VCS system?
Yesterday, a colleague asked me how to configure our VCS to timestamp the local copy of files pulled from the repository with the modification time in the repository.  I've always believed that they should be timestamped with the time they were pulled so that if you make a change, build, then back out by overwriting the changed file with the repository's copy, everything that depends on that file will build correctly.

I thought about it overnight, but couldn't come up with a good reason to have timestamped with the repository modification time.  What would be the advantages of doing it that way?

(Bonus question: repository modification time and local modification time are the only timestamping strategies that I'm aware of.  Are there others in use by VCS systems?)

答:
See the tools in the contexts for which they were built.  Version control systems are primarily made to track content of source files.  They usually only track very little file metadata (executable bit, usually), because you don't need that for managing source code.  The timestamp of the file on disk needs to be changed whenever the file is actually changed on your local disk so that your local build tools behave correctly.  If you say you need to timestamp to be able to tell which file is which, well, the version control system is there to tell which file is which by means of the all the versions it controls.

If what you actually need is  not a source code management tool but a deployment or backup tool, then you should use a tool made for that.  All the tools is that area, such as tar, rsync, rpm, dpkg, preserve file modification timestamps and other metadata, because that is necessary or desirable for their job.


问:
How should repetitive calendar tasks be stored in the database?
This is for a small personal project for micro-management. Basically, I store tasks in a SQLite3 database that looks like this:

```<code>    id INTEGER PRIMARY KEY AUTOINCREMENT
    label TEXT
    deadline INTEGER
</code>```

So each task has a due date (deadline) that is stored as a Unix Time Stamp. So far so good, I can do entries such as "tomorrow: visit grandma" and a new row gets created with "visit grandma" as the label and tomorrow transformed as Unix time for deadline.

Now I would like to enter new type of tasks: routines - tasks repeated on a time pattern, like "everyday: clean kitchen". How can such tasks be stored or modeled?

For the moment, I am thinking that, in the case of a task that needs to be done everyday, to generate new rows in my table that would have the same label, and the deadline field incremented by one day. In this case, I need to fix a limit in the future. For example, if I create a routine for every day, it creates a new row for everyday of the remaining year.

Is there a simpler way to do this? Am I missing some obvious database design principles?

答:
In addition to the comment from S.Lott, Martin Fowler - Recurring Events for Calendars PDF may help you (I found it a bit difficult).

Also note that several UI tools offer the function you are describing out of the box (with simple task model). I would consider this problem as a hard to solve database design problem without such tools.


答:
The problem here isn't that your software is more suited to version controlled in VSS as opposed to SVN and the resulting "process debt" as a result.

The problem is that your software has a design flaw that encourages poor practices and creates significantly more work for the team in the long run.  This is essentially technical debt not as a result of poor implementation necessarily but as a result of poor design.

The design flaw is that feature work cannot be adequately split up amongst developers without running into significant merging issues with a handful of files that change frequently by a number of different people.  Certain frameworks of course lend themselves to these kinds of problems, Struts (), ASP.NET (web.config) etc... however merging on a large scale has been one of SVN's weaker points.  Perhaps Git or Mercurial would be better suited to your project and help mitigate this problem.


答:
If the issue is that you need to apply multiple discounts, under given circumstances, you might want to consider the Chain of Responsibility pattern.

In a nutshell, you pass the information you want to process into the first processor, and it decides from there whether to pass it on to further processors before returning the result.

This way you can change the structure and sequence of the processors without ever changing the calling code.

Title: Is there a design pattern that would apply to discount models?

Body:
Are there any known design patterns for implementing discount models?

By discount models, I mean the following:

If a customer buys Product X, Product Y and Product Z he gets a discount of 10% or $100.

If a customer buys 100 units of Product X, he gets a discount of 15% or $500

If a customer has brought in the last year more than $100K, he gets a flat 20% discount

If a customer has purchased 2 units of Product X, he gets 1 unit of Product X (or Product Y) free.

...

Is there a generic pattern that can be applied to handle all of the above scenarios? I am thinking of a few models, but unable to come across a generic one.

ContentLicense: CC BY-SA 4.0


答:
Well, I would design a discount model as a pair "Precondition" and "Discount", where "Precondition" is a class with methods

```<code>  bool IsFulfilled(Customer c);
</code>```

or / and

```<code>  bool IsFulfilled(Customer c, Order o);
</code>```

and Discount has a method void ApplyTo(Customer c). This gives you the ability to combine any type of precondition with any type of discount (I think this is a form of "bridge pattern").

If you have a fixed number of preconditions, then you can solve the problem by building specific subtypes (strategy pattern). However, when your preconditions are allowed to be very complex, with logical statements like AND, OR and NOT, you may better implement some kind of rule interpreter for the conditions. The rules can be a plain text string written in a simple "domain specific language".

The same goes for the "Discount" class, you can either have some subtypes for different types of discounts, or a general approach where the discount rules are given in text form, evalued by some interpreter.

Body:
Well, I would design a discount model as a pair "Precondition" and "Discount", where "Precondition" is a class with methods

  bool IsFulfilled(Customer c);

or / and

  bool IsFulfilled(Customer c, Order o);

and Discount has a method void ApplyTo(Customer c). This gives you the ability to combine any type of precondition with any type of discount (I think this is a form of "bridge pattern").

If you have a fixed number of preconditions, then you can solve the problem by building specific subtypes (strategy pattern). However, when your preconditions are allowed to be very complex, with logical statements like AND, OR and NOT, you may better implement some kind of rule interpreter for the conditions. The rules can be a plain text string written in a simple "domain specific language".

The same goes for the "Discount" class, you can either have some subtypes for different types of discounts, or a general approach where the discount rules are given in text form, evalued by some interpreter.


答:
This is a actually a really tough question as there are going to be a lot of factors at play and they may or may not apply to you personally depending upon a number of variables. In general, when approaching formal education you need to look at your own skills and what your long term career goals are. While some will argue that there is no correlation between programming skills and education, most are hard pressed to argue that education (e.g formal education, workshops, one off courses, reading a book, etc) is going to inhibit your programming skills and in many cases it will actually improve them. Thus, education tends to always work in your favor over the long term.

From a career development standpoint, depending upon who you work for (or who you want to work for) you education will likely influence the path that your career can take. While you can be quite successful with no degree what so ever, you will find that you obtaining your dream job may be highly dependent upon your educational background. This is due to the fact that most medium to large companies tend to require that their employees have some degree of formal education that can be hiring requirement. Thus, for every person that you hear about that doesn't take education into account in hiring, you will encounter Human Resources (HR) departments who will state that "Bachelors degree in Computer Science required" in their job listing and will not even bother to look at a résumé that doesn't include one.

In terms of the educational hierarchy, you can generally expect to see things working out as follows:

No Education - If you have track record, this may not hurt you with a fair number of companies and you may be able to go quite far if you develop some fairly specialized knowledge that you can use for consulting. That said though, for every success story that you hear, there are also a lot of developers that you don't hear about that hold down the same job and really don't advance very far career-wise. Networking and social skills can help you in the long run, but you will find that some doors are closed due to the lack of the formalized education.

Associates Degree - This is a hard degree to pin down as it can actually open doors and companies that require a Bachelors degree may wave the requirement if you can really prove their worth to them, but most likely it will not get you fair in said companies. This could be a good stepping stone career-wise in that it may help you get a job with educational benefits, but eventually you may find that people start pushing you towards a Bachelors degree.

Bachelors Degree - This tends to be the general baseline degree that will open up many doors and generally will not cause any to be closed unless they are for higher level positions which may be dependent upon the industry. In terms of return on investment, you will likely find that the Bachelors degree tends to have the highest return in return for the amount of work that you put into it (financial cost can be too variable to be a factor).

Masters Degree - In general, you should not go for a Masters degree unless someone else is paying for it, or you have the opportunity to get it at the same time as your Bachelors degree without much additional work (i.e. a five year dual degree program). In the long run, in the cooperate sector, the Masters degree will open up some doors that may not have been open with just the Bachelors degree, but you may not actually find those doors unless you are actively looking for them (i.e. research and development style positions). In larger companies (i.e. Fortune 500), most of the middle and upper management will have a Masters degree and it generally seen as a requirement to move up in the company. That said though, most companies that have a requirement (formal or otherwise) of a Masters degree for upper management will generally have educational benefits that you can use to get the degree while you are working.

From an academia standpoint, the Masters degree is typically the minimum level of education required to teach at the collegiate level, but you are generally limited to lower paying lecture pitons that you generally cannot rely upon for steady employment. This might be a great goal for the long term as you approach retirement age, but when you are younger it might cause some stress.

Doctoral Degree - If you want to find high level research positions or go into academia, a doctoral degree is a requirement. For everyone else, a doctoral degree is simply a nice to have and in some cases a doctoral degree will actually close doors (i.e. entry level developer positions) for a variety of reasons. That said though, if you really enjoy computer science and really want to learn all there is to know about something, go for the doctoral degree and don't look back. Pretty much every one that I've ever talked to has said something along the lines of the following: "Don't get a PhD for the money, do it because you really love research and knowing all there is to know about something."

To round everything else, here are a couple other forms of formalized education that you may come across:

Vendor Certifications - Vendor certifications such as the MCAD or OCPJP have very mixed value as they only tend to be good for a couple of years before the expire and most interviewers don't care about them very much. That said though, if you are looking to move to a different area of development (i.e. Windows to Java development) you may find that they can land you a job if someone is skeptical of your abilities to do the job you are applying for. Likewise, when you are starting out they may help you get that first job if you don't have much formal education, but they tend to have a limited return on investment.

Post Bachelor Certificates - These are offered by colleges and universities as a way of formalizing a course of work that may not be worthy of a full Bachelors or Masters degree, but requires some sort of formal recognition. In most cases these are only worthwhile if you are looking for some formal background in an area of weakness on the job (i.e. mathematics) or if you are working in a field where you need some formal education in field you have no background in (i.e. if you are working in bioinformatics you may want take some biology courses). From a career standpoint these may be worth going for if someone else is paying for them, but generally you aren't going to see much value add beyond the knowledge you obtain. The exception to that final point is if you are trying to change careers all together in which case they tend to represent a lower bar than a Masters degree in the field which may require a fair degree of "make-up work" that a Bachelors degree holder in the same field would not have to take.

Master of Business Administration (MBA) - I'm including this because it is a common degree to see being held by managers and it isn't uncommon to see developers that are looking to go into management pursuing one. In the long run, it is a degree that can help you but you are likely going to be better off waiting until you have established you career and have a fair idea of where you want to go before going for it.

Certificate of Advanced Study - These are offered by colleges and universities as a degree of education that is past a Masters degree but is less than a Doctoral degree. Again, the value of these can be hard to say as they are generally something that is hard to quantify. Most of the people who I've known to take these had very specific reasons for doing, generally for career development, but they were also later in their career and either trying to bump their salary a bit, or get to work on something specific that they couldn't otherwise.

So go come back around to the original point, a Ph.D. can be of questionable value if you are just looking for a job as a developer, but may take you quite far if you want to be working with new technologies that aren't out of the lab yet. Generally more education will not hurt you, but you have to be comfortable with the time investments that are involved with the studies.


问:
What is the difference between routed events and attached events?
I am just going through the WPF concepts I came across these routed events, dependency properties and attached events.

What are the concepts behind them and why are they called instead of .NET ordinary methods?

答:
Routed events

According to MSDN,

A routed event is a type of event that can invoke handlers on multiple listeners in an element tree, rather than just on the object that raised the event.

The definition is followed by an example of a WPF node with three buttons. The single routed event is listening for three buttons. If you try to write the same code using ordinary events, you'll have to use three separated events, one event by button.

This means that, instead of defining multiple events on every control in a same child, you have to define a routed event at the parent level, which will be raised by every concerned child.

Further, you may want to read Routed Events on WPFTutorial.net which uses a more precise terminology than my answer, and which also explains why routed events usually appear as pair.

Dependency properties

According to MSDN,

The purpose of dependency properties is to provide a way to compute the value of a property based on the value of other inputs.

Think it as a way to simplify your code (and especially the ability to use the code), since you can use a dependency property as an ordinary one.

Further, you may want to read a more complete article on Switch On The Code article, which also explains why it makes sense that a DependencyProperty is static, shows how to add change callbacks or use validation, etc.

Attached events

According to MSDN,

The concept of an attached event enables you to add a handler for a particular event to an arbitrary element rather than to an element that actually defines or inherits the event.

This is particularly useful when the object which raises the event is independent from the actual WPF tree. One of the examples given by the same documentation is the mouse events, when those events are not related to the WPF element which, like in case of MouseDown, both raises and listens to the event.

Further, you may want to read Attached Events By Example, which explains that "the class defining the event is often neither the user of the event (whoever consumes it by adding a handler on it) nor the source of the event (whatever code raises it).", and gives much more details about attached events and their difference with routed events.


答:
You could make a Separate table for reoccurring. But honestly I would juts put it into the same table with a Type Field.

Something like this:

```<code>ID - Int Pk

TaskDescription - TEXT

Type - Text - (Re-Occurring, or Single Occurrence)

Due- TimeStamp - for Single Occurrence is the Date time

LastTimeCompleted - Time Stamp

ReoccurringUnit - Text - "Days", Weeks, Month, Ext

ReoccurringEveryX - Int - Reoccurring interval
</code>```

Title: How should repetitive calendar tasks be stored in the database?

Body:
This is for a small personal project for micro-management. Basically, I store tasks in a SQLite3 database that looks like this:

```<code>    id INTEGER PRIMARY KEY AUTOINCREMENT
    label TEXT
    deadline INTEGER
</code>```

So each task has a due date (deadline) that is stored as a Unix Time Stamp. So far so good, I can do entries such as "tomorrow: visit grandma" and a new row gets created with "visit grandma" as the label and tomorrow transformed as Unix time for deadline.

Now I would like to enter new type of tasks: routines - tasks repeated on a time pattern, like "everyday: clean kitchen". How can such tasks be stored or modeled?

For the moment, I am thinking that, in the case of a task that needs to be done everyday, to generate new rows in my table that would have the same label, and the deadline field incremented by one day. In this case, I need to fix a limit in the future. For example, if I create a routine for every day, it creates a new row for everyday of the remaining year.

Is there a simpler way to do this? Am I missing some obvious database design principles?

Body:
You could make a Separate table for reoccurring. But honestly I would juts put it into the same table with a Type Field.

Something like this:

ID - Int Pk

TaskDescription - TEXT

Type - Text - (Re-Occurring, or Single Occurrence)

Due- TimeStamp - for Single Occurrence is the Date time

LastTimeCompleted - Time Stamp

ReoccurringUnit - Text - "Days", Weeks, Month, Ext

ReoccurringEveryX - Int - Reoccurring interval