问:
Difference between Pattern and Principle
What is the difference between Object Oriented Design Patterns and Principles? Are they different things? As far as I understood both of them try to achieve some common goal (e,g. flexibility). So can I say a pattern is a principle and vice versa?

Design Principle = SOLID (i.e. Dependency Inversion Principle)

Design Pattern = Gof (i.e. Abstract Factory Pattern)

答:
Patterns are more high-level things, than principles. Patterns resolve specific issues. Principles could be applied anywhere regardless of context. Actually patterns based on principles (SRP, DRY, etc)

E.G. Lets look on Strategy pattern. It defines a family of algorithms, encapsulates each one, and makes them interchangeable. So, you have here high-level concept of algorithm. With State pattern you have high-level concept of state. With principles you don't have any high-level concepts. Principles are building blocks, which used by patters to achieve goal. When you implement Strategy pattern, you use SOLID:

SRP - you define code, which responsible for algorithm and extract it from another code.

OCP - you define abstraction, which represents all different algorithms and use it

LSP - you don't use concrete algorithm classes in client code, only abstraction

OwnerDisplayName: Chandi Gorom

OwnerDisplayName: lazyberezovsky


答: Well, Principles are rules while patterns are their concrete examples.</p>

ContentLicense: CC BY-SA 3.0

Title: Difference between Pattern and Principle

Body:
What is the difference between Object Oriented Design Patterns and Principles? Are they different things? As far as I understood both of them try to achieve some common goal (e,g. flexibility). So can I say a pattern is a principle and vice versa?

Design Principle = SOLID (i.e. Dependency Inversion Principle)

Design Pattern = Gof (i.e. Abstract Factory Pattern)

OwnerDisplayName: Ahmad


答:
No, they aren't the same.

Patterns are common solutions to object-oriented programming problems.  (I'm not aware of any similar books for functional or declarative programming.)  The idea was crystallized in the famous "Design Patterns" book by the Gang of Four in 1995.

As Andre points out, patterns are common in every paradigm.  I'll reiterate my previous statement: I'm not aware of any similar books for functional or declarative programming, but Andre has remedied my ignorance with the link he provided below.  (Thank you, Andre.)

Principles are less about particular languages or paradigms, more general.  "Don't Repeat Yourself" - DRY principle - is true for all programming.

OwnerDisplayName: duffymo


问:
Why do websites restrict the number & choice of characters in a password?
Registering on an insurance company's website right now, and my password is 16 characters long, using a nice variety of letters, numbers, special characters, etc. However, here's their list of restrictions:

Note your password:

must be between 6 and 12 characters

must not contain spaces, special/international characters

must not contain your user name, first name or last name

is case-sensitive

should contain at least 1 number and 1 letter

I can understand minimum 6 characters, not allowing parts of your name, being case-sensitive, and needing at least 1 number and letter. The part I don't get is restricting your choice of characters you can use, and having an upper bound.

Why do websites do this? The only thing I can think of it they don't know the basics of hashing a password, which would secure it better than anything, and get rid of any security concerns.

If I choose to type DELETE FROM users WHERE 1=1 as my password, I should be allowed to. PHP's MD5 hash of it becomes fe5d54132b51b7d65ab89b739b600b4b which I don't think will harm anything.

答:
Banks restrict the special characters, probably because <s>they are storing the passwords in plain text, which they shouldn't be doing, and</s> they are afraid some special characters will leak into their business logic and hack it.

As to the limit of number of characters, I can only speculate that software on some of the mainframes they still use cannot handle text fields larger than that.

ContentLicense: CC BY-SA 2.5


答:
These concepts are not same :

*Design Principle : * Software design principles represent a set of guidelines that help us to avoid having a bad design. like: Open Close Principle

*Design Pattern : * a Design Pattern is a general reusable solution to a commonly occurring problem within a given context in software design. Like: Singleton

OwnerDisplayName: amicngh


问:
Why does DirectX use a left-handed coordinate system?
I considered posting on Stack Overflow, but the question strikes me as being far too subjective since I can't think of a reasonable technical explanation for Microsoft's choice in this matter. But this question has bugged me for so long and the issue keeps coming up in one of my projects, and I have never actually seen an attempt at explaining this:

OpenGL uses a right-handed coordinate system, where the +Z part of the world coordinate system extends toward the viewer.

DirectX uses a left-handed system where the +Z part of the world coordinate extends into the screen, away from the viewer.

I never used the Glide API, so I don't know how it worked, but from what I can gather, it uses a left-handed system as well.

Is there a technical reason for this? And if not, is there some conceptual advantage to a particular handedness of a coordinate system? Why would one choose one over the other?

答:
To all those who think there is no advantage to right- or left-handedness, you are absolutely wrong.  The right-handedness of Cartesian co-ordinate systems comes from the definition of the vector cross product.  For XYZ basis vectors u, v and w, w = u X v.

This definition is fundamental to vector mathematics, vector calculus and much of physics.  Suppose that you are trying to simulate electromagnetic interactions.  You have a magnetic field vector, M, and a charged particle moving in that field with velocity v.  Which way does the charge accelerate?  Easy - in the direction of M X v.  Except some idiot thought it'd be fun to make your display system left-handed, so it accelerates in the direction of -M X v.

Basically any physical interaction between two vector quantities is defined as right-handed, and so any time you need to simulate that interaction, you'd better hope your graphics system is right-handed or you will need to remember to cart around negative signs in all your math.


问:
Handling (many) multiple projects in Git in an enterprise environment
One of the advantages of older version control systems such as CVS and SVN in enterprise development is that anyone can connect to source control and see all the projects that the company has. This can make it easier to get a high level view of what kid of development is happening outside your sprint and also keeps everything in one place and easy to find.

However, distributed version control systems (Git, specifically) use the repository as their base unit. They work best with one project (or several closely related projects) per repository. This makes repository management more difficult in most enterprise environments where it is not unusual to have more than 25-50 projects to support. As far as I have been able to determine, you have to keep a list somewhere else of all the repos you have. There is software available, like GitHub, that help, but that still is an extra step beyond a single connection string and listing the contents of the repository.

What is the best way to deal with the complexity of multiple repositories?

答:
You should take a tool to manage your repositories as units. Besides gitosis and Gitolite, there's also excellent Gitlab, looking like github.

If you need several repos to build your software, Google, has depot_tools for that, it allows you to pull from different repositories. In simpler cases you can, probably, get by using git submodules. Having a code review in a single place is also a good thing, Facebook's Phabricator allows that.


问:
Writing selenium tests, should I just get it done or get it right?
I'm attempting to drive my user interface (heavy on javascript) through selenium.  I've already tested the rest of my ajax interaction with selenium successfully.  However, this one particular method seems to be eluding me because I can't seem to fake the correct click event.  I could solve this problem by simply waiting in the test for the user to click a point and then continuing with the test but this seems like a cop out.  But I'm really running out of time on my deadline to have this done and working.  Should I just get this done and move on or should I spend the extra (unknown) amount of time to fix this problem and be able to have my selenium tests 100% automated?</p>

答:
I've seen that "wait for the user to do something" technique done.  It's a bad idea, for a lot of different reasons, but it can be made to work in a limited context.  If you do it, obviously you don't have an automated test, but rather one that requires active human observation and interaction.  Which means you can't run it as part of a Continuous Integration process, you probably won't want to run it as part of an in-the-background unit-test collection, etc.

If you decide to do this anyway, the correct way to do it is to alert the user that their action is required, and to then wait (looping with pauses as necessary) for the correct result of their action.  As opposed to waiting for a few minutes and hoping they did their piece of the job.


答:
Patterns where originally documented for Architecture.  In architecture, apply to things ranging from placement of the door in a room to the layout of a village.

The Gang of Four applied the idea to Object-Oriented Programming.   There may be more than one pattern which can be used to solve a problem, but each pattern will have a specific implementation.  Patterns exist in other programming approaches, but I am not aware of any applicable books.   As others have mentioned Patterns cover specific implementations.  Using a pattern when it doesn't apply is often considered an anti-pattern.

Principles don't cover implementation, although there can be standard implementation approaches.  Principles are more about covering general issues rather than specific problems.  For Inversion of Control, I am aware of at least three implementation approaches.  For DRY (Don't Repeat Yourself) I don't know of a singe specific implementation approach, although I use several.

Consider

You have been requested to use a Pattern like Abstract Factory Pattern as the only approach to develop a program.  Would this be appropriate?  No, then it is more likely a Pattern.

You have been requested to apply DRY to all components?
Would this be appropriate?  Yes, then it is more likely to be a Principle.


答:
Patterns are to principles, what implementations are to patterns.

A principle would be "indirection", which could be accomplished by a "factory" pattern, which gets implemented as a class with factory methods in the end.


问:
How to properly document functionality in an agile project?
So recently, we've just finished the first phase of our project.

We used agile with fortnightly sprints. And whilst the application turned out well, we're now turning our eyes on some of the maintenance tasks.

One maintenance task is that all of our documentation appears in the form of specs. These specs describe 1 or more stories and generally are a body of work which a few devs could knock over in a week.

For development, that works really well - every two weeks, the devs get handed a spec and it's a nice discrete chunk of work that they can just do.

From a documentation point of view, this has become a mess. The problem with writing specs that are focused on delivering just-in-time requirements to developers is we haven't placed much emphasis on the big picture.

Specs come from all different angles - it could be describing a standard function, it could describing parts of a workflow, it could be describing a particular screen...

And now, we have business rules about our application scattered across 120 documents. Looking for any document for a particular business rule or function in particular is quite hard because you don't know which document has this information, and making a change request is equally hard because once again, we are unsure about which spec to make the change.

So we have maybe a couple of weeks of lull before it's back to specing out functionality for the next phase but in this time, I'd like to re-visit our processes. I think the way we have worked so far in terms of delivering fortnightly specs works well.

But we also need a way to manage our documentation so that our business rules for a given function / workflow are easy to locate / change.

I have two ideas.

One is we compile all of our specs into a series of master specs broken by a few broad functional areas. The specs describe the sprint, the master spec describe the system. The only problem I can see is
1) Our existing 120 specs are not all neatly defined into broad functional areas. Some will require breaking up, merging etc. which will take a lot of time.
2) We'll be writing specs and updating master specs in each new sprint. Seems like double the work, and then do the devs look at the spec or the master spec?

My other suggestion is to concede that our documentation is too big of a mess, and manage that mess going forward. So we go through each spec, assign like keywords to it, and then when we want to search for a function, we search for that keyword. Problems I can see
1) Still the problem of business rules scattered everywhere, keywords just make it easier to find it.

anyway, if anyone has any decent ideas or any experience to share about how best to manage documentation, would really appreciate it.

答: This is one of the major problems with "big-A-Agile" development: it's primarily focused on development.  If system documentation matters to your users (and it usually does), your technical writers and their work-product need to be part of the sprint.  In the "small-a-agile" community, we've come to understand that there is more to product than just code.  We've integrate testers and testing into sprints, including making sure the testers know enough about what is being coded that they can test inside the sprint.  We need to do the same with the technical writers, although I don't know anyone who's doing it yet.


问:
Backbone.js, Rails and code duplication
I'm building a web app and I need a JS framework like Backbone.js to work with my backend provided by Rails that mostly return JSON objects after DB queries.

Searching on the web I've discovered Backbone which seems to be complete, quite popular and actively used in development but I've noticed that a lot of things done by Backbone are simply a duplicate of the work done by Rails: for example, validation and models.

My idea of "perfect" (for my actual needs) JS mvc (it can't be called mvc but I don't have a better name) is something really simple that has a function for each action in my Rails controller that is triggered by a specific event (user/hash changes, click on a button...) and sends requests to the server that respond with a JSON object then I'll load a template or execute some JS code.

Do you have any concerns about/suggestions for my idea?

Do you know of some "micro" js framework like what I have described?

If you have worked with backone.js + rails what can you suggest to me?

答: You should always do validation on the server. Backbone validations are optional. they are there to improve usability of the app.</p>

Title: Backbone.js, Rails and code duplication


问:
What are the benefits of using geospatial datatypes?
We currently store points as three floats (lat,lon,alt) and support only one type of query (points within a given radius) but look forward to support more queries. We are using PHP and MySQL.

What are the benefits of using geospatial types?

答:
Take a look at this wikipedia article on spatial databases

http://en.wikipedia.org/wiki/Spatial_database

Especially the section "Features of spatial databases"

The types of queries presented there is what you can do with spatially enabled data. Spatially enabled data have extra "dimensions" by which they can be queried on that regular data cannot.


问:
A programmer should concentrate on at least how many languages?
For me I am C# and Java person. I find these 2 languages are quite similar so its easier for me to crossover each other. I'm not sure if its good idea to pick up other different languages. Any thoughts?</p>

答:
When it comes to keeping skills up to date, and flexible, I think you should try to learn at least one completely new programming language every 6 months or so. And I mean a language that is very, very different.

So while learning more of the .net framework while using C# or the Java frameworks helps in keeping limber, learning Haskell, Smalltalk, Scala, Clojure or Ruby will expand your technique and help you think in different ways, some of which you may take usefully back to your main language, and some of which may help you move on if Java ceases to be king of the hill.

If you've never learned C, then although it's syntax has been brought to Java, the mindset can be quite different. It is worth knowing it, in depth, and even better, understanding how OO code can be written in this language which seems only procedural.

I recommend reading Bruce Tate's book "Beyond Java", which highlights only too well the dangers of being only on one language, noting the rise and fall of C++. Although C++ is far from dead yet and has decades left, it is becoming restricted more and more to use only in situations that cannot benefit from productivity gains in other languages. To contrast, Sinatra, a ruby framework, allows you to build a simple web service in about 6/7 lines of code, the C++ equivalent may be an order of magnitude larger than this.


问:
Should a software developer get a yearly equipment budget?
I am looking at a new position with a new company.  I have talked to some people in the past (in general, not at this company) that they had been given a yearly budget to buy new computer stuff to keep up to date.

Now why I feel this question is worth asking here is that Joel comes right out and says an employer should pay for the best equipment money can buy... within reason of course.

From The Joel Test: 12 Steps to Better Code

9. Do you use the best tools money can buy?

Writing code in a compiled language is one of the last things that still can't be done instantly on a garden variety home computer...

Top notch development teams don't torture their programmers. Even minor frustrations caused by using underpowered tools add up, making programmers grumpy and unhappy. And a grumpy programmer is an unproductive programmer...

Does anyone know if the industry has such a standard to offer an allowance or budget?

I have never worked for a company like this, but I am thinking I should toss this in the ring for negotiations.  Seems reasonable.  How do bigger companies like MS, Google, and Apple handle this?  If you say yes, give a range... I have been told numbers from $5k to $10k.  Seems high to me, but hey I would gladly take it.

答:
When the company I work for started out it we had a $1500 personal hardware allowance. Employees could buy equipment for working at home and expense it. As the company was bought and sold we've lost this nice benefit.
Our current IT department will supply developers with top of the line equipment but it's from one of the big vendors (HP, Dell, Lenovo, etc). </p>


问:
User intentions analysis
I'm going to work on some project that would do a user-action recognition based on what he/she does in the system.

As far as I understand there are two main parts here:

Intercept the user actions (say http traffic in web/ui interaction in thick-client)
analysis of user intentions.

While the first part is rather technical and therefor easy to implement, the second one is AI related and can be academic.

So I was wondering whether someone knows some third-parties/academic projects that would implement the 'action-recognition' stuff?

答:
It sounds like the "action-recognition" term you are looking for is 'web analytics'.

This can be a custom framework that you design and implement yourself, or - if advanced graphing and charting capabilities are required in to report usage data, you might want to check out these frameworks:

Google Analytics

Omniture - Site Catalyst

Title: User intentions analysis


问:
What is the benefit of a visual editor over straight programming?
I'm trying to figure out what the benefit to having a WYSIWYG HTML editor over hard coding, outside of, say, accessibility.  It seems like a waste of time to learn how to use something like Dreamweaver over Notepad++.  Am I missing something here?  Every time I've ever used one, I end up going back into the code to fix the problems the visual editor made.</p>

答: WYSIWYG editors are not designed for the competent coder with plenty of time, as it were. They are designed to knock out prototypes or for designers who cannot code.</p>


答:
This is a changing space, every tool has its place in a professional's toolbox, it takes a true professional to know when each tool is appropriate to use.

That said, not all tools are made the same, Dreamweaver was cutting edge a decade ago, there are better tools today. Tools like Flux and even Coda are invaluable for rapidly developing high quality code and debugging tedious things like cross browser CSS things. Not to mention the time they save with auto-completetion of the CSS and HTML tags and attributes.

If you aren't using a tool that does syntax highlighting and autocompletion for Javascript you are wasting time as well.

Anyone still arguing that they are more effient with a plain text editor isn't any better than a mechanic that only has a single adjustable wrench and says "they don't have time" to master the appropriate tools because they are "too busy". They are "too busy" working in-efficiently and wasting time.

Title: What is the benefit of a visual editor over straight programming?

Body: I'm trying to figure out what the benefit to having a WYSIWYG HTML editor over hard coding, outside of, say, accessibility.  It seems like a waste of time to learn how to use something like Dreamweaver over Notepad++.  Am I missing something here?  Every time I've ever used one, I end up going back into the code to fix the problems the visual editor made.</p>


答:
I've always used WYSIWYGs for the extraneous tools rather than the coding tools. My preference was always Dreamweaver because it came with built-in ftp. It has a whole bunch of snippet add-ons and extra junk, but the 3 things that made it the most powerful for me was line numbers (which I think Notepad++ has), integrated ftp/site definition settings, and multiple line/multiple file find and replace.

I actually had more problems when I inherited a site that was built with Dreamweaver using all of the built-in snippets than I've ever had with sites that don't use them.

As for the visual editor, the only time I ever use that is when my code is exhibiting a weird rendering behavior because of something I did. Sometimes the visual editor will help pinpoint the problem. But once the problem is pinpointed, back to the code I go.


答: I sometimes use WYSIWYG editor for my internal or personal webpages when I've been melting my brains on a production site and am so over seeing < and >. WYSIWYG or OOWriter means it gets done at all versus "F that, I'm going home to drink beer"...


问:
Is there a difference between "self-plagiarizing" in programming vs doing so as a writer?
I read this Gawker article about how a writer reused some of his older material for new assignments for different magazines.

Is there any similar ethical (societal?) dilemma when doing the same thing in the realm of Programming?  Does reusing a shared library you've accumulated over the years amount to self-plagarizm?

What I'm getting at is that it seems that the creative world of software development isn't as stringent regarding self-plagarism as say journalism or blogging.  In fact on one of my interviews at GS I was asked what kind of libraries I've developed over the years, implying that me getting the job would entail co-licensing helpful portions of code to that company.

Are there any cases where although it's legal to self-plagarize,  it would be frowned upon in the software world?

答:
The issue isn't who wrote the code, but who owns the code. If you were paid to write some code for one employer and then re-used that same code (without permission) on a job for someone else, that's a problem unless you somehow retained the rights to the code. In the US, at least, that's not how it usually works -- the guy who paid you to write the code owns it.

The main difference I see between writers and programmers in this regard is that if an author writes new material that expresses essentially the same ideas, the right thing to do is to at least credit the first version with a line like: As I wrote previously in The Popperville Gazette.... It'd be unusual to do that in code, though... as long as the previous work isn't patented (as opposed to copyrighted), you should be able to re-implement the idea in new code without necessarily needing to credit the first work.


问:
"Forgot Password" - How to handle this?
I read this answer and found a comment insisting not to send password by email:

passwords should not be able to be retrieved by email, I hate that. It means my password is stored in plain text somewhere. it should be reset only.

This raises me the question of handling Forgot Password option?

At any cost the raw password must be displayed in any UI so that user will be able to read it. So what would be the way to handle "Forgot Password"

答:
You should not store the users main password as plaintext, but you CAN store a temporary password as plaintext, i.e

user resets password -> temp password is created -> temp password is sent via email -> user is forced to change password at next log in (new password can't be temp password maybe)

Title: "Forgot Password" - How to handle this?


问:
Should I pay my developers for bugs fixes for a project or work that's still in progress?
We are working with a group of developers on a project. The project is still in progress (not completed) and these developers charge us for time spent on fixing bugs on codes that were not written valid in the first place. I understand that we should pay for changes/new requests if any, but not bugs fixes for a work in progress. We also understand that once the assignment is being deployed to the live site, we may be liable for bugs fixes that may arise after a support period is being exhausted.

The question now is, is it appropriate for such charges to be levied upon us while the project is still in progress?

答:
(I am not a lawyer)

It depends - what do you have written in a contract with them? If they are salaried employees you are responsible for paying them no matter what.


答:
What are the terms of your contract?  Did you specify having a user acceptance test phase?  Did you make the payments contingent upon clearing UAT?

Have the modules / units / whatever been accepted by your organization?  Note that there is a difference between received and accepted.  Received means you have received the code and it is entering user acceptance test.  Accepted means it has passed the UAT.

If the bug is found after UAT, you are generally bound to pay for the fix.  If it's found during UAT then you haven't received working code yet, so the payment milestone hasn't been met.

If you didn't put any sort of acceptance provisions within the contract, then you're likely bound to be paying to fix the bugs.

I'm editorializing here - if you're in a condition where you don't have a means to enforce receiving code that works as expected, then ditch the contract now.  The outside firm is only bound to deliver what is in the terms of the contract.  If the contract doesn't specify what "functional" is, then you're pretty much at their mercy for what is delivered for final content.

Additional edit #1:
If you're in a "Time and Materials" contract for the development work, then there is no functional difference between paying for them to code new function or paying them to fix bugs in the new functions.  Think of it this way: Just because they gave you a preview of a function doesn't mean that the function was actually delivered.  So while you may have found flaws within the function preview, that just means they're not complete with developing it yet.  What you see as bug fixes is really their continued refinement of the function.

Additional edit #2:
I would encourage checking to see if you formally moved from the fixed price contract to the project-log / by-the-hour (aka T&M) approach.  In general, I have never advised any of my clients to accept a T&M contract when it comes to new development.  There are simply too many variables in play to make a T&M contract an acceptable risk.

In a fixed price world, they are bound to fix any and all issues that prevent delivering the function specified by the contract.  So bug fixes would be on their dime, not yours.

In a T&M world, there is no such thing as a bug fix.  It's just additional enhancement of the code that has been generated at that point in time.

(Editorial #2) If things are bad, don't be afraid to ditch a bad contract.  Pay the escape penalty and be done with it.  It's very easy to get into a situation where good money is thrown after bad.  Stop the bad development process; re-work the RFP and specify what is actually required; ink a new contract.  It's the best way to make sure you'll get what you actually need and will save a lot of headache in working through a bad contract.

Title: Should I pay my developers for bugs fixes for a project or work that's still in progress?

Body:
We are working with a group of developers on a project. The project is still in progress (not completed) and these developers charge us for time spent on fixing bugs on codes that were not written valid in the first place. I understand that we should pay for changes/new requests if any, but not bugs fixes for a work in progress. We also understand that once the assignment is being deployed to the live site, we may be liable for bugs fixes that may arise after a support period is being exhausted.

The question now is, is it appropriate for such charges to be levied upon us while the project is still in progress?


答: Defects are an expected result of the software development process.  For a time and materials contract, I would expect that the developers charge you for the time they spend fixing bugs.  This is a normal part of a developer's job.  For a fixed bid contract, I would expect that the developers eat the cost of the defects and deliver the system bug free (or as close to it as the contract states) for that fixed cost.  For a situation where you are employing them more directly as contractors or as employees, then it would fall under the same time and materials reasoning: it is a part of the job so they should be paid for it.</p>


答: It might depend on the nature of the bugs. If the bugs are impeding their work on other features (for example, if Screen 1 fails to render due to an old bug, how can they add 2 new buttons to it?), then it might be cheaper to have them fix the bug and do their new work properly rather than code around the bug. In the future, you're probably better off defining this kind of situaiton more clearly in the initial contract.


答:
The spatial datatypes are in return for only supporting one type of query, much much faster at that type of query. Consider importing something like the MaxMind Cities database and finding the city closest to you. With regular float datatypes, that query would need to check all 2.7 million records against eachother to find the closest one (calculate haversine distance of every point to every other point). The Geospatial types on the other hand can be queried for the closest point and will be orders of magnitude faster by using something like quad-trees for the internal representation of the index.

You can do some logic to make querying with regular keys faster, described in this presentation among others. But this is no longer necessary since geospatial indexes are much better at this task.

Title: What are the benefits of using geospatial datatypes?

Body:
We currently store points as three floats (lat,lon,alt) and support only one type of query (points within a given radius) but look forward to support more queries. We are using PHP and MySQL.

What are the benefits of using geospatial types?


问:
Dynamically vs Statically typed languages studies
Do there exist studies done on the effectiveness of statically vs dynamically typed languages?

In particular:

Measurements of programmer productivity

Defect Rate

Also including the effects of whether or not unit testing is employed.

I've seen lots of discussion of the merits of either side but I'm wondering whether anyone has done a study on it.

答:
Here are a few:

Stefan Hanenberg. 2010. An experiment about static and dynamic type systems: doubts about the positive impact of static type systems on development time. In Proceedings of the ACM international conference on Object oriented programming systems languages and applications (OOPSLA '10). ACM, New York, NY, USA, 22-35. DOI=10.1145/1869459.1869462 http://doi.acm.org/10.1145/1869459.1869462

Daniel P. Delorey, Charles D. Knutson, Scott Chun, "Do Programming Languages Affect Productivity? A Case Study Using Data from Open Source Projects," floss, pp.8, First International Workshop on Emerging Trends in FLOSS Research and Development (FLOSS'07: ICSE Workshops 2007), 2007

Daly, M.; Sazawal, V., Foster, J.: Work in Progress: an Empirical Study of Static Typing in Ruby, Workshop on Evaluation and Usability of Programming Languages and Tools (PLATEAU) at ON-WARD 2009.

Lutz Prechelt and Walter F. Tichy. 1998. A Controlled Experiment to Assess the Benefits of Procedure Argument Type Checking. IEEE Trans. Softw. Eng. 24, 4 (April 1998), 302-312. DOI=10.1109/32.677186 http://dx.doi.org/10.1109/32.677186

ContentLicense: CC BY-SA 4.0


答:
I would say either the specs weren't clearly defined, or they blew their estimates (which you shouldnt have to pay for).

When seeking an estimate you need to clearly define what the functionality to be delivered is, and provide them (the dev shop) some clear definition of how the product should work and how it will be tested to verify that it works. Their job is to accurately estimate and deliver.

If the product doesn't work as expected (it doesn't pass the tests that you provided i.e. A user enters their username and password, clicks login and they are redirected to their homepage), that's not your fault.

However,  if you havent defined what should happen if they enter the wrong uname / pword, and the page throws an error, that MIGHT be room to say "Well, you didnt say we had to validate the username and password" so make sure to write down what you expect each "test scenario" to result in..

clearly define what you want

clearly define how you will verify that it works the way you want

upon delivery use the agreed upon test to validate it works as intended

not providing enough information up front will end up costing you..


答:
There is no way you can assume the programmers to write perfect code:

Fixing bugs in normal software project takes at least 1/3 of all the time used. In maintainance phase, more than 1/3.

Even after spending large amounts of time and money fixing bugs, nasa still lost space shuttles because of software problems. I think you will run out of money long before you get to the same quality.

Outsourcing the responsibility to fix bugs to outside vendors is definitely a good way to make your project fail.


答:
Should a software developer get a yearly equipment budget?

Definitely a nice to have and something I would bring up for discussion or even as part of your bargaining chips for salary negotiation. The question is more about whether it's a "should" or a "must".

Does anyone know if the industry has such a standard to offer an allowance or budget?

Unfortunately the industry definitely doesn't have it as a standard practice, but thankfully some companies are a bit less greedy and more in touch with their developers' (and employees' at large) needs.

This is going to be a rather broad answer, and by budget I don't make a distinction between a budget given to you to buy or place an order, or as something transparent where you request an upgrade managed by your company's staff. In their books, it's all the same thing anyways.

It's Handy

The problem is that this can obviously quickly represent a huge budget for a company, if it reaches a certain critical mass. However, I'd agree with you and Joel that it can be well worth it.

There's absolutely no point in frustrating employees.

Don't Get Spoiled

That being said, you also need to keep employees in line and make them realize that sometimes bad performance or slightly out-dated hardware is just a fact of life. You don't want everybody to turn into spoiled kids who want a new SSD, the latest iN processor, the extra GB of ram, etc...

I don't want people to obsess over eternal youth, and that applies to hardware as well.

(With software projects, however, I tend to push for staying as close to the latest release as possible... Analogies don't always hold :))

Specific Needs for Specific Hardware

I think there's a distinction to be made between:

the basic equipment that is definitely required for your job when you start,

and the more advanced equipment where the need stems from specific requirements.

Base Package

For instance, the following are pretty standard things you'd be entitled to expect, and for which I don't see a (strong) need for special orders:

a laptop + cellphone (if you are an on-site consultant),

a workstation if you work off-site and stay at the mothership,

plus maybe a few non-controversial goodies like:

decent input devices (keyboard, mouse, maybe trackballs...)

decent chair.

These can be the same for the whole company, except for special cases like employees with disabilities. Employees with disabilities or injuries should obviously be accommodated.

Bonuses

Then if obviously you'll need to do lots of videoconferencing and presentations, you might want a few gadgets like bluetooth thingies, tablets and styluses. Which can actually be shared across departments by using a reservation system, to not end up with everybody requesting some (and losing them), while cutting down on the room for whining.

If you are a designer, you'll need your drawing tablet, your trackball, etc... I do every once in a while see the one developer who begs for a trackball instead of a mouse. Personally I've tried both, and I see both as almost equally identical, so I never really bought into this claim, if you don't have a specific need for it other than "I like it better". You can live with a mouse instead of a trackball without developing an RSI within 8 hours if you don't already have issues and have correct usage habits. It's a different issue when you get a crappy mouse or trackball or keyboard, but I don't see a clear win for one or the other.

If you are a developer needing to run 4 application servers simultaneously, building projects, and keeping 3 instances of Eclipse or Visual Studio open at all times, you'll obviously need a rather competitive workstation. I'd consider this "basic needs" for developers, so it doesn't mean the marketing dudes necessarily need to be aligned on that.

Build Your Case: Hard-Data For the Win

From experience, most companies are understanding with regard to your needs if you can prove that they are legitimate. If you can defend the rationale for it, they'll cough up the money or try to accommodate you. They're paying you to work, so they really don't want you to be wasting time.

(That is, if they care one bit about your job... if you're irrelevant, I'm afraid you're out of luck there...)

Show the Gain for You

So, in the past, my coworkers and I did get upgrades for RAM, input devices, chairs, hard-drives and whole workstations or even server farms based on clearly collected and outlined requirements. It does take a bit of your time to build your case, so discuss it first with your line manager, but it will probably be fine. Or spend the extra hours one week at the office to build the case, it can be worth it and your line manager will trust you more with such decisions in the future.

Show the Gain for Them (Money is the root of all evil...)

With regard to the above example, we did for instance calculate build-times and the reduction we could get, and did comparisons between the different setups present at the company, calculating the average of wasted time per developer per day, and then making them realize that it was equivalent over a year to about 20 full days per person of being unable to do anything (as the computer would basically be unresponsive if you didn't have a least a quad-core and 8GB of RAM for this build). Times the number of developers, that's a hefty amount of hours they pay people to stick around doing nothing, which was way higher than upgrading at least some of the stations.

More recently, a co-worker has been doing a similar evaluation to persuade them to consider SSD drives, and is in the process of collecting really fine-grained data on how much time would be saved for every body, in a similar fashion.

For health-related queries, a simple recommendation from your doctor, even informal, might be enough.

For custom software, you may just need to present the advantages of the tool and its impacts when integrated into your process. For instance, I managed to get my last 3 companies to purchase licenses for wireframing tools after using a demo version for a presentation to grab their interest, and then using them more extensively in one or two short-lived projects involving a few people. These were rather cheap, but originally they didn't want to buy the licenses without seeing the need. When they realized it clearly helped to visualize prototypes and make educated decisions earlier, they gave the green light quickly.

Plan

Define an upgrade plan.

Define benchmarks and metrics to use for measuring the gain.

Provide clear results.

Draw conclusions on these results.

Maybe do some initial legwork on cost- and savings-calculations (discuss with line manager as well, or do this in a second review of your proposal).

Get coworkers to sign off on your request, possibly with each writing a statement about how they feel about the update, be it positive or negative (the point is not to make a completely biased marketing speech to extort something from your company, it's also to really research this and see if it's really needed).

A Quick Note on Large Upgrades for a Whole Team

Suggest rolling releases if you request upgrades for a whole team:

it distributes the cost over a longer period,

it gives time to iron out transitional issues ("whoops, just realizing that this CPU combined with this OS version actually presents issues when cross-compiling our product X for other platform X"),

it prevents the whole team from being stuck in IT maintenance hell with system reinstallation, system updates and the usual clean slate issues, or the occasional mishaps’ ("whoops, deleted that important backup...").

Admit Defeat: It Doesn’t Always Work For Everything...

And rightly so. Not everything is acceptable. And things that are acceptable may be out of reach for your company. Build your case, bring it to the line manager, discuss it over a team lunch or something more friendly and team-spirited than in the heat of this year's financial review.

Also, if you have a hard time building your case:

admit you probably don't need it,

admit you probably were wrong and upgrade X doesn't buy you what you thought it would.

If you can't build a case and start being defensive about your request, it means you'd be better off doing something else.

Body:
I am looking at a new position with a new company.  I have talked to some people in the past (in general, not at this company) that they had been given a yearly budget to buy new computer stuff to keep up to date.

Now why I feel this question is worth asking here is that Joel comes right out and says an employer should pay for the best equipment money can buy... within reason of course.

From The Joel Test: 12 Steps to Better Code

9. Do you use the best tools money can buy?

Writing code in a compiled language is one of the last things that still can't be done instantly on a garden variety home computer...

Top notch development teams don't torture their programmers. Even minor frustrations caused by using underpowered tools add up, making programmers grumpy and unhappy. And a grumpy programmer is an unproductive programmer...

Does anyone know if the industry has such a standard to offer an allowance or budget?

I have never worked for a company like this, but I am thinking I should toss this in the ring for negotiations.  Seems reasonable.  How do bigger companies like MS, Google, and Apple handle this?  If you say yes, give a range... I have been told numbers from $5k to $10k.  Seems high to me, but hey I would gladly take it.


答:
A good application design will not be able to explicitly recover a users password.  This is because it is usually stored after it is run through some sort of hash which is a one way operation.

The best way to handle lost password is to perform a reset, email to the users account a link with a generated parameter tacked on that identifies this as a valid password reset for the account in question.  At this point they can set a new password.

This does assume you have a users email address on file.

Title: "Forgot Password" - How to handle this?

Body:
I read this answer and found a comment insisting not to send password by email:

passwords should not be able to be retrieved by email, I hate that. It means my password is stored in plain text somewhere. it should be reset only.

This raises me the question of handling Forgot Password option?

At any cost the raw password must be displayed in any UI so that user will be able to read it. So what would be the way to handle "Forgot Password"


问:
Is it bad practice for a module to contain more information than it needs?
I just wanted to ask for your opinion on a situation that occurs sometimes and which I don't know what would be the most elegant way to solve it.

Here it goes:

We have module A which reads an entry from a database and sends a request to module B containing ONLY the information from the entry module B would need to accomplish it's job (to keep modularity I just give it the information it needs -> module B has nothing to do with the rest of the information from the read DB entry). Now after finishing it's job, module B has to reply to a module C if it succeeded or failed. To do this module B replies with the information it has gotten from module A and some variable meaning success or fail. Now here comes the problem: module C needs to find that entry again BUT the information it has gotten from module B is not enough to uniquely find the exact same entry again.

I don't think that module A giving more information to module B which it doesn't need to do it's job but which it could then give back to module C would be a good practice because this would mean giving some module information it doesn't really need.

What do you think?

答:
Getting information from one part of a program to another is a constant battle and there is pretty much never a perfect solution.

I can see four possible solutions in a situation like this:

Just go ahead and include the information that C needs in the call to B

A calls C with all of the information and C calls B with just the information that B needs

Put all of the information into a neutral object that both B and C can access and let each of them get what they need

A calls B with just the information that B needs, B returns pass/fail, A calls C with information C needs (introduces dependency of A on C but removed dependency of B on C)

The "best" solution will depend on the circumstances that actually exist in any given situation.

OwnerDisplayName: gekod


问:
Securing Back End API for Mobile Applications
I have an application that I am writing for both iOS and Android; this application will be served by a ReSTFUL API running on a cluster of servers on "the internets". I am curious how the rest of the world is going about securing their APIs so only specific applications running on iOS or Android can use these APIs.

I could go the same route as other OAuth providers by providing a key/secret combination (2-legged OAuth), however, what do I do if I ever have to change these keys??? Do I create a new key/secret for every person that downloads the app???

The application is a social-based game that will allow the user to interact with other "participants" in the game based on location, achievements, etc.

The API will provide the following functions:

-Questions, Quests, etc
-Profile Management
-User Interaction
-Possible Social Interaction

Once the app gains traction I plan on opening up the API ala Facebook, Twitter, etc. Which is easy enough, I plan on implementing an OAuth Server and whatnot. However, I want to make sure, during this phase, that only people who are using the application can access and use the API.

答: There is no way you can be sure that the application at the far end of the wire is the one you think it is.  You can't prevent someone reverse-engineering the communications and API and running their own app.   You can (of course) make it difficult, for example by encrypting the traffic, and by making the protocols difficult to emulate even if decrypted.</p>


问:
Why are effect-less functions executed?
All the languages I know of would execute something like:

```<code>i = 0
while i < 100000000
    i += 1
</code>```

..and you can see it take a noticeable amount of time to execute.

Why though, do languages do this? The only effect this code will have is taking time.

edit: I mean inside a function which is called

```<code>function main(){
    useless()
}
function useless(){
    i = 0
    while i < 100000000
        i += 1
}
</code>```

答: Get a better implementation. Many C++ compilers I know would remove much more complex code with no side effects than this.</p>

Title: Why are effect-less functions executed?


问:
Reporting in Visual Studio 2010 Express
I want to download Visual Studio 2010 Express Edition to learn all that is new in it. I find it insufficient as there is no Crystal Reports integration in it. Apart from that I want to learn other enterprise features that are bundled with the Professional Edition.

If I download the VS 2010 Professional Edition, it is just limited to 90 days. Is there any other alternative for learners?

Also, is there any FREE alternative for reporting in Express Edition.

答: I'd like to point out also that Crystal Reports tools aren't integrated anymore in VS since version 2008. They have been replaced by MS Reports, and I found them more powerful and easy to use than CR. VS does anyway support the CR format for legacy projects, it just doesn't provide you the templates to create them.</p>

Title: Reporting in Visual Studio 2010 Express


答:
There's 2 things to mention here. The first is that, many compilers as DeadMG said might optimize out code like this. As you probably know, if the point of the code was to take time, then this is inaccurate and dependent on the frequency of the processor.

The second thing to point out is your mentioning of "effect-less". It might not be what you mean, but many devs (especially those who are fans of functional programming, and its associated paradigms) advocate that you should avoid side-effects almost entirely - that is to say, have no external state. Generally speaking, programming in this way requires that you return some value from every function, thus it doesn't apply to the trivial example that you posted - but does to less-trivial examples.

Title: Why are effect-less functions executed?

Body:
All the languages I know of would execute something like:

```<code>i = 0
while i < 100000000
    i += 1
</code>```

..and you can see it take a noticeable amount of time to execute.

Why though, do languages do this? The only effect this code will have is taking time.

edit: I mean inside a function which is called

```<code>function main(){
    useless()
}
function useless(){
    i = 0
    while i < 100000000
        i += 1
}
</code>```


答: As @BillMichell suggests in his comment, the point is to consume time, assumably to allow something else to happen.  Most modern languages have a better way to do this--telling the thread or process to sleep or wait for a specified period of time.  In the bad old days, that wasn't an option.

Title: Why are effect-less functions executed?


答:
I agree with Larry OBrien than the best solution is probably to have A call B, then when B returns, A calls C.

If you really can't do that, I'd consider having A pass an opaque handle to B, which B then passes to C. C can then pass that back to A to get access to the information it needs.

In a typical implementation, A would cache the information, and the handle would really be something like a hash value or an index into a table. Assuming the data is no longer needed after being passed to C, A would also flush the data from the cache after passing it to C in response to being accessed via the handle.

Title: Is it bad practice for a module to contain more information than it needs?

Body:
I just wanted to ask for your opinion on a situation that occurs sometimes and which I don't know what would be the most elegant way to solve it.

Here it goes:

We have module A which reads an entry from a database and sends a request to module B containing ONLY the information from the entry module B would need to accomplish it's job (to keep modularity I just give it the information it needs -> module B has nothing to do with the rest of the information from the read DB entry). Now after finishing it's job, module B has to reply to a module C if it succeeded or failed. To do this module B replies with the information it has gotten from module A and some variable meaning success or fail. Now here comes the problem: module C needs to find that entry again BUT the information it has gotten from module B is not enough to uniquely find the exact same entry again.

I don't think that module A giving more information to module B which it doesn't need to do it's job but which it could then give back to module C would be a good practice because this would mean giving some module information it doesn't really need.

What do you think?


答:
In general, its hard (that is, undecidable) to prove if something is a silly busy loop (that could be optimized out) or an infinite loop (that cannot be optimized out withuot changing the meaning of the program). Does the following code loop forever or does it stop?

```<code>var n = //some positive integer
while(n != 1){
   if(n % 2 == 0)
      n = n/2;
   else
      n = 3*n+1
}
</code>```

Because of this complexity, most programming languages give up on trying to reason too much about the program and therefore pass the responsibility of not running silly busy loops back to the programmer.

Title: Why are effect-less functions executed?

Body:
In general, its hard (that is, undecidable) to prove if something is a silly busy loop (that could be optimized out) or an infinite loop (that cannot be optimized out withuot changing the meaning of the program). Does the following code loop forever or does it stop?

var n = //some positive integer
while(n != 1){
   if(n % 2 == 0)
      n = n/2;
   else
      n = 3*n+1
}

Because of this complexity, most programming languages give up on trying to reason too much about the program and therefore pass the responsibility of not running silly busy loops back to the programmer.


问:
Using a parser to locate faulty code
Lately I've been working a lot in PHP and have run into an abnormally large number of parsing errors.  I realize these are my own fault and a result of sloppy initial coding on my part, but it's getting to the point that I'm spending more time resolving tags than developing.  In the interest of not slamming my productivity, are there any tricks to locating the problem in the code?

What I'd really be looking for would be a line to put in the code which would output the entire faulty tag in the parsing error, or something similar.

Purely for reference sake, my current error is Parse error: syntax error, unexpected '}' in /home/content/80/9480880/html/cache/tpl_prosilver_viewtopic_body.html.php on line 50

(which refers to this):

```<code></dd><dd><?php if ($_poll_option_val['POLL_OPTION_RESULT'] == 0) {  echo ((isset($this->_rootref['L_NO_VOTES'])) ? $this->_rootref['L_NO_VOTES'] : ((isset($user->lang['NO_VOTES'])) ? $user->lang['NO_VOTES'] : '{ NO_VOTES }')); } else { echo $_poll_option_val['POLL_OPTION_PERCENT']; } ?></dd> </dl> <?php }} if ($this->_rootref['S_DISPLAY_RESULTS']) {  ?> <dl> <dt> </dt> <dd class="resultbar"><?php echo ((isset($this->_rootref['L_TOTAL_VOTES'])) ? $this->_rootref['L_TOTAL_VOTES'] : ((isset($user->lang['TOTAL_VOTES'])) ? $user->lang['TOTAL_VOTES'] : '{ TOTAL_VOTES }')); ?> : <?php echo (isset($this->_rootref['TOTAL_VOTES'])) ? $this->_rootref['TOTAL_VOTES'] : ''; ?></dd> </dl> <?php } if ($this->_rootref['S_CAN_VOTE']) {  ?> <dl style="border-top: none;"> <dt> </dt> <dd class="resultbar"><input type="submit" name="update" value="<?php echo ((isset($this->_rootref['L_SUBMIT_VOTE'])) ? $this->_rootref['L_SUBMIT_VOTE'] : ((isset($user->lang['SUBMIT_VOTE'])) ? $user->lang['SUBMIT_VOTE'] : '{ SUBMIT_VOTE }')); ?>" class="button1" /></dd> </dl> <?php } if (! $this->_rootref['S_DISPLAY_RESULTS']) {  ?> <dl style="border-top: none;"> <dt> </dt> <dd class="resultbar">_rootref['U_VIEW_RESULTS'])) ? $this->_rootref['U_VIEW_RESULTS'] : ''; ?>"><?php echo ((isset($this->_rootref['L_VIEW_RESULTS'])) ? $this->_rootref['L_VIEW_RESULTS'] : ((isset($user->lang['VIEW_RESULTS'])) ? $user->lang['VIEW_RESULTS'] : '{ VIEW_RESULTS }')); ?></dd> </dl> <?php } ?> </fieldset></div>
</code>```

答:
This example is screaming to be refactored into a function. Maybe two or more.

Once you've created a function, and put it in an included PHP file, you can test it in (relative) isolation. Perhaps by creating a page that calls that function and does nothing else, and passing that page to an HTML verifier (I'm assuming your problem is HTML parsing, because otherwise the PHP engine would be telling you where the problem is).

Plus, with a function you can insert comments that explain exactly where the content is being generated (although remove them for production use).

Title: Using a parser to locate faulty code

Body:
Lately I've been working a lot in PHP and have run into an abnormally large number of parsing errors.  I realize these are my own fault and a result of sloppy initial coding on my part, but it's getting to the point that I'm spending more time resolving tags than developing.  In the interest of not slamming my productivity, are there any tricks to locating the problem in the code?

What I'd really be looking for would be a line to put in the code which would output the entire faulty tag in the parsing error, or something similar.

Purely for reference sake, my current error is Parse error: syntax error, unexpected '}' in /home/content/80/9480880/html/cache/tpl_prosilver_viewtopic_body.html.php on line 50

(which refers to this):

```<code></dd><dd><?php if ($_poll_option_val['POLL_OPTION_RESULT'] == 0) {  echo ((isset($this->_rootref['L_NO_VOTES'])) ? $this->_rootref['L_NO_VOTES'] : ((isset($user->lang['NO_VOTES'])) ? $user->lang['NO_VOTES'] : '{ NO_VOTES }')); } else { echo $_poll_option_val['POLL_OPTION_PERCENT']; } ?></dd> </dl> <?php }} if ($this->_rootref['S_DISPLAY_RESULTS']) {  ?> <dl> <dt> </dt> <dd class="resultbar"><?php echo ((isset($this->_rootref['L_TOTAL_VOTES'])) ? $this->_rootref['L_TOTAL_VOTES'] : ((isset($user->lang['TOTAL_VOTES'])) ? $user->lang['TOTAL_VOTES'] : '{ TOTAL_VOTES }')); ?> : <?php echo (isset($this->_rootref['TOTAL_VOTES'])) ? $this->_rootref['TOTAL_VOTES'] : ''; ?></dd> </dl> <?php } if ($this->_rootref['S_CAN_VOTE']) {  ?> <dl style="border-top: none;"> <dt> </dt> <dd class="resultbar"><input type="submit" name="update" value="<?php echo ((isset($this->_rootref['L_SUBMIT_VOTE'])) ? $this->_rootref['L_SUBMIT_VOTE'] : ((isset($user->lang['SUBMIT_VOTE'])) ? $user->lang['SUBMIT_VOTE'] : '{ SUBMIT_VOTE }')); ?>" class="button1" /></dd> </dl> <?php } if (! $this->_rootref['S_DISPLAY_RESULTS']) {  ?> <dl style="border-top: none;"> <dt> </dt> <dd class="resultbar"><a href="<?php echo (isset($this->_rootref['U_VIEW_RESULTS'])) ? $this->_rootref['U_VIEW_RESULTS'] : ''; ?>"><?php echo ((isset($this->_rootref['L_VIEW_RESULTS'])) ? $this->_rootref['L_VIEW_RESULTS'] : ((isset($user->lang['VIEW_RESULTS'])) ? $user->lang['VIEW_RESULTS'] : '{ VIEW_RESULTS }')); ?></a></dd> </dl> <?php } ?> </fieldset></div>
</code>```


答:
In no particular order (well, maybe in order order of relevance, sort of):

format your code;

create code generators, so you don't mangle PHP and HTML code. It's a basic principle: separation of concerns for view/UI and business/logic code;

use automated code checkers;

write at least a few basic unit or integration tests that will detect the "blank page because of parse error" scenarios;

use a decent IDE, that will give you instant feedback on parse errors (if you separate UI and logic code...);

have shorter code-to-test lifecycles so you catch these early.

Title: Using a parser to locate faulty code


问:
When decomposing a large function, how can I avoid the complexity from the extra subfunctions?
Say I have a large function like the following:

```<code>function do_lots_of_stuff(){

    { //subpart 1
      ...
    }

    ...

    { //subpart N
      ...
    }
}
</code>```

a common pattern is to decompose it into subfunctions

```<code>function do_lots_of_stuff(){
    subpart_1(...)
    subpart_2(...)
    ...
    subpart_N(...)
}
</code>```

I usually find that decomposition has two main advantages:

The decomposed function becomes much smaller. This can help people read it without getting lost in the details.

Parameters have to be explicitly passed to the underlying subfunctions, instead of being implicitly available by just being in scope. This can help readability and modularity in some situations.

However, I also find that decomposition has some disadvantages:

There are no guarantees that the subfunctions "belong" to do_lots_of_stuff so there is nothing stopping someone from accidentally calling them from a wrong place.

A module's complexity grows quadratically with the number of functions we add to it. (There are more possible ways for things to call each other)

Therefore:

Are there useful convention or coding styles that help me balance the pros and cons of function decomposition or should I just use an editor with code folding and call it a day?

EDIT: This problem also applies to functional code (although in a less pressing manner). For example, in a functional setting we would have the subparts be returning values that are combined in the end and the decomposition problem of having lots of subfunctions being able to use each other is still present.

We can't always assume that the problem domain will be able to be modeled on just some small simple types with just a few highly orthogonal functions. There will always be complicated algorithms or long lists of business rules that we still want to correctly be able to deal with.

```<code>function do_lots_of_stuff(){
   p1 = subpart_1()
   p2 = subpart_2()
   pN = subpart_N()
   return assembleStuff(p1, p2, ..., pN)
}
</code>```

答:
I would suggest moving to a more functional programming style. The fact that you are talking about "calling in the wrong order" and showing functions that don't return data, this means that you are working with very impure functions.

The better approach is to work with pure functions:

1) Reject global state variables. They are bad. Enough said.

2) Every function should take arguments and return something.

3) Given the same arguments functions should output the same data.

When you follow these goals you will find that your code becomes much cleaner, functions can call other functions without fear of side-effects because functions are not allowed to mess with global state.

Now, in a web/gui app, you will have to modify global state at some point, in that case you can break the above rules in small fringe cases.

At this point, decomposing functions is extremely simple. You simply start taking logical parts in the code and breaking them into functions. When you find duplicated code, merge the functions into a single function. If you find yourself writing the same code over and over, then find a way to write that as a single function.

For instance, in a pseudo language, a for loop could be re-written as a map. So instead of this:

```<code>arr = [1, 2, 3, 4, 5]

for (x = 0; x < arr.length; x ++)
{
   arr[x] += 1
}
</code>```

You could write a map function once:

```<code>function map(func, arr)
{
   out = []
   for (x = 0; x < arr.length; x ++)
   {
     out.add(func(arr[x]))
   }
   return out;
}
</code>```

And in the future, instead of a for loop, you simply write:

```<code>function inc (x) { return x + 1; }

map(inc, [1 2 3 4])
</code>```

So instead of a single-use-case imperative for-loop. Now you have 2 functions that you can reuse in thousands of places in your program.

Resources:

http://skilldrick.co.uk/2011/07/easy-functional-programming-in-javascript-with-underscore-js-part-1/

http://www.ibm.com/developerworks/library/wa-javascript/index.html

EDIT:

Update to address the OP's edits:

In your example, I suggest using maps in a situation like this. So in your example:

```<code>function foo(arg)
{
    data = {"p1": func1(arg),
            "p2": func2(arg),
            "pN": funcN(arg)}
    return assemble(data);
}
</code>```

So in general, try to start with a empty hash map, and build out the structure by applying small functions to it until you build out your entire data set.

Or in a much cleaner way:

```<code>function reduce(fn, data, init)
{
   for (x = 0; x < data.length; x ++ 1)
       init = fn(init, data[x])
   return init
}
</code>```

Then simply:

```<code>function foo(arg)
{
    fns = [p1, p2, pN]
    data = reduce((l, f) -> f(l), fns, {})
    reduce assembleData(data)
}
</code>```

Using reduce you can also implement business rules with ease. Focus around data, and functional programming and you'll start to see how simple these things can really be.

Every day I spend close to 10 hours programming in both C# and Clojure, so I've seen both extremes and the functional approach simplifies things dramatically.

Perhaps a full real-world example would be in order?

Body:
I would suggest moving to a more functional programming style. The fact that you are talking about "calling in the wrong order" and showing functions that don't return data, this means that you are working with very impure functions.

The better approach is to work with pure functions:

1) Reject global state variables. They are bad. Enough said.

2) Every function should take arguments and return something.

3) Given the same arguments functions should output the same data.

When you follow these goals you will find that your code becomes much cleaner, functions can call other functions without fear of side-effects because functions are not allowed to mess with global state.

Now, in a web/gui app, you will have to modify global state at some point, in that case you can break the above rules in small fringe cases.

At this point, decomposing functions is extremely simple. You simply start taking logical parts in the code and breaking them into functions. When you find duplicated code, merge the functions into a single function. If you find yourself writing the same code over and over, then find a way to write that as a single function.

For instance, in a pseudo language, a for loop could be re-written as a map. So instead of this:

arr = [1, 2, 3, 4, 5]

for (x = 0; x < arr.length; x ++)
{
   arr[x] += 1
}

You could write a map function once:

function map(func, arr)
{
   out = []
   for (x = 0; x < arr.length; x ++)
   {
     out.add(func(arr[x]))
   }
   return out;
}

And in the future, instead of a for loop, you simply write:

function inc (x) { return x + 1; }

map(inc, [1 2 3 4])

So instead of a single-use-case imperative for-loop. Now you have 2 functions that you can reuse in thousands of places in your program.

Resources:

http://skilldrick.co.uk/2011/07/easy-functional-programming-in-javascript-with-underscore-js-part-1/

http://www.ibm.com/developerworks/library/wa-javascript/index.html

EDIT:

Update to address the OP's edits:

In your example, I suggest using maps in a situation like this. So in your example:

function foo(arg)
{
    data = {"p1": func1(arg),
            "p2": func2(arg),
            "pN": funcN(arg)}
    return assemble(data);
}

So in general, try to start with a empty hash map, and build out the structure by applying small functions to it until you build out your entire data set.

Or in a much cleaner way:

function reduce(fn, data, init)
{
   for (x = 0; x < data.length; x ++ 1)
       init = fn(init, data[x])
   return init
}

Then simply:

function foo(arg)
{
    fns = [p1, p2, pN]
    data = reduce((l, f) -> f(l), fns, {})
    reduce assembleData(data)
}

Using reduce you can also implement business rules with ease. Focus around data, and functional programming and you'll start to see how simple these things can really be.

Every day I spend close to 10 hours programming in both C# and Clojure, so I've seen both extremes and the functional approach simplifies things dramatically.

Perhaps a full real-world example would be in order?


答:
Keep each function as simple as possible.

Think of it in simple terms, the way a function is meant to be:

gets 0 to N inputs,

returns 0 or 1 result (possible a composite or collection),

and isn't tied to state.

When you stick to functional programming idioms, you get rid of most of these questions you're asking yourself. Sure, your class will get bigger in terms of number of functions. But if the methods are not tied to each by internal state changes, they get easier to understand, manage and compose to achieve an end result.

Also, try to give them appropriate accesses based on the above design decisions. Helpers will commonly easily be declared as statics (and if they don't seem to need to be private or can be reused, they could extracted to an helper class), which gives a strong hint to the other developers: this thing is meant to be independent and side-effect free.

Repeat the following mantras to aim for purity:

My function shall be:

short,

side-effects free,

realizing one and one function only.

My function shall be strict on output. [1]

My function shall be testable, and tested.

My function shall be readable and read like a natural language expression.

My function shall be documented. [2]

My function shall be null-hostile.

[1] Whether it shall be strict or lenient on input depends on whether it's consumer code or library code.

[2] Self-documentation counts, comments for tricky parts count as well.

Of course, if you are in a generally non-FP-oriented code base, you won't manage to avoid shared mutable state for ever, but it's a very good, sensitive and no-BS guideline to follow. Even if you do get it wrong by over-modularizing and complexifying your class, it'll still be easier to pick up from there and refactor again than from a giant dump of code with high complexity and tight coupling.

Regarding the rules of the compositionality of your functions, these are your business rules. They are dictated by what you want to achieve, there's no automagical way of determining it for you.

Title: When decomposing a large function, how can I avoid the complexity from the extra subfunctions?

Body:
Say I have a large function like the following:

```<code>function do_lots_of_stuff(){

    { //subpart 1
      ...
    }

    ...

    { //subpart N
      ...
    }
}
</code>```

a common pattern is to decompose it into subfunctions

```<code>function do_lots_of_stuff(){
    subpart_1(...)
    subpart_2(...)
    ...
    subpart_N(...)
}
</code>```

I usually find that decomposition has two main advantages:

The decomposed function becomes much smaller. This can help people read it without getting lost in the details.

Parameters have to be explicitly passed to the underlying subfunctions, instead of being implicitly available by just being in scope. This can help readability and modularity in some situations.

However, I also find that decomposition has some disadvantages:

There are no guarantees that the subfunctions "belong" to do_lots_of_stuff so there is nothing stopping someone from accidentally calling them from a wrong place.

A module's complexity grows quadratically with the number of functions we add to it. (There are more possible ways for things to call each other)

Therefore:

Are there useful convention or coding styles that help me balance the pros and cons of function decomposition or should I just use an editor with code folding and call it a day?

EDIT: This problem also applies to functional code (although in a less pressing manner). For example, in a functional setting we would have the subparts be returning values that are combined in the end and the decomposition problem of having lots of subfunctions being able to use each other is still present.

We can't always assume that the problem domain will be able to be modeled on just some small simple types with just a few highly orthogonal functions. There will always be complicated algorithms or long lists of business rules that we still want to correctly be able to deal with.

```<code>function do_lots_of_stuff(){
   p1 = subpart_1()
   p2 = subpart_2()
   pN = subpart_N()
   return assembleStuff(p1, p2, ..., pN)
}
</code>```


答:
More dynamic languages like javascript and python have the ability to declare functions inside of functions

```<code>function a(param1, param2) {
  function helperFunc1() {
    return param1 % param2 * param2
  }
  function helperFunc2(param3) {
    return (param1 - param2) * param3
  }
  return helperFunc1() + helperFunc2(2) - helperFunc2(1.5)
}
</code>```

These internal functions should have access to all vars inside the main function while hiding them from the outside, like a class would.

Body:
More dynamic languages like javascript and python have the ability to declare functions inside of functions

function a(param1, param2) {
  function helperFunc1() {
    return param1 % param2 * param2
  }
  function helperFunc2(param3) {
    return (param1 - param2) * param3
  }
  return helperFunc1() + helperFunc2(2) - helperFunc2(1.5)
}

These internal functions should have access to all vars inside the main function while hiding them from the outside, like a class would.


问:
Naming convention for iOS
I am learning Objective-C and iOS development and not sure what proper naming convention should be used. I understand how to use the label aspect of Obj-C methods but not the proper way to name each label. What is the best practice for naming methods, properties, objects, outlets, and actions?

Also,

Should different naming conventions be used between Obj-C code and C code? And if so what differences is there?

答:
Aside from the official Apple guidelines, this guide from Google of all places should help you. For future reference, use the words "idiomatic" and whatever language you need to find stuff.

In quick summary:

Names should be descriptive, not abbreviations, contain the proper prefixes (NS, AB, IB, etc) where applicable, unambiguous, non-self referential and PascalCase.

Title: Naming convention for iOS


问:
"UML is the worst thing to ever happen to MDD." Why?
William Cook in a tweet wrote that:

"UML is the worst thing to ever happen to MDD. Fortunately many people now realize this ..."

I would like to know the reasoning behind that claim (apparently, I'm not referring to his personal opinion).

I've noticed that many people out there don't like UML that much. Also it is worth mentioning that he is in academia, where UML is preety much the holy grail of effective design and modelling.

答: UML is the equivalent of taking a screwdriver and a hammer and taping them together and calling it a "Universal Fastening Tool." In theory it can be used to represent a ton of things in great detail, in practice its a bunch of poorly integrated tools claiming to be a single tool, that makes doing any one task far more difficult than having a proper tool to begin with.</p>


问:
What are the usual difficulties in concurrent programming and tuning of concurrent programs (shared-memory model)?
I can list part of the problems that will show up when writing a moderately-sized concurrent application with shared memory:

Locking granularity

Choice of synchronization primitive

Number of threads

Method for decomposing into threads (data parallelism; task parallelism; how threads are organized, etc)

What are other similar problems?

答:
The two most common problems in my experience of taking a class on the subject were the debugging of programs and the efficient distribution of resources.

Debugging a parallel program particularly on an independently managed thread system is astonishingly difficult. It's non-deterministic which means that your program may work 999 times out of a 1000 and that one time it fails just because something arrived in the wrong order or the thread manager didn't allocate correctly.

Atomicity errors are also common, this is why functional languages are becoming popular to handle concurrency as they wall off state (it's not that they don't have a state, it's that it's transparent).

The other big issue is communication. This falls into two categories: Resourcing and Time. Resourcing refers to often limited cache sizes and memory allocations for individual processes. Parallel systems often see use in data heavy applications, thus proper flow and packaging of that data is important. There's also the issue of dealing with the fact that there may not be a good algorithm that efficiently does what you want. Some tasks aren't not easily parallelizable and even if they are, the communication involved may render any speed gains moot. Time refers to the communication times between processors. This is less an issue in "multicore" systems than in distributed ones but it's still a problem.

You might ask why I'm talking about distributed systems at all. Well, some "shared memory" systems are actually distributed with particular facilities that make them function as shared memory.


答:
The thing I like the best is for the application to send an email to the user on the registered email-address with a one-time link valid for X hours which provides a "Change password" page.

The user can then set the password as s/he likes without risking having it put in an email.

Title: "Forgot Password" - How to handle this?


答:
Just because your functions can call each other a variety of ways doesn't mean they do. Your program's complexity isn't suddenly quadratic because you've named the blocks of code you ran before...

All of the other advice is good, but missing a key issue: you have a function doing a lot of stuff. Breaking that function into a series of function calls doesn't make it do less stuff, it just pushes the stuff around. Having a function that does too much is a sign that you have poorly abstracted your problem. Fix your abstraction so that the functionality is a better mapping to what you need to do and the function will naturally be less complex.


答:
I would suggest that the OP look at refactoring the problem and solution before starting to code.  If something is so complex that you start to worry about these issues, then you really need to jump outside of the box and look at the problem from a different angle.

Just for fun, Maybe you can create a DSL to solve your problem ^^


答:
If B can't do its job (which includes telling C pass/fail) then A isn't really giving it all of the information it needs, is it?

Either add the info, or make that no longer part of B's job.


答:
The last big problem I encountered was working around bottlenecks.  I had a lot of fields that were frequently referenced by many threads, and, with the program running flat out, I'd have CPU usage in the 8 to 10 percent range.  Hopefully your threads won't interfere with each other like that, but I spent a lot of time pausing my debugger and checking who was stuck where.  I ended up breaking up my lock/synchronized blocks to look at a minimum number of fields and working with local variables whenever possible.  (There are plenty of other reasons to stick with local variables.  This was just one more.)

I also ended up putting blocks of code in separate threads.  This might use up a bit of CPU in overhead, but I had 90 to 92 percent available.  The code in the separate thread didn't have to wait while it's parent thread waited on a lock and didn't hold up the parent thread while it waited on a lock.

And I went looking for data structures that were both thread-safe and thread-efficient.  That's how I found Java's ConcurrentSkipListMap.

Everything else here, as I write this, is more important, and maybe you won't get into quite the tangle of threads I did, but, as I say, this is where I ended up.  It's really just a rehash of the problems you listed, but faced after the decisions had supposed all been made and implemented.

Title: What are the usual difficulties in concurrent programming and tuning of concurrent programs (shared-memory model)?

Body:
I can list part of the problems that will show up when writing a moderately-sized concurrent application with shared memory:

Locking granularity

Choice of synchronization primitive

Number of threads

Method for decomposing into threads (data parallelism; task parallelism; how threads are organized, etc)

What are other similar problems?


问:
Looking for an example of how a software project can be managed/deployed
My company is evaluating adopting off-the-shelf ALM products to aid in our development lifecycle; we currently use our own homegrown solutions to manage requirements gathering, specification documentation, testing, etc. One of the issues I am having is understanding how to move code between stages of development. We have what we call a pipeline, which consists of particular stops:

[Source] -> [QC] -> [Production]

At the first stop, the developer works out a solution to some requested change and performs individual testing. When that process is complete (and peer review has been performed), our ALM system physically moves the affected programs from the [Source] runtime environment to the [QC] runtime environment. This movement of code is triggered by advancing the status of the change request to match the stage of the pipeline.

I have been searching the internet for a few days trying to find how the process is accomplished elsewhere -- I have read a bit about builds, automated testing, various ALM products, etc. but nowhere does any of this state how builds interact with initial change requests, what the triggers are, how dependencies are managed, how the various forms of testing are accommodated (e.g. unit testing, integration testing, regression testing), etc.

Can anyone point me to any resources detailing specific workflows or attempt to explain (generically) how a change could/should be tracked and moved though the development lifecycle? I'd be very appreciative.

Note: I've cleaned up the question to hopefully make it easier to understand. Also, I found another question (which I can't find now) that referenced this book, which sounds like it might be exactly what I am looking for -- not sure if I want to shell out the cash for it, though.

Additional details per @GlenH7's suggestion:

Our products are built with a proprietary language and set of translation tools -- the ultimately runtime environment is similar to a web site architecture, in that we have a bunch of 'code' files sitting out on a server, which our client app accesses on-demand (not unlike a GET request) and then interprets to provide the user experience. We sell an integrated product which is made up of a set of modules (most of which are optional), each module has a team of ~4 programmers and 2 QC testers devoted to the development/bug maintenance. There are around 30 modules per product line (and 3 product lines) -- some teams maintain multiple products lines for their given module. In total, we have 700 employees devoted to development and ~200 programmers. Certainly adopting any new processes or systems is going to involve buy-in, etc. but I'm tasked with simply understanding how the code will be managed so that we can speak intelligently about things. My first task was to learn how to adopt version control into our process (we do not yet use formal version control for most of our product lines, we rely instead of keeping around multiple copies of the entire codebase).

We follow the waterfall method pretty closely (which sucks, but the company has been producing software since 1969, so it was probably the natural fit back then and until now, there has been no need to change anything). Some folks are intrigued by the various offerings of the agile methodologies, but as has been noted by @Chad below, we're likely going to need to take incremental steps towards any such end goals (though if we adopt an ALM system, it might be the time to just force a whole new way to do things on everyone).

Now for a specific example of our current process, let's say we have a product called HIS, which has an MIS and ITS module (what these are/could be is not important -- think of them as just a collection of files) -- in our current process, if someone requests a change to ITS, a coder will modify some files (effectively) on the development server. When that change needs to be tested, transitioning the status of the change request from 'development needed' to 'qc needed' will trigger our tools to copy the affected files from the development server to the QC server. Now when QC testers signon to the QC testing environment, they will be able to see the effect of the changes. Once they signoff on the change, advancing the status of the request to 'production ready', our tools again copy the code files to the next stage. Once signed off there, a final copy is done to the holding location used for deliveries to customers.

We manage delivery of our releases by a major release number (e.g. 6.0) followed by a service release designation (e.g. 5) and a 'priority pack' number (e.g. 1) -- customers take delivery of priority packs, e.g. 6.0.5.1. As stated above, we simply push code from place to place on multiple servers, so we end up with a project folder for each major release and service release throughout the pipeline and end up with a final resting place for each of the ppacks, e.g.:

```<code>dev6.0
qc6.0
production6.0

dev6.0.5
qc6.0.5
production6.0.5

ship6.0.5.1
</code>```

I was thinking that under version control, we could simulate this kind of scheme as:

```<code>trunk
branches
--6.0.5
tags
--6.0.5.1
</code>```

but that seems to cover only half of the locations, i.e. where do the qc and production sources live? Would I create a separate trunk for each major and minor release of the product? Or would I rely on something outside of version control (e.g. the ALM system) to track the revision(s) interesting for testing done at the QC and production stops? We'd need a runtime environment for each, still, but that could be 'built' on-demand as bug fixes and features are made available -- which reinforces the idea that I need not keep any special 'copy' of these stages under version control (they are simply references to revision history of the trunk or branch).

Another thing that has thrown me for a loop as that a colleague is pretty adamant that you should not persist anything in branches, i.e. the branch folders should be ephemeral and used only during large changes that can't be committed directly to the trunk (with the expectation that the branch will eventually be merged into the trunk). In his scheme, the minor releases would necessitate a separate top-level with it's own set of trunk, branches and tags, e.g.:

```<code>product6.0
trunk
branches
--silly_new_feature
tags
--6.0.5

product6.0.5
trunk
branches
--crazy_bug_fix
tags
--6.0.5.1
</code>```

(sorry for the delay on adding these details -- got pulled away to meetings all day)

答:
Start here: Software Development Process

In particular, look at the Iterative approach and the Agile approach.  Also check out Unified Process for bonus reading.  UP gets a bad rap when folks think everything has to be included.  That's not the way it works - you only pick what you need from UP.

Then go here: Systems Development Life Cycle

Most of your questions should be answered from those two resources.

You'll want to make sure your ALM software has or can integrate with issues tracking as that's a critical component of SDLC.  Here's a handy comparison link, ymmv.

As far as QA doing its thing, what I've seen work best is this:  Dev has a feature that they work against.  Once the feature is "code complete," it's released to QA and is marked as "in test" or "done."  Bugs / issues can then be opened up against the feature that was released.  As the bugs are fixed, they too can go into "in test" or "done."  Feature ships when QA says its done or mgmt says it's good enough.

Update #1
I think your first priority is to decide what version control system you want to use.  For the environment you described, (almost) anything will be better than nothing.  Git and Mercurial are two very solid options to consider.  I'm not as familiar with Git, but to my understanding the feature-sets are very similar.

Hg Init

Joel on DVCS

SO conversation on DVCS

Next up, start looking into branching patterns and identify what's going to work best for your organization.

Atwood's thoughts

The SVN book off of red-bean is well worth the time to read through.

Your (D)VCS needs to be decided prior to your ALM software.  A fairly common pattern for your case would be to have branches / lines / (insert your term here) for dev, test, and prod releases.  You can additional additional lines based upon your major versions.  From your description, I think tags / equivalent within the main line for the version would be fine for your service releases and patches.  It can be a complicated setup, but given the number of developers and different activities you have going on, I think it will be required.

Your coworker is partially correct about branches, nowhere near enough correct to be adamant about it.  Some models only use branches for ephemeral work.  Generally, that only works with smaller shops that don't have multiple releases running at the same time.  You could appease him by having multiple trunks based upon versions, but that's a serious PITA.  Spolsky's Hg Init covers some basic patterns that address your situation including a workflow.

Mercurial (and by association git) is the closest (D)VCS that I've seen that replicates the release environment for a large development team.  Back in the day, we used a proprietary product that was release oriented and I've yet to find anything that truly recreates that.  Hg + some integrated bug tracking will put you well on the way to automating your release life cycle.

Start with Hg Init; research the other options; research branching patterns; revisit the Hg Init tutorial.  If nothing else, you'll have a boodle more terms to plug into SO and P.SE to continue your research with.

OwnerDisplayName: rguilbault


问:
"continue" and "break" for static analysis
I know there have been a number of discussions of whether break and continue should be considered harmful generally (with the bottom line being - more or less - that it depends; in some cases they enhance clarity and readability, but in other cases they do not).

Suppose a new project is starting development, with plans for nightly builds including a run through a static analyzer. Should it be part of the coding guidelines for the project to avoid (or strongly discourage) the use of continue and break, even if it can sacrifice a little readability and require excessive indentation? I'm most interested in how this applies to C code.

Essentially, can the use of these control operators significantly complicate the static analysis of the code possibly resulting in additional false negatives, that would otherwise register a potential fault if break or continue were not used?

(Of course a complete static analysis proving the correctness of an aribtrary program is an undecidable proposition, so please keep responses about any hands-on experience with this you have, and not on theoretical impossibilities)

Thanks in advance!

答:
I think this depends on exactly how the static analysis is being done.  For example, in Java many static analyses are done on Java bytecode, rather than on the Java source directly.  This simplifies many aspects of analysis because it uses unstructured control-flow (i.e. with conditional and unconditional branching).  Here, break and continue statements are compiled away into unconditional branches and so the analyzer doesn't even notice them.

However, if the static analysis is operating on source code directly, then break and continue statements may cause a loss of precision.  But, equally, they may not.


答: I like Dreamweaver as well because you can hand code it or do a small insert then clean up the code to give you the best of both worlds. The Built in ftp client is one of the nicer features. Have not used it since I changed everything to linux and sftp though.</p>


答:
To create an extreme loading condition

One use of the Unix yes application, which uses a similar loop construct, is to exercise the CPU to simulate high load.

It also provides a continuous "y" output for use with responses to older versions of Unix command lines.

I realise that the yes application is providing a measurable side-effect and so would not get optimised away, but the point I'm making is that fast, tight loops serve as useful load tests.

Title: Why are effect-less functions executed?


问:
Should a software developer get a yearly equipment budget?
I am looking at a new position with a new company.  I have talked to some people in the past (in general, not at this company) that they had been given a yearly budget to buy new computer stuff to keep up to date.

Now why I feel this question is worth asking here is that Joel comes right out and says an employer should pay for the best equipment money can buy... within reason of course.

From The Joel Test: 12 Steps to Better Code

9. Do you use the best tools money can buy?

Writing code in a compiled language is one of the last things that still can't be done instantly on a garden variety home computer...

Top notch development teams don't torture their programmers. Even minor frustrations caused by using underpowered tools add up, making programmers grumpy and unhappy. And a grumpy programmer is an unproductive programmer...

Does anyone know if the industry has such a standard to offer an allowance or budget?

I have never worked for a company like this, but I am thinking I should toss this in the ring for negotiations.  Seems reasonable.  How do bigger companies like MS, Google, and Apple handle this?  If you say yes, give a range... I have been told numbers from $5k to $10k.  Seems high to me, but hey I would gladly take it.

答:
I think a yearly budget is a waste of money -- equipment doesn't become obsolete that quickly.  I think it is better to upgrade when performance jumps ahead to where it is worth it to make the switch, for example when dual-core processors were replaced with quad or 6-core, when Windows 7 replaced Windows Vista and XP, when terabyte hard drives replaced 200 or 300 MB drives, and when SSD drives came out.  These were all significant improvements.

But after getting the latest and greatest desktop with some or all of the features mentioned above, it doesn't make any sense to spend another $5K the following year for an incremental improvement.

Also, I believe all developers in a group should be upgraded together, and also get the same equipment, since support will be easier that way.


问:
Fastest way to set up a JSON server on my local machine
I am a front-end developer. For many experiements I do I need to have a server that talks JSON with my client side app. Normally that server is a simple server that response to my POSTs and GETs.
For example I need to setup a server that saves, modifies and read data from a "library" database like this:

POST /books create a book

GET /book/:id gets a book

and so on...

What is the fastest to set up and easiest technology stack for database and server in this case? I am open to use Ruby, Nodejs and anything that do the job fast and easy.

Is there any framework (on any language) that do stuff like this for me?

答:
Yes, most languages have JSON bindings available.  Check out JSON.org; there's a fairly extensive list if you scroll down a few pages.

So you've basically got three problems here, and it's best to separate them into their own layers.

You need an HTTP server.  Just about any language has one.  Looks like you'll want to put some specific logic about parsing URLs into that layer.

You need a JSON layer that can create and read JSON. Your JSON library would go here.

You need business logic that defines and implements the API for your server.  That part's up to you.

In pretty much any modern language, HTTP server and JSON libraries will already be available for free.  Just take a look at the options.  So the real question is, which language would you be best at problem #3 in?  That's your answer.