答: as a rule of thumb one thing i make sure to ask is how the turnover is on the tech team. If you ask around on your interview with the team members and the longest anyone has been their is a year or two then watch out. personally, i pass on these jobs and only look to be hired by teams that have people with Grey hair... if everyone looks like they are under 30 then that's another red flag.</p>

Title: What do you do if you've had a series of bad employers?

Body:
So I've had a series of really bad experiences and am wondering what I'm doing wrong.

I started out as a part time programmer at a major university.  I developed a problem with my wrist and asked (nicely) for some help with my ergonomic accomodations.

My boss started screaming at me, then later claimed I screamed at her.  When questioned about it, she just started sobbing.  Luckily, there were others around who heard the screaming and knew I was telling the truth.  She was eventually let go.

My contract went up and I switched jobs, this time to a startup.  Well, we went several months without my getting a development machine.  When the economy tanked, they started asking for insane amounts of overtime.  I complied because I was afraid of having to look for work.  The final straw was they contacted me right before my father's funeral to fix a problem.

I was laid off, didn't receive my final check on time and the company screwed my COBRA up to the point where I couldn't get prescriptions for months.  They recently were fined by the State of X for what they did.  Now, even though I worked my heart out for them and they were willing before being fined, they are refusing to provide a reference.

I took a new job quickly, mainly because I really needed my health insurance set up.  They wanted me to do several months of work in a couple of weeks.  They had no project plan.  Their customers were seriously not doing well, as whole sections of the application would stop working if someone ran a spell check.  Even though they had completely unreasaonble expectations about my work, they were happy to say it would take several months to repair the spell check bug.  There was virtually no training.

They had me interviewing candidates and I selected one.  Apparently, that person was my replacement because I was let go after a few months.

Recently, my former boss called my current employer and made up allegations that I am discouraging people from applying to open positions at his firm, which is insane because I didn't even know they were hiring.

I feel like I have a T-shirt that says, "If you're insane or would like someone to kick around and treat badly, hire me!".

Then again, when I look at some programmers' resumes, I do see horror stories, too.

So are there things I can do differently to avoid these problems?  Is it part of our profession that people do not have standards?  Perhaps it is a personality issue, that resides purely with me?

Has anyone else had a series of bad experiences and turned things around?


问:
How to make Unit Tests to make sure stored procedure is deleting row from the database?
I'm new to unit testing and I need some help with the following.

I have created a small project to help me learn how to make Unit Tests. The functionality for one of the forms in my application deletes a user from the User table (and other rows in mapping tables).

Currently, the unit test I have created to test this sets up the required objects and then calls the business rules method (passing in the user id) which calls the data access method to execute the stored procedure that deletes the rows in the tables.

Is this the correct method to test whether something is being deleted successfully? Should the unit test / setup method first insert some test data which the unit test then deletes?

答:
IMHO if you are just starting to learn unit testing, it is better to leave databases out of the picture for now. Data in a DB is harder to test - in fact when you are testing code which makes direct calls to a DB, it isn't a unit test anymore but integration test.

You can unit test code manipulating a DB, but it requires more effort and tools, including extra frameworks - like DBUnit in the Java world -, interfaces, mocks etc. which are more advanced topics.

ContentLicense: CC BY-SA 3.0


答:
you should mock the (abstracted) database while testing the form

essentially providing a dummy implementation that does the minimum necessary to complete the tests

this way when you call submit on the form you can then see if deleteUser in the data access gets called

Title: How to make Unit Tests to make sure stored procedure is deleting row from the database?

Body:
I'm new to unit testing and I need some help with the following.

I have created a small project to help me learn how to make Unit Tests. The functionality for one of the forms in my application deletes a user from the User table (and other rows in mapping tables).

Currently, the unit test I have created to test this sets up the required objects and then calls the business rules method (passing in the user id) which calls the data access method to execute the stored procedure that deletes the rows in the tables.

Is this the correct method to test whether something is being deleted successfully? Should the unit test / setup method first insert some test data which the unit test then deletes?


答: It will be much easier to write unit tests for SQL stored procedures in SQL.  Take a look at tSQLt.  Avoid retesting the stored procedures in your C# unit tests; take ratchet freak's advice and mock the database to test the C# code.</p>


问:
Initialize array in amortized constant time -- what is this trick called?
There is this data structure that trades performance of array access against the need to iterate over it when clearing it. You keep a generation counter with each entry, and also a global generation counter. The "clear" operation increases the generation counter. On each access, you compare local vs. global generation counters; if they differ, the value is treated as "clean".

This has come up in this answer on Stack Overflow recently, but I don't remember if this trick has an official name. Does it?

One use case is Dijkstra's algorithm if only a tiny subset of the nodes has to be relaxed, and if this has to be done repeatedly.

答:
I would call it "lazy array cell reinitialization", but it doesn't seem to have any established name (that is, name being in wide use).

The algorithm is clever, but very specialized and applicable in a very narrow area.


问:
Should we use an outside CMS?
I work at a web design/development shop.  Everything we do is centered around the Joomla! CMS.  I'm a bit worried-if anything goes wrong with Joomla (major security flaw revealed, Joomla folds and ceases development) we're sunk.

I'm meeting with the CEO to plan the next few steps for our company.  Should I recommend that we create our own in-house CMS or am I just being paranoid about a single point of failure?

答:
I disagree with the other answers in this thread and think you should create your own CMS for the following reason:

It will be easier to create completely custom websites and decouple the frontend and backend

Most CMSs I've used have the frontend (the public portion of the website) tightly coupled to the backend (the admin portion of the website). If you roll your own CMS and create it in such a fashion that it is simply a CRUD application, then you can build a completely custom frontend that only needs to talk to the DB. For example, you could have your backend written in PHP, but the frontend could be written in Rails and as long as they talked to the same DB, it will be a seamless experience for the end-user. You won't find yourself tweaking the Joomla! view code to reorder the display of various elements on a frontend page. Instead, you'll be tweaking code that you wrote and that is completely decoupled from the backend.

Writing your own CMS, though, does induce alot of overhead in terms of frontend and backend routing, and you'll find yourself solving problems that have already been solved (such as breadcrumbs). But if you go this decoupled frontend/backend approach, it may be easier to develop completely custom websites.

It will not be worth it to develop your own CMS if the frontend and backend code will be tightly coupled, IMHO.

Title: Should we use an outside CMS?


问:
Working with Git on multiple machines
This may sound a bit strange, but I'm wondering about a good way to work in Git from multiple machines networked together in some way. It looks to me like I have two options, and I can see benefits on both sides:

Use git itself for sharing, each machine has its own repo and you have to fetch between them.

You can work on either machine even if the other is offline. This by itself is pretty big I think.

Use one repo that is shared over the network between machines.

No need to do git pulls every time you switch machines, since your code is always up to date.

Never worry that you forgot to push code from your other non-hosting machine, which is now out of reach, since you were working off a fileshare on this machine.

My intuition says that everyone generally goes with the first option. But the downside I see is that you might not always be able to access code from your other machines, and I certainly don't want to push all my WIP branches to github at the end of every day. I also don't want to have to leave my computers on all the time so I can fetch from them directly. Lastly a minor point is that all the git commands to keep multiple branches up to date can get tedious.

Is there a third handle on this situation? Maybe some third party tools are available that help make this process easier? If you deal with this situation regularly, what do you suggest?

答:
If not all the machines are up all the time, there's no silver bullet: before shutting down the machine, you have to push the changes somewhere else. I push to a private server, but it could just as well be dropbox or a usb key you carry everywhere.

Yes, pushing multiple branches to a central place can get tedious, but that shouldn't be too difficult to script. I use a push.sh script for that, which I run every time I'm done working on a machine.

Title: Working with Git on multiple machines


问:
What should be in a coding standard?
What should be in a good (read:useful) coding standard?

Things the code should have.

Things the code shouldn't have.

Should the coding standard include definitions of things the language, compiler, or code formatter enforces?

What about metrics like cyclomatic complexity, lines per file, etc?

答:
Naming Conventions

EDIT: By this I mean naming Guidelines, not naming Rules.

For example, a Guideline would be All boolean values should begin with Is/Can/Has/etc when possible. A rule would be All boolean values must start with Is

ContentLicense: CC BY-SA 2.5

Title: What should be in a coding standard?


问:
Advantages and disadvantages to using XAML/C# or HTML5/JavaScipt for Metro apps?
I was just wondering if there are any major advantages or disadvantages to using either XAML/C# or HTML5/JavaScript for Metro Apps.</p>

答:
As a little background, I built the American Airlines Windows 8 app in HTML5. I have to say it was fantastic.

First, drop all your ideas of HTML5 as it relates to mobile apps. In Windows 8,  JavaScript is a first class native language. You have access to all the hardware features that a XAML app would. There are also fantastic templates built into Visual Studio 2012 for WinJs applications.

WinJs is not just some half thought webview implementation. Microsoft is finally showing JS the respect it deserves.

I would suggest getting up to speed with the latest and greatest in IE10. Honestly that is the core framework for all of the WinJs stuff. It is powerful and fast!

Also, here's a great place to get started with WinJs:
http://msdn.microsoft.com/en-us/library/windows/apps/br211385.aspx

The future looks bright for JS as a native language for Windows.

ContentLicense: CC BY-SA 4.0


问:
What Java data structure/design pattern best models this object, considering it would perform these methods?

Methods:

```<code>1.  getDistance(CityA,CityB) // Returns distance between two cities
2.  getCitiesInRadius(CityA,integer) // Returns cities within a given distance of another city
3.  getCitiesBeyondRadius(CityA,integer) //Returns cities beyond a given distance of another city
4.  getRemoteDestinations(integer) // Returns all city pairs greater than x distance of each other
5.  getLocalDestinations(integer) //Returns all city pairs within x distance of each other
</code>```

答:
If there's a distance between every city, and every city is known in advance, I'd use a 2 dimensional array.  For simplicity and speed, I'd use the whole thing, even though you're storing all the distances twice.  Then you'll want a 1 dimensional array (ArrayList might work better) to link the indexes in your distance table to actual City objects (which in the simplest case would just be their names as Strings and their table index number).  Then add cities to a Map keyed on names to get the their indexes.  If you know the number of cities in advance, and even if you don't, a HashMap is probably what you want.  Now, given a name, you can find a row/column in the table, scan it for numbers you like, turn desired column/row index into a City object, and return whatever you want from that (name, for instance).

If the vast majority of city pairs do not have distances, skip the 2D array, and create a Connection class that references two cities and contains a distance.  Then the City class would contain a list of Connection objects, and you have a graph (as in graph theory).  There's lots of ways to work with them.


问:
How do you explain the importance of using a [distributed] version control system to someone who's not in the CS field?
A good example of someone who fits that description might be a project manager.

I was asked by my boss the other day, "what this Github thing is and why it's important?"  He has some proprietary projects so he would need private hosting and I found myself struggling to explain beyond the usual: VCSs make collaboration trivial, provide a history and "backup" of all your data, and allow you to record atomic changes in a code base.  In my mind I was thinking, "it's almost as if you have to use a DRVS to really understand how beneficial it is".

I ended up pointing him to BitBucket because they give you unlimited private repositories (I even had to explain what a repository was).

Does anyone have ay really good concrete examples of how a VCS has saved their ass or made life easier, etc -- basically, how would you sell a DVSC to someone who's not unfamiliar with programming, but not a programmer by profession?

答:
If you don't use version control, how do you know how to rebuild your
production environment?

1 Different people (testers, developers) will look for the same information in      different places

leading to DUPLICATE DATA that gets out of sync.

Version control is the easiest way to eliminate duplicate data.

2 If you do use version control, it is easy to ensure the production environment matches what is in the version control.

This makes it easy to detect whether a problem was due to a bad build (prod
does not match version control), or a design or coding bug (prod does match version control).

Version control makes it easy to assign a release number to each
test environment and you would naturally expect production to have
a lower release number than test or development, and test to have
a lower release number than development.  If this were not the
case, some part of the code has not been properly tested..


答:
The aforementioned approach requires that each cell be able to hold a number large enough to hold the number of times the array may need to be reinitialized, which is a substantial space penalty.  If a slot is capable of holding at least one value which will never be legitimately written, one may avoid having any other (non-constant) space penalty at the expense of adding an O(Wlg(N)) time penalty, where W is the number of distinct array slots written between clearing operations and N is the size of the array.  For example, suppose one will be storing integers from -2,147,483,647 to 2,147,483,647 (but never -2,147,483,648) and one wants blank array items to read as zero.  Start by filling the array with -2,147,483,648 (call that value B).  When reading an array slot for the application, report a value of B as zero.  Before writing array slot I, check whether it held B and if so and I is greater than one, store a zero to slot I/4 after performing a similar check for that location (and, if it held B, I/16, etc).

To clear the array, start with I equal to 0 or 1, depending upon the array base (the algorithm as described will work for either).  Then repeat the following procedure: If item I is B, increment I and, if doing so yields a multiple of four, divide by four (terminate if the divide yields a value of 1); if item I is not B, store B there and multiply I by four (if I starts at zero, multiplying by four will leave it zero, but since item 0 will be blank, I will get incremented).

Note that one could replace the constant "four" above with other numbers, with larger values generally requiring less work tagging, but smaller values generally requiring less work clearing; since array slots that are tagged have to be cleared, a value of three or four is almost certainly optimal; since the value four is certainly close to optimal, is better than two or eight, and is more convenient than any other number, it would seem the most reasonable choice.

Title: Initialize array in amortized constant time -- what is this trick called?

Body:
There is this data structure that trades performance of array access against the need to iterate over it when clearing it. You keep a generation counter with each entry, and also a global generation counter. The "clear" operation increases the generation counter. On each access, you compare local vs. global generation counters; if they differ, the value is treated as "clean".

This has come up in this answer on Stack Overflow recently, but I don't remember if this trick has an official name. Does it?

One use case is Dijkstra's algorithm if only a tiny subset of the nodes has to be relaxed, and if this has to be done repeatedly.


问:
What do you do if you've had a series of bad employers?
So I've had a series of really bad experiences and am wondering what I'm doing wrong.

I started out as a part time programmer at a major university.  I developed a problem with my wrist and asked (nicely) for some help with my ergonomic accomodations.

My boss started screaming at me, then later claimed I screamed at her.  When questioned about it, she just started sobbing.  Luckily, there were others around who heard the screaming and knew I was telling the truth.  She was eventually let go.

My contract went up and I switched jobs, this time to a startup.  Well, we went several months without my getting a development machine.  When the economy tanked, they started asking for insane amounts of overtime.  I complied because I was afraid of having to look for work.  The final straw was they contacted me right before my father's funeral to fix a problem.

I was laid off, didn't receive my final check on time and the company screwed my COBRA up to the point where I couldn't get prescriptions for months.  They recently were fined by the State of X for what they did.  Now, even though I worked my heart out for them and they were willing before being fined, they are refusing to provide a reference.

I took a new job quickly, mainly because I really needed my health insurance set up.  They wanted me to do several months of work in a couple of weeks.  They had no project plan.  Their customers were seriously not doing well, as whole sections of the application would stop working if someone ran a spell check.  Even though they had completely unreasaonble expectations about my work, they were happy to say it would take several months to repair the spell check bug.  There was virtually no training.

They had me interviewing candidates and I selected one.  Apparently, that person was my replacement because I was let go after a few months.

Recently, my former boss called my current employer and made up allegations that I am discouraging people from applying to open positions at his firm, which is insane because I didn't even know they were hiring.

I feel like I have a T-shirt that says, "If you're insane or would like someone to kick around and treat badly, hire me!".

Then again, when I look at some programmers' resumes, I do see horror stories, too.

So are there things I can do differently to avoid these problems?  Is it part of our profession that people do not have standards?  Perhaps it is a personality issue, that resides purely with me?

Has anyone else had a series of bad experiences and turned things around?

答:
I don't believe in series. Maybe you should start to ask your former coleagues how they perceived you, what you could improve. Call your old bosses also, this might help.

Why do that? Because you may find out that the problem was you!

If it's the case, you can improve things, but only if you know there is a problem.

However, if the problem is not you, you will stop asking yourself (and us).

Now there is another solution I like:

You are only 28 year old, you are at the beginning of your life, you may have done some mistake in the past, but who cares? You have the life ahead of you. Don't fill your mind with such unhelpful thoughts. You imagination is probably creating them. It's normal, all you have to do is ignoring them.


答:
Start with the basics:

Firstly a VCS protects developers from themselves and from each other - if it served no other purpose than to allow two or more developers to work on the same codebase relatively safely it would be of huge value (and I have been in a team where the previous days work has been overwritten by a bit of careless copying).

Secondly it provides an audit trail - a history - you can go back and see who changed what and when and you can go back and retrieve code that you deleted because it was no longer needed or appropriate when it turns out that it will be needed after all.

Thirdly it gives you a reference point - the definitive source is the committed code (in the real world its a bit more complicated, especially with DVCS, but for the sake of this discussion its close enough). If you have the repository properly backed up you should then have company's asset protected.

Those three things should be "it" for selling VCS - if a manager can't see sufficient value in the above its time to find another manager.

Once you've sold VCS (which are, after all, only of use to development teams where the number of devs is greater than zero) then the question of why DVCS over, say, SVN or TFS and the further question of whether to work in house or to use a hosted service such as Kiln or Bitbucket or Github (which does private if you pay) is rather deeper and more context dependent.

Title: How do you explain the importance of using a [distributed] version control system to someone who's not in the CS field?

Body:
A good example of someone who fits that description might be a project manager.

I was asked by my boss the other day, "what this Github thing is and why it's important?"  He has some proprietary projects so he would need private hosting and I found myself struggling to explain beyond the usual: VCSs make collaboration trivial, provide a history and "backup" of all your data, and allow you to record atomic changes in a code base.  In my mind I was thinking, "it's almost as if you have to use a DRVS to really understand how beneficial it is".

I ended up pointing him to BitBucket because they give you unlimited private repositories (I even had to explain what a repository was).

Does anyone have ay really good concrete examples of how a VCS has saved their ass or made life easier, etc -- basically, how would you sell a DVSC to someone who's not unfamiliar with programming, but not a programmer by profession?


问:
Storing IEnumerable as instance variable - is it a code smell to expect it to change?
I have something that works like a fixed size list - it's actually called FixedSizeStack<T> in my program. I will use it to represent the X last occured events. This event list will then be examined by different observers, and if they detect patterns they will trigger some action.

Naturally, I see no reason for them to know of FixedSizeStack<T> - to me it makes sense to present it to the actions as IEnumerable. I am considering giving them this event list in their constructors, then calling something like PreviewEvent(Event e); and EventOccured(); and they will iterate over this IEnumerable.

I feel a little queasy enumerating this IEnumerable multiple times, and making it part of the contract that the enumeration changes - do you think this is a reasonable method?

答: It would be more semantically correct to include the IEnumerable as a parameter passed to the event handler.</p>


答:
I don't think it's a code smell at all.  The IEnumerable (and IEnumerable<T>) interfaces are simply described as:

Exposes the enumerator, which supports a simple iteration over a collection of a specified type. - MSDN

It's a collection, and it exposes an enumerator.  There's nothing in the contract that would imply that that each time you access the enumerator, that it would return the same sequence of elements.  Probably a little unconventional, but totally correct.

It is up to the consumer to make assumptions or have requirements about a reference to a collection being passed in.  If the consumer really doesn't want the list to change unexpectedly, they should immediately call .ToList() or .ToArray().

Title: Storing IEnumerable as instance variable - is it a code smell to expect it to change?

Body:
I have something that works like a fixed size list - it's actually called FixedSizeStack<T> in my program. I will use it to represent the X last occured events. This event list will then be examined by different observers, and if they detect patterns they will trigger some action.

Naturally, I see no reason for them to know of FixedSizeStack<T> - to me it makes sense to present it to the actions as IEnumerable. I am considering giving them this event list in their constructors, then calling something like PreviewEvent(Event e); and EventOccured(); and they will iterate over this IEnumerable.

I feel a little queasy enumerating this IEnumerable multiple times, and making it part of the contract that the enumeration changes - do you think this is a reasonable method?


答:
"Have you ever found the 'undo' button useful?  Oh, so you agree we should use a version control then?"

When I started using version control the main feature I was interested in was the ability to 'undo' my mistakes and go back to a previous version.  Everyone can appreciate an undo button.  Granted version control can do a lot more.


答:
I think you need need to start doing more research on the company before taking a job and ask more pointed questions about the company in the interview. Since Health insurance is important to you, I would stay away from start-ups altogether as they can crash very suddenly leaving you in a similar situation (they usually aren't great at bureaucratic stuff like COBRA either).  Don't take the first job offered because you are panicked about being unemployed. How did your old boss even know where you are employed now to call them up? You are under no obligation to tell them.

Decide what working conditions you need before starting to interview. Then ask questions to ensure you get those conditions. Don't accept a job that doesn't meet your minimum. I once had a horrible job where my shortest working day was 11 hours and every week I worked over 18 hours 1-2 days a week. You can bet I used that experience to ask about their normal overtime policies and to make it clear that while I would work overtime in a crunch, I was not interested in a job where overtime was a way of life. Screen out the companies that don't do things the way you need them to. You'll be happier and so will they.


答:
I work mostly with engineers (not developers per se, but they do write code)

The main point, when I explain to them about version control, is the possibility of undoing and managing your code/documentation/whatever and simplifying collaboration with other developers/writers/etc...

That's a good selling point - and was the main reason for me to use a VCS for all my work, also the other advantages: having a history, a repo that can be easily backed up...

Most of them like the idea and find it quite useful, adopting it for their projects (specially if they involves collaboration with other engineers).


问:
What came first, the compiler, or the source?
I'm curious about the birth of the compiler.  How did programming begin?  Did people first build hardware that recognized a certain set of commands, or did people define a language and then build hardware around it?  And on a related note, what was the first programming language?</p>

答:
Interpreters existed before compilers so source code existed before compilers.

There are some very interesting papers on the history of computing here.  The source code for the FORTRAN II compiler is supposed to be available, but those links are broken.

This paper, from 1954, describes the Whirlwhind interpreter.


答:
It's not that you are being too paranoid (the questions 'what happens if my CMS ceases development' and 'what happens if my CMS has a security bug' are good ones) - it's that you are being incorrect in your analysis of how bad that is, and what to do about mitigating them.

Starting with 'what happens if development ceases' - In the case of an open source product, if everyone else in the world gave up on the thing, you'd still have the option of doing it yourself, WITHOUT having to start from zero. Since that's unlikely to happen all at once, you'd actually have a good bit of lead to time to decide whether to hire devs, or switch, or whatever. Obviously Joomla suits your needs at the moment, so re-inventing the wheel at this point is a complete waste of money. The amount of work involved in writing a full-on CMS is NOT small.

On the subject of security bugs - it is FAR more likely that you'd introduce security issues into a bespoke product than if you use one that lots of other folks are constantly fooling with and which has a fairly high profile like Joomla. It's unlikely that your initial efforts wouldn't have at least a couple of major security flaws.

If you are really interested in mitigating these concerns to the greatest possible degree, then I'd advise you to hire a developer or two to perform security analysis and fixes on Joomla itself. The idea here is that instead of re-inventing the wheel, you'd make the wheel you're already using more secure by fixing problems, and you'd have an in-house dev already familiar with Joomla in the event that you did need to take over development completely.

Title: Should we use an outside CMS?

Body:
I work at a web design/development shop.  Everything we do is centered around the Joomla! CMS.  I'm a bit worried-if anything goes wrong with Joomla (major security flaw revealed, Joomla folds and ceases development) we're sunk.

I'm meeting with the CEO to plan the next few steps for our company.  Should I recommend that we create our own in-house CMS or am I just being paranoid about a single point of failure?


问:
Should you create a class within a method?
I have made a program using Java that is an implementation of this project: http://nifty.stanford.edu/2009/stone-random-art/sml/index.html.  Essentially, you create a mathematical expression and, using the pixel coordinate as input, make a picture.  After I initially implemented this in serial, I then implemented it in parallel due to the fact that if the picture size is too large or if the mathematical expression is too complex (especially considering the fact that I made the expression recursively), it takes a really long time.  During this process, I realized that I needed two classes which implemented the Runnable interface as I had to put in parameters for the run method, which you aren't allowed to do directly.  One of these classes ended up being a medium sized static inner class (not large enough to make an independent class file for it though).  The other though, just needed a few parameters to determine some indexes and the size of the for loop that I was making run in parallel - here it is:

```<code>class DataConversionRunnable implements Runnable
    {
        int jj, kk, w;

        DataConversionRunnable(int column, int matrix, int wid)
        {
            jj = column;
            kk = matrix;
            w = wid;
        }

        public void run()
        {
            for(int i = 0; i < w; i++)
                colorvals[kk][jj][i] = (int) ((raw[kk][jj][i] + 1.0) * 255 / 2.0);
            increaseCounter();
        }
    }
</code>```

My question is should I make it a static inner class or can I just create it in a method?  What is the general programming convention followed in this case?

答:
Jon Lin's got the solution you want.  (+1 to Jon)  An anonymous class is the way to go.  Otherwise:  if you want to use the same class more than once, a named local class can be used, just as you have it in your question.  If you need it in more than one method, switch to a private inner class.  If it helps other classes work with the parent class, then use a public inner class.  If it's not tightly tied to its parent, put it in its own file.

The basic idea is encapsulation of the class (as opposed to data--a variable or field).  The class itself should be known only to the code that needs to know about it.  If you make it a nested class, someone looking at the reference has to go look for the class code and someone looking at the nested class code has to go looking for a reference.  With a good IDE this is not too hard, but with local/anonymous classes its easy even when looking at the code in Notepad.  And then there's the problem of getting data to and from the class....

Java is really good with this.  Some other languages don't allow local classes.  To be fair, they don't require them, either--a lot of standard Java classes are written with the idea the user can easily generate swarms of local, temporary classes.  But, as in your case, local classes are quite handy even without the system classes that want them.


问:
Parsing multiple file formats/protocols
We are starting a project where we will need to write parsers for a bunch of binary file formats, each of them representing very similar data (time-value series from different measurement devices).

Since we are starting from scratch, I would like to get it right, and I see two possible approaches:

write dedicated, home grown binary parsers for each format separately, or

represent binary formats using a grammar, and then use some standard algorithms for lexical analysis/tokenization.

Whenever I seek for advice on how to build a parser, I find most guys advocating the latter approach. However, I don't have much experience with formal grammars and languages, and I am afraid that there might be a learning curve before we get results.

So, I basically have these questions:

What is the problem with coding parsers "by hand"?

Is there a practical "size limit" of a problem when it pays off to invest in learning the "formal approach"?

Most parsing examples focus on textual files. What is the good way to specify grammar for a binary parser?

答:
I don't have much experience with formal grammars and languages, and I
  am afraid that there might be a learning curve before we get results.

Spend a couple afternoons building a simple project to try it out. Given that you need to support "a bunch" of formats, it's a good bet your investment in learning to use tools that do exactly what you need will pay off quickly.

What is the problem with coding parsers "by hand"?

The problems are mainly:

writing and maintaining parsers by hand is time consuming, difficult, and error-prone

writing the code yourself means that there's another layer of indirection between the two things you care about: the format and the parser. If the parser doesn't work quite right, you have to look at the code to figure out why. If you can specify the format as a grammar instead, it should be easier to see where the problem is (or avoid problems in the first place).

Is there a practical "size limit" of a problem when it pays off to
  invest in learning the "formal approach"?

I suspect that the where the line is depends on your situation. Coding parsers by hand will always feel easier if you don't know any other way. As you get more comfortable with tools like flex and bison (or whatever you choose), the line will move.

Most parsing examples focus on textual files. What is the good way to
  specify grammar for a binary parser?

I don't think that needs to be the case. For example, flex lets you specify input characters in terms of octal or hex values.

Title: Parsing multiple file formats/protocols


问:
COBOL program or JCL?
I have to perform 3 tasks:
an insert, a delete, and a write

I'm not sure what the best way to do this is. My mainframe program design skills aren't too tight, so I was looking for advice.

Could I avoid doing a COBOL program for this?
The way I see it, I just need JCL that executes SQL statements. If I design my statements correctly, then they should be able to preform tasks 1 and 2 this way. But I'm thinking I may need to have a COBOL program to write to a file? If I do, would I just run through database with a cursor, then process each row and take appropriate action based on the row?

Each task seems similar, but the queries are different and produce different results, so the SQL statements are very different. But they are all working with the same table.

Task 1:

preform SQL query

For each row that the query picks up

Insert a new row based on that row

Task 2:

perform SQL query

For each row that the query picks up

delete the record

Task 3:

perform SQL query

For each row that the query picks up

Write that record to a file

答: You might be able to find some kind of query execution facility that would let you avoid writing much code for task 2 (just executing a DELETE statement), but if you need to reformat, filter or augment data, you're probably going to need to write a program.  These are pretty simple tasks, though, so I would bet you can find examples without too much trouble.</p>

Title: COBOL program or JCL?


答: Depending on how complex your file formats are, I suspect you'd be better off writing a utility parsing library and writing your lexers/parsers by hand.  I've done this before for parsing BAF records from phone switches and you can crank out the basic framework pretty quickly (a couple of days).  If you were already familiar with parsing tools like flex and bison then I'd second Caleb's suggestion, but since you're not I'd suggest sticking with what you know.  I assume that nobody on your team is familiar with parsing tools either, so this way everyone should be able to maintain the code going forward (no 'single point of failure' when a parsing error/bug crops up).</p>

Title: Parsing multiple file formats/protocols

Body:
We are starting a project where we will need to write parsers for a bunch of binary file formats, each of them representing very similar data (time-value series from different measurement devices).

Since we are starting from scratch, I would like to get it right, and I see two possible approaches:

write dedicated, home grown binary parsers for each format separately, or

represent binary formats using a grammar, and then use some standard algorithms for lexical analysis/tokenization.

Whenever I seek for advice on how to build a parser, I find most guys advocating the latter approach. However, I don't have much experience with formal grammars and languages, and I am afraid that there might be a learning curve before we get results.

So, I basically have these questions:

What is the problem with coding parsers "by hand"?

Is there a practical "size limit" of a problem when it pays off to invest in learning the "formal approach"?

Most parsing examples focus on textual files. What is the good way to specify grammar for a binary parser?


问:
Are there any major alternatives to Waterfall and Agile?
I am curious if anyone knows of any methodologies that are significantly different (not a recombination) and I would especially appreciate anyone who brought forward any experience with alternatives.</p>

答:
Cowboy Coding

Pure unstructured, unmanaged, freeform development. It can be useful for small hobby projects that lack a deadline or even a clear goal, but likely won't work in a corporate setting.


问:
Confusion of scope of a variable: Is Global Variable a solution?
I am newly learning C Programming.

When we have a C Program with lot of functions, parameter passing, calling and all - It becomes a great problem as to which variable must be declared where.

My question is: If I declare all the variables (or atleast the variables that are confusing me) as Global Variables - my problem will be solved - but is that a Good Practice?

答:
Certain variable names tend to be used over and over again. For example, temp,i,theVar, and counter. It is better to give them a small scope so that you don't find yourself spending too much time creatively coming up with variable names, only to spend more time remembering them.

Have every variable be global and you'll end up with names like temp2, theOtherVar, timer (not to be confused with counter), loop controls reaching every letter of the alphabet, etc..

Limit the scope if you can. If only one function will use a variable, declare it in that function. You should only make a variable global if you plan to use it everywhere throughout your program. And even then it isn't always the best idea.

The whole point of having functions is that you can encapsulate pieces of logic. If, for example, you have a function that finds the distance between two coordinates, you should be able to pass the coordinates to it, get the distance back, and not have to worry about what happened in between. But if the function uses a global variable, and you accidentally modify it elsewhere in the program, you may spend hours trying to figure out why your function is acting unusual.


问:
Why a static main method in Java and C#, rather than a constructor?
I’m Looking for a definitive answer from a primary or secondary source for why (notably) Java and C# decided to have a static method as their entry point, rather than representing an application instance by an instance of an Application class (with the entry point being an appropriate constructor).

Background and details of my prior research

This has been asked before. Unfortunately, the existing answers are merely begging the question. In particular, the following answers don’t satisfy me, as I deem them incorrect:

There would be ambiguity if the constructor were overloaded. – In fact, C# (as well as C and C++) allows different signatures for Main so the same potential ambiguity exists, and is dealt with.

A static method means no objects can be instantiated before so order of initialisation is clear. – This is just factually wrong, some objects are instantiated before (e.g. in a static constructor).

So they can be invoked by the runtime without having to instantiate a parent object. – This is no answer at all.

Just to justify further why I think this is a valid and interesting question:

Many frameworks do use classes to represent applications, and constructors as entry points. For instance, the VB.NET application framework uses a dedicated main dialog (and its constructor) as the entry point1.

Neither Java nor C# technically need a main method. Well, C# needs one to compile, but Java not even that. And in neither case is it needed for execution. So this doesn’t appear to be a technical restriction. And, as I mentioned in the first paragraph, for a mere convention it seems oddly unfitting with the general design principle of Java and C#.

To be clear, there isn’t a specific disadvantage to having a static main method, it’s just distinctly odd, which made me wonder if there was some technical rationale behind it.

I’m interested in a definitive answer from a primary or secondary source, not mere speculations.

1 Although there is a callback (Startup) which may intercept this.

答:
Well, there're lots of main functions out there which just run an infinite loop. A constructor working this way (with an object that never gets constructed) is what seems odd to me.

There're so many funny things about this concept. Your logic running on top of a unborn object, objects that born to die (since they do all their job in the constructor), ...

Wouldn't all these side effects gonna corrupt much more the OO wagon than a simple public (because it needs to be accessed by an unknown) static (because no instance is needed for us to get started) void main (because it's the entry point)?

For a simple, plain, function entry point to exist in Java, public and static would automatically be required. Although being a static method, it boils down to what we can get more near of a plain function to accomplish what's wanted: a simple entry point.

If you are not going to adopt a simple, plain, function entry point as an entry point. What's next that doesn't seems odd as a contructor that's not meant to construct?

OwnerDisplayName: Konrad Rudolph


答:
I like @Buttons840's description of it as an undo button for the code base. It might also help to compare it to a (less frustrating) version of Word or InDesign's "Track Changes" feature. In my experience, it definitely reduces the need for one person to go around telling others not to touch files X, Y, and Z for the next few hours, which is handy for getting things done.

I've also found the fine-grained version info incredibly useful for fixing/working around bugs. I stash the SVN version number (via the $Id property) in nearly every data file I generate. That way, if (when?) a bug is found, it's trivial to identify files with potential problems and regenerate them or have other code compensate for the bug.


答:
This has a very clear answer, actually: Source code came first – by a big margin.

Before giving the technical details, a bit of perspective:

The first programming languages were all translated into machine language or assembler by hand. The idea of using a piece of software to automate this translation (either via a compiler or evaluator) always came later, and was far from intuitive.

Consider this quote of the Wikipedia article on FORTRAN which illustrates the reluctance compilers had to face:

… the first FORTRAN compiler [was] delivered in April 1957. This was the first optimizing compiler, because customers were reluctant to use a high-level programming language unless its compiler could generate code whose performance was comparable to that of hand-coded assembly language. [emphasis mine]

=> By the time the FORTRAN compiler hit the market (1957), people were already happily programming both in assembly language and FORTRAN.

The case was similar for LISP (from Hackers & Painters):

Steve Russell said, look, why don't I program this eval …, and I said to him, ho, ho, you're confusing theory with practice, this eval is intended for reading, not for computing. But he went ahead and did it. That is, he compiled the eval in my paper into IBM 704 machine code, fixing bug, and then advertised this as a Lisp interpreter, which it certainly was. So at that point Lisp had essentially the form that it has today..."

Once again, not only does the source code (in LISP) predate the interpreter, the latter wasn’t even implicit in the former.

But these developments are relatively late. Even not considering Charles Babbage’s Analytical Engine and Ada Lovelace’s related first program, there were programming languages in the 20th century which predated compilers:

Konrad Zuse’s Plankalkül and the mathematical construct of λ-calculus introduced by Alonzo Church. Both of these are indubitably formally specified programming languages, but neither had a compiler at the time.

To put this into perspective, λ-calculus is from the 1930s, and Plankalkül was developed around 1945. By contrast, the first FORTRAN compiler came out in 1957 (but again three years after FORTRAN was specified).

Title: What came first, the compiler, or the source?

Body: I'm curious about the birth of the compiler.  How did programming begin?  Did people first build hardware that recognized a certain set of commands, or did people define a language and then build hardware around it?  And on a related note, what was the first programming language?</p>


答:
A big part of learning to program well is learning to design your program so that the parts that need to know about each other do, and the parts that don't need to know about each other don't.

Imagine starting a company. When you have three or four employees, everybody naturally knows everybody else, and things work fine. But that doesn't scale even to 100 employees, let along 1,000. At some point you have to start organizing your employees into departments that are each responsible for certain aspects of the business. Employees outside the Accounting department shouldn't go messing with the books, and employees outside the shipping department shouldn't be shipping products. Imposing structure on the business makes things work better -- it makes the business work in an organized, predictable way. That structure might irritate the old-timers who are used to doing a little bit of everything, but it's necessary for the company's growth.

The same thing is true for programs. When you're writing Hello, world! or FizzBuzz or Tic Tac Toe, all your code fits in a single file and you don't need to think much about structure. But that doesn't scale. When you start writing programs that are more complex, you have to start imposing structure on the code. You have to think about how to group tasks, what information is required for each module to do it's job, and how different modules will communicate.

Using global variables for everything is like running a company where all the employees know each other and know everything about the business -- it'll work, for a while, but it makes it hard to grow. The sooner you learn to organize your program and the flow of information through it, the sooner you'll have learned what programming is really all about, and the sooner you'll be able to write useful programs.

Title: Confusion of scope of a variable: Is Global Variable a solution?

Body:
I am newly learning C Programming.

When we have a C Program with lot of functions, parameter passing, calling and all - It becomes a great problem as to which variable must be declared where.

My question is: If I declare all the variables (or atleast the variables that are confusing me) as Global Variables - my problem will be solved - but is that a Good Practice?


答: The bad bosses/companies really make you appreciate the good ones.  It's good that you had the experience when you are young, so when you find a good place (which is a combination of examination and luck) you'll know what you found.  The last job I had was pure misery, but now I have the best job I've ever had, and I know it.


问:
How should I encapsulate database access?
What are some examples of good class structures used to manage database access? I am a fan of class encapsulation and would prefer the containers (e.g. car) not to perform database tasks.

I would also like the ability to easily drop in things like a database cache in future.

I often take the pattern of container classes, complete with getters and setters for validation and database access performed by a single singleton class. That being said, this often gets mixed between the two and becomes quite confusing.

Sorry if my question is hard to understand; I'm not absolutely sure on terms regarding databases. Please feel free to ask for clarification if needed.

答:
I have used the Strategy Pattern to encapsulate data access. This pattern allows you to hide the the type of storage you are using behind a common interface. In the interface, define your data access methods with disregard for the type of storage (file,database,web). Then for your current storage choice, in a class realizing the strategy interface, implement the data access details. This way your application doesn't care about the data source you are using.

You can also build a service layer that uses the current data storage strategy instance to define more application specific details instead of mixing data access and business logic together.


答: You can quickly run some standalone tests on a class, during development, by sticking a main() in the class you're trying to test.

Title: Why a static main method in Java and C#, rather than a constructor?

Body:
I’m Looking for a definitive answer from a primary or secondary source for why (notably) Java and C# decided to have a static method as their entry point, rather than representing an application instance by an instance of an Application class (with the entry point being an appropriate constructor).

Background and details of my prior research

This has been asked before. Unfortunately, the existing answers are merely begging the question. In particular, the following answers don’t satisfy me, as I deem them incorrect:

There would be ambiguity if the constructor were overloaded. – In fact, C# (as well as C and C++) allows different signatures for Main so the same potential ambiguity exists, and is dealt with.

A static method means no objects can be instantiated before so order of initialisation is clear. – This is just factually wrong, some objects are instantiated before (e.g. in a static constructor).

So they can be invoked by the runtime without having to instantiate a parent object. – This is no answer at all.

Just to justify further why I think this is a valid and interesting question:

Many frameworks do use classes to represent applications, and constructors as entry points. For instance, the VB.NET application framework uses a dedicated main dialog (and its constructor) as the entry point1.

Neither Java nor C# technically need a main method. Well, C# needs one to compile, but Java not even that. And in neither case is it needed for execution. So this doesn’t appear to be a technical restriction. And, as I mentioned in the first paragraph, for a mere convention it seems oddly unfitting with the general design principle of Java and C#.

To be clear, there isn’t a specific disadvantage to having a static main method, it’s just distinctly odd, which made me wonder if there was some technical rationale behind it.

I’m interested in a definitive answer from a primary or secondary source, not mere speculations.

1 Although there is a callback (Startup) which may intercept this.


答:
To my understanding the primary reason is simple.  Sun was a Unix company selling Unix machines and Unix is what the C "main(args)" convention for invoking a binary was designed for.

Additionally Java was explicitly designed to be easy to pick up for C and C++ programmers, so there was no good reason for not just simply picking up the C convention.

The chosen approach where every class can have an invocation method is quite flexible, especially in combination with the Main-Classline in the MANIFEST.MF file in a runnable jar.


问:
What popular "best practices" are not always best, and why?
"Best practices" are everywhere in our industry.  A Google search on "coding best practices" turns up nearly 1.5 million results.  The idea seems to bring comfort to many; just follow the instructions, and everything will turn out fine.

When I read about a best practice - for example, I just read through several in Clean Code recently - I get nervous.  Does this mean that I should always use this practice?  Are there conditions attached?  Are there situations where it might not be a good practice?  How can I know for sure until I've learned more about the problem?

Several of the practices mentioned in Clean Code did not sit right with me, but I'm honestly not sure if that's because they're potentially bad, or if that's just my personal bias talking.  I do know that many prominent people in the tech industry seem to think that there are no best practices, so at least my nagging doubts place me in good company.

The number of best practices I've read about are simply too numerous to list here or ask individual questions about, so I would like to phrase this as a general question:

Which coding practices that are popularly labeled as "best practices" can be sub-optimal or even harmful under certain circumstances?  What are those circumstances and why do they make the practice a poor one?

I would prefer to hear about specific examples and experiences.

答:
GoTo Considered Harmful

If you are implementing a state machine a GOTO statement can make more sense (readability and efficient code) than a "structured programming" approach. It really worried some co-workers when the first piece of code I wrote in a new job included not just one but several goto statements. Fortunately they were intelligent enough to realize that it was actually the best solution in this particular case.

Any "best practice" that doesn't allow for sensible and documented exceptions to its rules is just plain scary.


问:
Scripting language for filling out web form
I have a job as an intern at a technology company, I was given the unfortunate job of performing some data entry into our web management system. The information entered into the web form is stored in a MySQL DB. Upon receiving the data I realized I would have to submit this online form about 1000 different times all consisting of about 10 different text fields / check boxes per form. (So in other words, would be completely mind numbing and be a ridiculous waste of time and resources, or so I thought...)

Having used databases a good bit prior to this, my immediate reaction was to just write a short MySQL script to bulk import all of the data, especially since it was already presented to me in an excel spreadsheet ready to go. Thought it may have been some sort of a test since it seemed too obvious. I wrote the script which consisted of about 10 lines of code but was then informed I couldn't be trusted with MySQL Admin privileges to run said script. So my next thought would be to write a script to just enter the information through the web form (Which will take ten times longer but it's what I have to)

Being unfamiliar with scripting of this nature (seems like I would need something similar to a bot, but the good kind) I was unsure of how to proceed to do this. Is there a preferred language to use to enter the data i have into the web form I do have access to? I'm not particularly looking for this to be done for me by any means just a nice point in the right direction as far as what scripting language to use and how to pair that with the data I have that needs to be entered.

Thanks for the help/ valuable input!

EDIT:

Is there a way to perform this using perl without having access to place any files on the server?

Would I be able to run some Javascript loops to pull the data out of .csv or just a .txt format with line delimiters and insert it into the web form?

答:
Firstly, you probably should change your attitude a little.  You say " given the unfortunate job  "  - why? I mean, you may learn valuable lessons here. Plus, you are an intern. It's a great job, and it does involve "dirty" work.

Hmm, I might advise you to check out Selenium. If you have to automate a web function, it's quite useful to use Selenium.


答:
There are a few possibilities (last one would be the easiest and most sensical, in my opinion, except if that's meant to be a long-term and reusable piece of code):

Use a web-testing framework

They are meant to do this sort of stuff, so obviousy they do it well. But I think they're a bit heavyweight for what you want to do. For instance, Adel recommended Selenium, which is a great testing tool but a freaking monster to get started with (and will fire up browsers, except if you use the new WebDriver-based API that will use a browser-less driver like HtmlUnit.

So, that's why I'd recommend, if you go down this route, to just use something like HtmlUnit (which you could invoke from a Java program, or from any other JVM-based language: Groovy, Scala, Clojure...). But I'd still regard this as relatively heavy.

Use a general-purpose scripting language

Python, Perl and a herd of others will allow you to write this from scratch quickly, or to reuse an existing library to implement your own HTTP client to send your POST requests.

If this think is going to be maintained in the future, I'd go with Python. If it's going to be quick and dirty, Perl is a hacker's best friend (and CPAN its favorite sledgehammer).

Use bare shell scripting and something like curl

Go even more minimalistic: bare shell-scripting to process your inputs and format your data, some curl invocations to POST to the server, and voila!

If you're on Windows, Powershell will be your friend.

There are hundreds of other possibilities to do this, I barely mention the ones that come to mind and that I'd use.

If that was my task, I'd probably write an ugly command line that:

if it's a simple spreadsheet (not something where you'd need to cherry pick cell values):

converts the .xls to .csv,

pipe it through to whatever suits you to transform the data,

pipe it to a curl command to POST.

if it's a complex spreadsheet (where you'd need to cherry pick cell values):

script the data extraction bit,

invoke curl or use the scripting language's built-in libs to POST.

I'only use a more advanced testing framework if:

I'm likely to be asked to do this again for different data formats,

I'm likely to be asked to do this again for different datasources and target DBs,

I'm likely to be asked to do this often.

In that case, a more engineered approach does make some sense, for maintainability and extensibility.

In all cases, remember to backup that script and pass it along, and to document it (a README would do) and implement a usage. If they have one, version it in their SCM.

Note: another reason why taking the web-form submission approach might be better than the "direct to SQL" approach is that the server receiving the form might be doing extra checks you aren't aware of at this time.

Not saying it's the case, but maybe security wasn't the only reason.

Good luck with the job.

EDIT: just noticed you tagged this as "PHP". I don't really see why, as that would imply for the code to be server-side (well, you could use PHP for any kind of scripting, but why do this to yourself?)

Title: Scripting language for filling out web form

Body:
I have a job as an intern at a technology company, I was given the unfortunate job of performing some data entry into our web management system. The information entered into the web form is stored in a MySQL DB. Upon receiving the data I realized I would have to submit this online form about 1000 different times all consisting of about 10 different text fields / check boxes per form. (So in other words, would be completely mind numbing and be a ridiculous waste of time and resources, or so I thought...)

Having used databases a good bit prior to this, my immediate reaction was to just write a short MySQL script to bulk import all of the data, especially since it was already presented to me in an excel spreadsheet ready to go. Thought it may have been some sort of a test since it seemed too obvious. I wrote the script which consisted of about 10 lines of code but was then informed I couldn't be trusted with MySQL Admin privileges to run said script. So my next thought would be to write a script to just enter the information through the web form (Which will take ten times longer but it's what I have to)

Being unfamiliar with scripting of this nature (seems like I would need something similar to a bot, but the good kind) I was unsure of how to proceed to do this. Is there a preferred language to use to enter the data i have into the web form I do have access to? I'm not particularly looking for this to be done for me by any means just a nice point in the right direction as far as what scripting language to use and how to pair that with the data I have that needs to be entered.

Thanks for the help/ valuable input!

EDIT:

Is there a way to perform this using perl without having access to place any files on the server?

Would I be able to run some Javascript loops to pull the data out of .csv or just a .txt format with line delimiters and insert it into the web form?


答:
I prefer the Repository Pattern to encapsulate data access.  In a nutshell, the repository is responsible for loading all the data required for a specific object.  Say you have a Car object, like in your example.  But all the attributes for the car, make, model, year, owners, features (CD player, 4wd etc) are stored in various tables throughout the database.  The repository determines how to load and save the data.  If multiple smaller queries are needed, fine, but only the repository pattern needs to know that.  The service layer invoking the repository only needs to know which repository to invoke.

That can then be combined with the unit of work pattern.  So in your example, the service layer would say it needs to load a car entity, it has some sort of unique identifier, and sends that identifier down to the repository. The repository returns the car entity.  Some other code manipulates the car entity and sends that entity back to the repository so it can be saved.

If you really want to go all out, the repository layer would only expose interfaces, such as ICarRepository.  The repository would contain a factory which the service layer would use to get the ICarRepository interface.  All database access would be hidden behind an interface, which makes unit testing much much easier.

Title: How should I encapsulate database access?

Body:
What are some examples of good class structures used to manage database access? I am a fan of class encapsulation and would prefer the containers (e.g. car) not to perform database tasks.

I would also like the ability to easily drop in things like a database cache in future.

I often take the pattern of container classes, complete with getters and setters for validation and database access performed by a single singleton class. That being said, this often gets mixed between the two and becomes quite confusing.

Sorry if my question is hard to understand; I'm not absolutely sure on terms regarding databases. Please feel free to ask for clarification if needed.


答:
This question is pivots strongly on our semantic interpretation of 'source code'. If we define it as 'text-based computer instructions that are compiled', then presumably a compiler came first.

I'm more inclined to go with something more authoritative, such as Mark Harman's paper "Why Source Code Analysis and Manipulation Will Always Be Important" presented at the Tenth IEEE International Working Conference
on Source Code Analysis and Manipulation

Deﬁnition 1 (Source Code): For the purpose of clarity ‘source code’ is
  taken to mean any fully executable description of a software system.
  It is therefore so construed as to include machine code, very high
  level languages and executable graphical representations of systems.

And I think your answer is implicit in that definition - source code most certainly came first.


答:
This is an example of database Factory pattern;</p>

```<code>using System.Reflection;
using System.Configuration;

public sealed class DatabaseFactory
{
    public static DatabaseFactorySectionHandler sectionHandler = (DatabaseFactorySectionHandler)ConfigurationManager.GetSection("DatabaseFactoryConfiguration");

    private DatabaseFactory() { }

    public static Database CreateDatabase()
    {
        // Verify a DatabaseFactoryConfiguration line exists in the web.config.
        if (sectionHandler.Name.Length == 0)
        {
            throw new Exception("Database name not defined in DatabaseFactoryConfiguration section of web.config.");
        }

        try
        {
            // Find the class
            Type database = Type.GetType(sectionHandler.Name);

            // Get it's constructor
            ConstructorInfo constructor = database.GetConstructor(new Type[] { });

            // Invoke it's constructor, which returns an instance.
            Database createdObject = (Database)constructor.Invoke(null);

            // Initialize the connection string property for the database.
            createdObject.connectionString = sectionHandler.ConnectionString;

            // Pass back the instance as a Database
            return createdObject;
        }
        catch (Exception excep)
        {
            throw new Exception("Error instantiating database " + sectionHandler.Name + ". " + excep.Message);
        }
    }
}
</code>```

Body:
This is an example of database Factory pattern;

using System.Reflection;
using System.Configuration;

public sealed class DatabaseFactory
{
    public static DatabaseFactorySectionHandler sectionHandler = (DatabaseFactorySectionHandler)ConfigurationManager.GetSection("DatabaseFactoryConfiguration");

    private DatabaseFactory() { }

    public static Database CreateDatabase()
    {
        // Verify a DatabaseFactoryConfiguration line exists in the web.config.
        if (sectionHandler.Name.Length == 0)
        {
            throw new Exception("Database name not defined in DatabaseFactoryConfiguration section of web.config.");
        }

        try
        {
            // Find the class
            Type database = Type.GetType(sectionHandler.Name);

            // Get it's constructor
            ConstructorInfo constructor = database.GetConstructor(new Type[] { });

            // Invoke it's constructor, which returns an instance.
            Database createdObject = (Database)constructor.Invoke(null);

            // Initialize the connection string property for the database.
            createdObject.connectionString = sectionHandler.ConnectionString;

            // Pass back the instance as a Database
            return createdObject;
        }
        catch (Exception excep)
        {
            throw new Exception("Error instantiating database " + sectionHandler.Name + ". " + excep.Message);
        }
    }
}


问:
Is an API in C++ a better alternative to computing directly in SQL?
I need to perform large amounts of computations on data storerd in a busy Microsoft SQL server. Would it be faster if I retrieve the data from the server, perform the computations locally in C++, and possibly later update the tables on the server, all through an API?

Many thanks.

答:
You need to determine (or share with us) busy how? Busy because the data has a lot of additions, updates, reads or all the above?

A table/database/server that has heavy transaction activity, can be periodically copied to a place that is going to be reported/read a lot. How up-to-date does it have to be? You tell us.

Is there any down-time, when these calculations/updates can be done or are you 24/7/365?

Many back-office operations can wait for their recalculated data. Maybe you just need to ask?


问:
Erlang web frameworks survey
(Inspired by similar question on Haskel)

There are several web frameworks for Erlang like Nitrogen, Chicago Boss, and Zotonic, and  a few more.

In what aspects do they differ from each other? For example:

features (e.g. server only, or also client scripting, easy support for different kinds of database)

maturity (e.g. stability, documentation quality)

scalability (e.g. performance, handy abstraction)

main targets

Also, what are examples of real-world sites / web apps using these frameworks?

EDIT: Starting a bounty in hopes that it will get some conversation going

答:
The comparison of Erlang web frameworks has been moved to Github:

https://github.com/evanmiller/ChicagoBoss/wiki/Comparison-of-Erlang-Web-Frameworks

Title: Erlang web frameworks survey


问:
If you could only have one programming related book on your bookshelf what would it be and why?
One per answer please. I'll add my favourite as an answer.</p>

答:
The Pragmatic Programmer: From Journeyman to Master
(Andrew Hunt and David Thomas)</p>


问:
What decent web-frameworks exists for functional programming?
I would like to do some web programming using functional programming. What decent web-frameworks exists for functional programming languages?</p>

答:
There is a comparison of Erlang web frameworks on Github:

https://github.com/evanmiller/ChicagoBoss/wiki/Comparison-of-Erlang-Web-Frameworks

I haven't played with all the frameworks listed there so I don't want to judge, but I've been using Zotonic quite extensively in my currently project and I can wholeheartedly recommend it. As far as I know it's the only Erlang framework which is not only a framework but also a full-blown CMS. So you can start easily with just the CMS features and then expand the website by adding your custom functionality using your own modules. In my case I am using it purely as a framework because at this moment the CMS features work only with PostgreSQL and I can't use a separate database. But even just as a framework it offers lots of features not always found in the other frameworks.

What's very nice is that the project is being very actively developed because the people behind Zotonic design and implement websites and they use it as their CMS of choice.

If I had to choose then I would probably give Zotonic the first chance, then ChicagoBoss, and then Nitrogen.


问:
Is saying "JSON Object" redundant?
If JSON stands for JavaScript Object Notation, then when you say JSON object, aren't you really saying "JavaScript Object Notation Object"?

Would saying "JSON string" be more correct?

Or would it be more correct to simply say JSON? (as in "These two services pass JSON between themselves".)

答:
I would also like to point out that even though it's not a case of redundancy here, redundant practices with acronyms are being done all the time, especially with technical terms (e.g. ATM machine, TCP/IP protocol, UDP protocol, SMTP protocol, etc.).

By being redundant and restating the essence of the acronym it is easier to convey what the acronym relates to.

Title: Is saying "JSON Object" redundant?


答:
My suggestion is-

Split your code in several source files. Keep related code together and unrelated code separate. I mean modularize the project.

Try to pass parameters instead of using global variables for read-only purpose. For the parameter which will be changed in some function, use pointers.

Also consider using pointers for passing big data like structures.

If desperately needed, use global variable in the file scope by using 'static' modifier. Then the variable will be accessible from that file but not from other files.


答:
In a word,

NO!

Don't EVER do that!  NOT EVER!

Take special note of Why is Global State so Evil?


问:
How can I maintain proficiency in multiple languages?
How can I maintain proficiency (if not expertise) in multiple languages?

In any large organization it seems necessary to know more than one language.  For example, this week I've looked at if not written code in the following languages.

VBA

C

C#

Java

Thankfully they're all imperative languages, or I would have lost my mind.

I struggled for a day or so with the C as it's been a while (read: years) since I've used it seriously.

What tips, habits, and training is there for keeping up your knowledge in so many languages?

答:
I like to play strategy games.  Seriously.  My experience has been that it's less about retaining proficiency or expertise in particular skills and more about maintaining the focus and mentality it takes to learn (or relearn) things quickly.  One week I'll be developing in C#, able to experiment with WPF and new techniques in unit testing, whereas the next I may be waist-deep in a hack job on a legacy VB6 code base.  Or I might be asked to learn Python while on a flight overseas to help optimize a system I've never even seen before.  A month later, I can be deeply entrenched in a ladder logic program, where you still have to think about how you want to arrange your bits in the few thousand words of memory you're given, taking care not to exceed the 10,000 instruction limit.

There's no way that I could find time to keep up on all of the different systems I might need to maintain, so if you're in this kind of highly mutable environment (as it sounds you are), the best advice I can give is to use your personal time to unwind so that you can approach your professional challenges with the full energy and focus required to navigate the maelstrom.  It also helps a lot if you enjoy the variety and the challenge.  If you'd much rather dig deep into a particular domain, try expressing your concerns to your boss; a good manager will want to get the best results they can from their team and allocating the right kind of work to people is a big part of that.


问:
How to find an error in a tcp server application for which there is no source code
I have a c++/cli tcp client application sending a data in a specific format like L,20100930033425093,-5.929958,13.164021
to a main application on port 9000.The main application is actually done by the other vendor and I dont have the source code for that.

Now,I can communicate to the desired application using the IP and Port No.But the data supposed to be visible on the Main Application GUI is not showing up. But I used a different socket server demo application with same IP as the main application to receive the data I am sending.It works perfectly fine. Now I do not know where the error is or whether the stream is received on the other side. How can I effectively solve this situation. I am asking this in a broader picture to get some ideas.

Any suggestions or discussion on this will be helpful?

答:
Try the following:

Check your data. Are you sure it's the right format? Sorry for being Captain Obvious, but I regularly forget to include important, but invisble, characters like linebreaks, null bytes, etc.

Use Wireshark to look at what your application sends and what the demo application sends. If your message shows up in Wireshark you can also be pretty sure it will reach its destination, since you're using TCP.

Ask the main application vendor for support, if at all possible. Send them a sample script showing how you connect to their server and what data you are transmitting.


答:
It is not your job to find the error, this is the duty of the other vendor.

All you have to do is to report the bug with as many relevant information as possible. For that, you may want to follow Joel's advices:

Every good bug report needs exactly three things.

Steps to reproduce,

What you expected to see, and

What you saw instead.

Title: How to find an error in a tcp server application for which there is no source code

Body:
I have a c++/cli tcp client application sending a data in a specific format like L,20100930033425093,-5.929958,13.164021
to a main application on port 9000.The main application is actually done by the other vendor and I dont have the source code for that.

Now,I can communicate to the desired application using the IP and Port No.But the data supposed to be visible on the Main Application GUI is not showing up. But I used a different socket server demo application with same IP as the main application to receive the data I am sending.It works perfectly fine. Now I do not know where the error is or whether the stream is received on the other side. How can I effectively solve this situation. I am asking this in a broader picture to get some ideas.

Any suggestions or discussion on this will be helpful?


问:
Is committing/checking in code everyday a good practice?
I've been reading Martin Fowler's note on Continuous Integration and he lists as a must "Everyone Commits To the Mainline Every Day".

I do not like to commit code unless the section I'm working on is complete and that in practice I commit my code every three days: one day to investigate/reproduce the task and make some preliminary changes, a second day to complete the changes, and a third day to write the tests and clean it up^ for submission. I would not feel comfortable submitting the code sooner.

Now, I pull changes from the repository and integrate them locally usually twice a day, but I do not commit that often unless I can carve out a smaller piece of work.

Question: is committing everyday such a good practice that I should change my workflow to accomodate it, or it is not that advisable?

Edit: I guess I should have clarified that I meant "commit" in the CVS meaning of it (aka "push") since that is likely what Fowler would have meant in 2006 when he wrote this.

^ The order is more arbitrary and depends on the task, my point was to illustrate the time span and activities, not the exact sequence.

答:
I think most of the answers here misses one of the main points in Martin Fowlers statement. This is related to Continuous Integration. Code that isn't checked in (pushed/published/merged) into the mainline isn't tested.

This should not be read as an encouragement to commit whatever code you have in your local machine whenever it's time to leave the office. As pointed out by several others here that would be bad, would break the build and cause an unstable mainline.

However, it is an encouragement to try to make your changes in small steps that can be checked in to the mainline without causing problems. This encourages evolution of the code instead of ripping it all apart and rewriting.

Now, what's good about this way of working?

Not committing large chunks of code or revolutionary changes reduces the chance of breaking the build.

If your commit breaks the build it is fairly trivial to identify what the problems are, to revert it and then commit a fixed version quickly.

By making sure all tests run on every small change in the code, you ensure that you don't introduce subtle bugs or regressions that can come from having code grow outside of the continuous integration scheme.

Of course not all changes lend themselves to this approach. As others pointed out, no rule is absolute. However, for changes that are expected to stay out of mainline for a long time, set up an alternative mainline with it's own continuous integration scheme and follow the same approach towards it. With the distributed VCS's of today that's a fairly easy thing to do.


问:
Separating words in a string
How do I separate words in a string?

In the following I have a random sample of words in a string extracted from text file with over a million words.

Here's the string:
"intervene Pockets Jerusalemand tissues powerful days gadgets rate invention heated Stewartis find communal  working lots internal They caused noise offer goand big jumps lose galaxies All Mall birth child world spin killed produced great center Dont pretend Africa solution times cursor good night professional problem refugees talk"

As you can see, the third word is "Jerusalemand." My goal is to separate "Jerusalem" and "and", and do the same thing for any other words that are stuck together.

Only thing that I could think of as of now is to compare every word in the string to a dictionary (SCOWL perhaps?), and if a segment of the word matches a word in the dictionary, I'll have to split the words to make them independent.

As an example, for "Jerusalemand" I'll loop through every character until a match is found in the dictionary for "Jerusalem," then I can separate that from "and," in turn completing the separation.

Shouldn't there be a better way to do this?

答:
I can't think of any sensible alternatives to the general approach you describe. You're probably going to want to focus your attention on exactly what steps you're going to use to (try to) transform a potential word into one or more verified words.

One thing you could definitely do to speed things up is to check the whole word first, and only check substrings if that lookup fails. This assumes that most potential words are valid words, as appears to be the case in your example.

Some things to consider, in no particular order:

Will there ever be more than 2 words jammed together?

Make sure your dictionary lookup is fast!

A capital letter in the middle of the word could be a good indication of where to start trying to split a word.

Is a split only valid if both the parts are valid words?

What do you want to do if there's a potential word which you can't split into 2 (or more) valid words?

If you really care about efficiency, you may find it's faster to try splitting potential words in half first, rather than starting with the first character and going from there. Valid splits are going to tend to be near the middle of potential words, rather than at the beginning or end. This would make the code responsible for trying all the potential splits a bit more complex though.

Title: Separating words in a string


问:
What should be in a coding standard?
What should be in a good (read:useful) coding standard?

Things the code should have.

Things the code shouldn't have.

Should the coding standard include definitions of things the language, compiler, or code formatter enforces?

What about metrics like cyclomatic complexity, lines per file, etc?

答: A procedure for code reviews to enforce the standard.  Oh, and to find bugs too.</p>

Title: What should be in a coding standard?


问:
Why is Java the lingua franca at so many institutions?
EDIT: This question at first seems to be bashing Java, and I guess at this point it is a bit. However, the bigger point I am trying to make is why any one single language is chosen as the one end all be all solution to all problems. Java happens to be the one that's used so that's the one I had to beat on here, but I'm not intentionality ripping Java a new one :)

I don't like Java in most academic settings. I'm not saying the language itself is bad -- it has several extremely desirable aspects, most importantly the ability to run without recompilation on most any platform. Nothing wrong with using the language for Your Next App ^TM. (Not something I would personally do, but that's more because I have less experience with it, rather than it's design being poor)

I think it is a waste that high level CS courses are taught using Java as a language. Too many of my co-students cannot program worth a damn, because they don't know how to work in a non-garbage-collected world. They don't fundamentally understand the machines they are programming for. When someone can work outside of a garbage collected world, they can work inside of one, but not vice versa. GC is a tool, not a crutch. But the way it is used to teach computer science students is a as a crutch.

Computer science should not teach an entire suite of courses tailored to a single language. Students leave with the idea that all good design is idiomatic Java design, and that Object Oriented Design is the ONE TRUE WAY THAT IS THE ONLY WAY THINGS CAN BE DONE. Other languages, at least one of them not being a garbage collected language, should be used in teaching, in order to give the graduate a better understanding of the machines.

It is an embarrassment that somebody with a PHD in CS from a respected institution cannot program their way out of a paper bag.

What's worse, is that when I talk to those CS professors who actually do understand how things operate, they share feelings like this, that we're doing a disservice to our students by doing everything in Java. (Note that the above would be the same if I replaced it with any other language, generally using a single language is the problem, not Java itself)

In total, I feel I can no longer respect any kind of degree at all -- when I can't see those around me able to program their way out of fizzbuzz problems.

Why/how did it get to be this way?

答:
Your question is supporting the findings of another person who wrote a paper saying Java is so cool but not heavy enough for scientific computing. I think he should just use Big Decimal with all its fine precisions, NANs etc..and get on with it.

I want to live only in a automatic garbage collected world. Its healthier, cleaner, neater, aesthetic, prevents money wasted on health expenses, is more desirable - don't have to tag something as unwanted - simply by dereferencing it or setting it to null or when I move out of scope the item gets automatically tagged for garbage collection..

Ok, now I am talking about Java only but it would be most helpful if this works in the real garbage scenario too. Java is write once run anywhere which is good enough for me for it to be used as a language in schools. No memory leaks and being liked by happy programmers who don't want to spend time tagging every object they use and stop using itself is good logic on behalf of Java.

Java has pointers - well we call them references..
String s1 = "Hello";
String s2 = "Hello";
String s3 = new String("Hello");

s1 and s2 will be pointing to the same String object - which is by reference
s1 == s2, s1.equals(s3) but s1 == s3 is false because s3 is a new reference object - this is java arithmetic of references and I understand all this so sorry, I do not wish to be labeled as someone who does not understand the under lying complexities of pointer arithmetic from C or C++.


问:
Managing multiple people working on a project with GIT
I'm very new to GIT/GitHub (as new as starting yesterday). I would like to know what is the best way to manage multiple people working on the same project with Github. Currently I'm managing one project with four developers.

How do I go about the workflow and making sure everything is in sync?

(Note: All developers will have one universal account.)

Does each developer need to be on a different branch?

Will I be able to handle 2 people working on the same file?

Please post a detailed answer, I'm not a shy reader. I need to understand this well.

答:
If all of the developers have commit access to the repo, you should not need to do anything special. They will pull changes from the repo, make their own changes, commit locally, and then push back into the public repo when they have something working.

If on the other hand you have one (or a few) developer(s) responsible for committing to the repo, and the others are providing patches to these. Have each of them clone the repo into their own accounts and have them send pull-requests when they have a change they want into the main repo.

It's also possible to make specific clones for working on specific features if you wish. Using the same workflow with pull-requests to get changes into the main repo when the feature is done.

If by "All developers will have one universal account" you mean that all developers will share one GitHub account and appear as the same committer in the repo, that's a bad idea. Make separate accounts and set them up as collaborators if you want them all to have commit access.

As for your specific questions:

No, use branches for features, fixes etc that will take more than one commit. More than one developer can be working on the same branch.

Yes, git handles conflicts really well, so there's no problems having people work on the same file. No problems except, conflict resolution may not always be trivial if there's fundamental changes to a file that has been edited by more than one member. This is however nothing that can not be overcome by talking together. Version control does not replace communication.

Good luck!


问:
How do you explain the importance of using a [distributed] version control system to someone who's not in the CS field?
A good example of someone who fits that description might be a project manager.

I was asked by my boss the other day, "what this Github thing is and why it's important?"  He has some proprietary projects so he would need private hosting and I found myself struggling to explain beyond the usual: VCSs make collaboration trivial, provide a history and "backup" of all your data, and allow you to record atomic changes in a code base.  In my mind I was thinking, "it's almost as if you have to use a DRVS to really understand how beneficial it is".

I ended up pointing him to BitBucket because they give you unlimited private repositories (I even had to explain what a repository was).

Does anyone have ay really good concrete examples of how a VCS has saved their ass or made life easier, etc -- basically, how would you sell a DVSC to someone who's not unfamiliar with programming, but not a programmer by profession?

答:
VCSs

Just explain the concept of backups. Backups let you see what you had been working on at a given moment in time. Tell how before VCSs programmers used to copy their entire projects compulsively, generally to save each good and stable release they had, so when things went bad they had a good point of reference of when things worked, compare them with the latest stuff and see where they or someone else messed up and fix it easier by just looking at the differences instead of the whole two backups of the project.

In summary: VCSs let you save backups of your work and give you the ability of seeing only the differences between backups.

DVCSs

As for distributed version control, explain how typical version control used to need a server and an internet connection and that everybody got tired of that because it was slower and everybody worked on a single backup, if one messed up it messed the project for everybody, so with distributed version control everybody can work on their own backup in their machine without an internet connection, and everybody is happy because no one messes with their backup while they work and they can worry about sharing their work later when they are done.

Another good one is that unlike a centralized VCS where there is only one backup, if the machine with the backup catches fire there are still other complete backups to go around (at least one for each developer).

In summary: DVCSs let you work in your own backup without everybody having to be crammed in a single server bothering each other, and let you worry about others changes after your are finished with your stuff. Also, nothing happens if the main repository machine catches fire.


答:
We work with 2 developers and we use this workflow:

On Github we have a master branch and a dev branch

The master branch is the same as production or contains deployment
ready code

The dev branch is ahead of master and contains all new code currently
being worked on

Locally we both work on the dev branch and push to github when something is ready

The other dev fetches any new changes from the dev branch before pushing his new code

When dev branch is good,we merge with the master branch

Locally we have several feature branches issue branches etc.

Title: Managing multiple people working on a project with GIT

Body:
I'm very new to GIT/GitHub (as new as starting yesterday). I would like to know what is the best way to manage multiple people working on the same project with Github. Currently I'm managing one project with four developers.

How do I go about the workflow and making sure everything is in sync?

(Note: All developers will have one universal account.)

Does each developer need to be on a different branch?

Will I be able to handle 2 people working on the same file?

Please post a detailed answer, I'm not a shy reader. I need to understand this well.


问:
How do I handle a user story that I complete, but with compromise and need to revisit?
I have just fulfilled (is that a good term?) two user stories out of a new project backlog I have just built. These are user registration and password reset, both requiring mail. I need to implement a substitute mail component because my initial choice, and a normally reliable one, wasn't working. Because I was focused on delivering the user stories, not debugging the mail component, I swapped it out to deliver working code at sprint end. Do I now log a new support issue for the mailer, or 're-insert' these stories into the backlog? If I do the latter, am I not introducing too much tech detail into user stories?</p>

答:
The Simplest Thing That Will Reasonably Work

In a related comment, the OP says:

My 'workaround' is a quality solution, but the originally envisaged implementation will be an improvement on the workaround, so maybe I can create a new story to improve the email function?

If that's the case, the original question is moot. The YAGNI principle requires that a solution not be over-engineered in anticipation of future requirements.

If a solution meets the current sprint goals, functions as designed, and meets the team's "definition of done," then it is done. It's not half-done, sort of done, or "done pending a planned refactoring."

Mark it done and move on.

Minor Caveat

If you genuinely think there's another story there, or some sort of technical debt that doesn't prevent the original story from being done, then you should raise another story for the Product Backlog.

New work always needs to be placed on the Product Backlog to raise visibility--no invisible work, ever! Ultimately, it is the Product Owner's job to decide whether the proposed improvement aligns with the product goals, and to prioritize your new user story within the Product Backlog if he chooses to add the story.